在Android中动态地向LinearLayout添加按钮

4

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

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); 


    }
}

1
请使用“adb logcat”获取应用程序的正确堆栈跟踪(它位于已安装的Android SDK中的platform-tools文件夹中)。 - thoredge
3个回答

2
尝试这样做:

像这样尝试:

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

我会膨胀,但我认为从代码中添加不是最佳实践。 - Mike

1

只有当linearLayout为空时才会出现错误,请确保layout1是R.layout.main的有效项


0
在您的自定义活动类中尝试以下操作:
this.addContentView(call,
    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接