【问题标题】:App crashes when using onClickListener in onCreateDialog [closed]在 onCreateDialog 中使用 onClickListener 时应用程序崩溃 [关闭]
【发布时间】:2016-05-16 17:13:11
【问题描述】:

我正在尝试在警报对话框中使用 XML 中的按钮,但当 Activity 尝试加载时应用程序崩溃。

package dtt.bob.rsrpechhulp;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

public class CallWindow extends DialogFragment implements View.OnClickListener{
LayoutInflater inflater;
View v;

@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Button annuleren = (Button) v.findViewById(R.id.annuleren); //here is the problem I assume
    annuleren.setOnClickListener(this);

    inflater = getActivity().getLayoutInflater();
    v = inflater.inflate(R.layout.call, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);
    return builder.create();
}

public void onClick(View v) {
    switch(v.getId()){
        case R.id.annuleren:
            annulerenClick();
            break;
    }
}

//annuleren
private void annulerenClick(){
    dismiss();
}

关于如何解决这个问题的任何想法?我在其他活动中使用过 onClickListener,但它们在 onCreate 方法中,而不是在 onCreateDialog 方法中。

【问题讨论】:

标签: java android android-studio


【解决方案1】:

您正在尝试在对象 v(View) 膨胀之前调用 findViewById(...)。
我假设您收到导致崩溃的 NullPointerException。
查看此链接 - http://www.mkyong.com/android/android-custom-dialog-example/ 了解更多信息。

【讨论】:

  • 是的,我不聪明,谢谢你的帮助
【解决方案2】:

您试图在实例化 View v 之前找到按钮 id.....

首先实例化你的充气器和 View 对象,然后是你的按钮。

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        inflater = getActivity().getLayoutInflater();
        v = inflater.inflate(R.layout.call, null);
        Button annuleren = (Button) v.findViewById(R.id.annuleren); //here is the problem I assume
        annuleren.setOnClickListener(this);


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(v);
        return builder.create();
    }

【讨论】:

  • 谢谢老兄,成功了!
猜你喜欢
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多