Java 在Android中将按钮动态添加到LinearLayout
我正在做一个需要动态添加按钮的项目。但每当我运行应用程序时,应用程序强制关闭。我了解到问题是当我尝试添加按钮时Java 在Android中将按钮动态添加到LinearLayout,java,android,button,dynamic,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; impo
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);
}
}
只有当linearLayout为null时才会发生错误,请确保layout1是R.layout的有效项。main请尝试以下操作:
linearLayout.addView(
btn,
new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT)
);
在自定义活动类中尝试以下操作:
this.addContentView(call,
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
请使用“adb logcat”获取应用程序的正确堆栈跟踪(它位于已安装的Android SDk中的platform tools文件夹中)。我会夸大,我不认为从代码添加是最佳做法