1

嘿,伙计们需要一点帮助........我的目的是开发一个只包含一个按钮的应用程序......点击它必须在屏幕上动态创建另一个按钮......

这是我的代码...

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Button bee=new Button(getBaseContext());
            bee.setText("hello:");
             RelativeLayout a;
            a=(RelativeLayout)findViewById(R.layout.activity_main);
    a.addView(bee,new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        }
    });

此代码没有错误,但执行时显示“不幸的是 'myapplication' 已停止”....

请帮帮家伙..(我的唯一目标是动态创建小部件,因此尝试了 dis 程序)。如果您有任何其他建议,请发表评论

4

5 回答 5

1
 a=(RelativeLayout)findViewById(R.layout.activity_main);

activity_main 是一个布局,而不是一个 RelativeLayout 小部件!

你应该使用

 a=(RelativeLayout)findViewById(R.id.my_relative_layout);

请发布堆栈跟踪(logcat),以便您获得更好更快的答案。

于 2012-11-02T09:50:58.990 回答
0

您正在查找 id 而不是 layout

所以改变这一行:

a=(RelativeLayout)findViewById(R.id.activity_main); 
于 2012-11-02T09:53:31.747 回答
0

试试这个代码我认为你只是因为没有正确设置参数而遇到问题所以检查这个代码 -

 LinearLayout container = (LinearLayout)findViewById(R.id.container);

    Button btn = new Button(this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.MATCH_PARENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT);
    btn.setLayoutParams(lp);

    container.addView(btn);
于 2012-11-02T09:54:45.553 回答
0

您正试图“找到”一个不存在的布局!请确保您已RealtiveLayout使用有效 id 定义 a 然后执行

a=(RelativeLayout)findViewById(R.id.valid_layout_id);

代替

a=(RelativeLayout)findViewById(R.layout.activity_main);

于 2012-11-02T09:52:23.457 回答
0

尝试这个。

RelativeLayout rLayout = (RelativeLayout )findViewById(R.id.relativeLayout); // Here this should be id of your relative layout.
Button btn = new Button(this);
rLayout.addView(btn);
于 2012-11-02T09:52:27.857 回答