【问题标题】:Android Input Dialog Box's Onclick doesn't workAndroid 输入对话框的 Onclick 不起作用
【发布时间】:2013-12-15 07:19:06
【问题描述】:

所以我是 Android 编程新手,所以如果这是初学者的错误,我深表歉意,但我正在编程我的按钮以将用户添加到具有对话框中给出的名称的数组列表中。当我运行它时,一切正常,除非它执行 users.add(new User(name)); (它返回一个空指针我不确定为什么会这样。任何帮助将不胜感激。这是我的代码。

addPersonButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        final EditText input = new EditText(mainActivity);

        new AlertDialog.Builder(mainActivity)
            .setTitle("New User")
            .setMessage("What is the new user's name?")
            .setView(input)
            .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    final String name = input.getText().toString();
                    users.add(new User(name));
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Do nothing.
                }
            }).show();
    }
});

【问题讨论】:

  • 你在哪里初始化了用户?

标签: java android user-interface


【解决方案1】:

我认为您的问题在于onClick 方法中的input,并且因为您的dialog layout 中的input 不在main layout 中,所以您必须使用以下代码:

    final String name = dialog.input.getText().toString();
    users.add(new User(name));

【讨论】:

    【解决方案2】:

    在xml中创建edittext并使用findViewById(R.id.edittext);

    或者在java中

    final EditText input = new EditText(MainActivity.this);
    

    参考here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2015-02-22
      • 1970-01-01
      相关资源
      最近更新 更多