我正在尝试在对话框中创建动态按钮,我可以在对话框外创建它,但无法创建内部对话框。
cust.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
custom = new Dialog(MyActivity.this);
custom.requestWindowFeature(Window.FEATURE_NO_TITLE);
custom.setContentView(R.layout.hor);
custom.show();
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.content1);
Button btn[] = new Button[20];
for( int i=0;i<10;i++)
{
btn[i] = new Button(MyActivity.this);
btn[i].setText("Button " + i);
linearLayout.addView(btn[i]);
}
}
});`
获取错误:linearLayout.addView(btn [i]);
02-22 00:51:17.919 5437-5437/com.example.DialogTry E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.DialogTry.MyActivity$1.onClick(MyActivity.java:135)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17446)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
更改此行 -
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.content1);
到此 -
LinearLayout linearLayout = (LinearLayout) custom.findViewById(R.id.content1);