Android scrollview не может быть создан программно.

#android #scrollview

#Android #scrollview

Вопрос:

Я хочу использовать scrollview в своем приложении. Я попытался добавить текстовый вид в scrollview, но я не вижу ничего отображаемого, кроме цвета фона вида прокрутки.

вот как я это сделал:

 public class MyView extends ViewGroup
{
    ScrollView myScrollview;
        Textview tv;

        public MyView(Context context) { 
        myScrollView = new ScrollView(context);
        myScrollView.setBackgroundColor(0xfff00fff);

        textview=new TextView(context);

        textview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
                textview.setLayoutParams(params)
        textview.setText("sadfasdfasdfasdfasdfasdfasdfsadfsadf");

        textview.layout(0, 0, 1000, 2000);
        textview.setHeight(5000);
        textview.setWidth(3200);
                myScrollView .addView(tv);
                addView(myScrollview);
        }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // TODO Auto-generated method stub

        int width = r-l;
        int height =b-t;

        myScrollView .layout(0, 0, width, height-100);
    }
}
  

Я обнаружил, что почти все учебные пособия по scrollview используют xml для определения представления. Но я хочу сделать это программным способом. Но в любом случае, я также пробовал xml.

Я скопировал XML Ромена Гая отсюда для тестирования:http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/

XML scrollview сам по себе является правильным, если я создам этот scrollview и добавлю его в действие, используя

 scrollview= (ScrollView)  getLayoutInflater().inflate(R.layout.scrollviewid,null);
  

setContentView (scrollview);

или setContentView(R.layout.scrollviewid);

это сработало. Однако, если я хочу сделать scrollview дочерним видом какого-либо другого вида, я снова мог видеть только фон scrollview. внутри ничего не отображается:

      public class MyView extends ViewGroup
{
   ScrollView myScrollview;

    public MyView(Activity activity,Context context) 
    {
            super(context);

    myScrollview= (ScrollView)  activity.getLayoutInflater().inflate(R.layout.restaurantcategoryselectorviewlayout,null);
    myScrollview.setBackgroundColor(0xfff00fff);

    addView(myScrollview);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    // TODO Auto-generated method stub

    int width = r-l;
    int height =b-t;

    myScrollview.layout(0, 0, width, height-100);
}
}
  

Что не так с моим кодом? Есть ли какой-либо пример создания scrollview с помощью program, а не xml?

Кроме того, являются ли эти исходные коды Java для Android также на kernel.org ? поскольку служба git не работает, где я могу загрузить исходный код Android?

Ответ №1:

Когда вы программно создаете ScrollView внутри него, вам нужно создать View , а затем добавить ScrollView внутри этого View .

 LinearLayout maincontainer = (LinearLayout) findViewById(R.id.weatherInfo);
maincontainer.setOrientation(LinearLayout.HORIZONTAL);

final HorizontalScrollView scrollView = new HorizontalScrollView(getApplicationContext());
maincontainer.addView(scrollView);

final LinearLayout linearLayout = new LinearLayout(getApplicationContext());
linearLayout.setOrientation(LinearLayout.HORIZONTAL);

scrollView.addView(linearLayout);
  

Ответ №2:

Я не понимаю, что не так с вашей ViewGroup, но, похоже, в этом и заключается проблема. Если я возьму ваш код, отлажу его (в коде, опубликованном выше, есть несколько ошибок) и добавлю его в начальный код для простого действия, тогда он будет работать так, как ожидалось. Он создает текстовую область прокрутки с вашим тестовым текстом.

Вот этот код. Обратите внимание, что ожидается, что файл макета будет содержать простой линейный макет с идентификатором linearLayout1 :

 public class ListTestActivity extends Activity {
LinearLayout layout;
ScrollView myScrollView;
TextView textview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    layout = (LinearLayout) this.findViewById(R.id.linearLayout1);

    myScrollView = new ScrollView(this);
    myScrollView.setBackgroundColor(0xfff00fff);
    myScrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));


    textview = new TextView(this);
    textview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
    textview.setText("sadfasdfasdfasdfasdfasd fasdfsadfsadf");

    myScrollView.addView(textview);
    layout.addView(myScrollView);
}}