gpt4 book ai didi

java - 带有自定义布局按钮的警报对话框

转载 作者:行者123 更新时间:2023-12-01 12:01:03 25 4
gpt4 key购买 nike

我有一个警报对话框的布局。并且有一个调用时间选择器的按钮。但我不知道如何编写按钮的setonClickListener。它总是崩溃。

致命异常:主要

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at prototype.feedme.cat.prototype.activity.CatActivity$3.onClick(CatActivity.java:115)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

代码:

private Button time;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CatActivity);
time=(Button)findViewById(R.id.time);
time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog tpd=new TimePickerDialog(CatActivity.this, mTimesetlistener, mHour, mMinute, true);
tpd.show();
}
});
clk_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog alertDialog=new AlertDialog.Builder(CatActivity.this)
.setTitle("Hi")
.setMessage("Are you ok?")
.setView(R.layout.notificaton_setting)
.show();
}
});
}

最佳答案

您说该按钮位于对话框内。但你试图在 Activity 中找到它。我的意思是,在您尝试显示对话框之前,根本没有按钮,您尝试从 Activity onCreate 方法中找到它。

您需要做的是在对话框 View 中找到您的按钮。你可以这样做:

LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.notificaton_setting, null);
dialogLayout.findViewById(R.id.time).setOnClickListener(...)

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialoglayout);
builder.show();

关于java - 带有自定义布局按钮的警报对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27979791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com