0

我想以编程方式在其中创建带有文本视图的滚动视图。我的代码如下所示。它有效,但是当我在 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?
        }   
    }
}
4

3 回答 3

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);
    }
}
}
于 2012-12-14T12:59:30.257 回答
0

您需要LayoutParamsViews - theScrollViewTextView. 并使用正确的类型(FrameLayout.LayoutParams两者)。

例如

...
tv = new TextView(context);
tv.setText("Hello World");
sv.addView(tv, new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
...
于 2012-12-14T13:00:35.470 回答
0

滚动视图不应使用 wrap_content 而是使用 fill_parent。

于 2012-12-14T13:03:17.697 回答