在Android中动态添加Button到LinearLayout

时间:2011-04-12 07:40:24

标签: java android button dynamic

我正在开发一个需要动态添加按钮的项目。但每当我运行我的应用程序时,应用程序强制关闭我已经了解到问题是当我尝试添加按钮时。

package com.Feras.TestProject;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class TestProject extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    AddAll();
    // Set Text for the button in the Old Testament



}
public void AddAll() {
    LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout1);
    Button btn = new Button(this); 
    btn.setText("MyButton"); 
    linearLayout.addView(btn); 


    }
}

3 个答案:

答案 0 :(得分:2)

尝试这样:

linearLayout.addView(
                     btn, 
                     new LayoutParams(
                          LayoutParams.WRAP_CONTENT, 
                          LayoutParams.WRAP_CONTENT)
                     );

答案 1 :(得分:1)

如果linearLayout为null,则只会发生错误,请确保layout1是R.layout.main的有效项

答案 2 :(得分:0)

在自定义活动类中尝试以下操作:

this.addContentView(call,
    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));