如何以编程方式创建滚动视图?

时间:2012-12-14 12:53:45

标签: android widget

我想以编程方式在其中创建带有文本视图的滚动视图。我的代码如下。它可以工作,但是当我在onSizeChanged中执行getLayoutParams时,我得到InvocationTargetException。我的代码出了什么问题?

public MyActivity extends Activity 
  {
    public void onCreate(Bundle savedInstanceState) 
    {       
        super.onCreate(savedInstanceState);
        setContentView(new MyLayout(this));
    }
    protected class MyLayout extends RelativeLayout 
     {
        TextView tv;
        public MyLayout(Context context)
        {
           super(context);
           ScrollView sv = ScrollView(context);
           tv = new TextView(context);
           tv.setText("Hello World");
           sv.addView(tv);
           addView(sv);
        }
        protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld)
        {
            LayoutParams params = (LayoutParams)tv.getLayoutParams(); // I have          InvocationTargetException here. What's wrong?
        }   
    }
}

3 个答案:

答案 0 :(得分:0)

你应该在TextView中加入一些文字,所以:

public MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {       
        super.onCreate(savedInstanceState);
        setContentView(new MyLayout(this));
    }
    protected class MyLayout extends RelativeLayout {
    public MyLayout(Context context) {
        super(context);
        ScrollView sv = new ScrollView(context);
        TextView tv = new TextView(context);
        tv.setText("Hello World");
        sv.addView(tv);
        addView(sv);
    }
}
}

答案 1 :(得分:0)

您需要为LayoutParams添加View - ScrollViewTextView。并使用正确的类型(两者都为FrameLayout.LayoutParams)。

E.g。

...
tv = new TextView(context);
tv.setText("Hello World");
sv.addView(tv, new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
...

答案 2 :(得分:0)

scrollview不应该使用wrap_content而是fill_parent。