setContentView使用扩展视图类

时间:2013-12-11 07:53:24

标签: android

我正在使用扩展视图来设置活动的内容。正在发生的事情是显示空白活动。而不是设置文本。

public class ThreadCheck extends Activity{
        MyView view;
        /* (non-Javadoc)
         * @see android.app.Activity#onCreate(android.os.Bundle)
         */
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            Context ctx = getApplicationContext();
            view=new MyView(ctx);
            setContentView(view);
        }
    }

public class MyView extends View{
            TextView tvThread;
            public MyView(Context context) {
                super(context);
                tvThread=new TextView(context);
                tvThread.setText("Hello This Is Myview");
                // TODO Auto-generated constructor stub
            }

        }

1 个答案:

答案 0 :(得分:2)

更改此

view=new MyView(ctx);

view=new MyView(ThreadCheck.this);

并改为

   public class MyView extends TextView{

    public MyView(Context context) {
        super(context);
        this.setText("Hello This Is Myview");
    }

}

编辑:评论中的问题。您需要一个添加视图的ViewGroup。

public class MyView extends RelativeLayout{

        public MyView(Context context) {
            super(context);


            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            this.setLayoutParams(layoutParams);

            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            TextView tv = new TextView(context);
            tv.setText("hello");
            tv.setId(1);

            Button b = new Button(context);
            params1.addRule(RelativeLayout.BELOW, tv.getId());
            b.setText("Hi");
            b.setId(2);

            this.addView(tv);
            this.addView(b, params1);

        }
    }