爲什麼setOnClickListener給出以下錯誤? MainActivity.java的錯誤在自定義對話框
java.lang.NullPointerException
com.example.MainActivity.onClick(MainActivity.java:206)
android.view.View.performClick(View.java:4240)
android.view.View$PerformClick.run(View.java:17721)
.
.
.
代碼:CustomDialogClass.java的
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View color=findViewById(R.id.vie);
color.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
if(arg0.getId()==R.id.vie){
final CustomDialogClass cdc=new CustomDialogClass(this);
View dialogButton = cdc.findViewById(R.id.view3);
//**** the blow code that is in Block comment give an error****
/* dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
cdc.dismiss();
}
}); */
cdc.show();
}
}
}
代碼:
public class CustomDialogClass extends Dialog {
public Activity c;
public Dialog d;
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog);
setTitle("select");
}
}
和custom_dialog.xml是:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="40dp"
android:gravity="center" >
<View
android:id="@+id/view3"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#24b5ed" />
</RelativeLayout>
能
人告訴我我做錯了什麼?
What's line MainActivity.java:206? – 2014-09-05 07:02:16
對話框類的onCreate()方法只在'Dialog.show()'後調用。該對話框沒有View來查找其他視圖。 – user3811368 2014-09-05 07:06:02
我刪除了不必要的代碼! – user3824114 2014-09-05 07:06:53