gpt4 book ai didi

android - 来自 AlertDialog 的 findViewById(使用自定义布局)- NullPointerException

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:08 32 4
gpt4 key购买 nike

我正在尝试从 AlertDialog 中的 EditTexts 中获取文本,它的创建如下所示。问题是,我无法检索 TextView 。我得到的只是一个空值。有任何想法吗?

    final EditText editFirstname = (EditText) findViewById(R.id.editFirstname);
final EditText editLastname = (EditText) findViewById(R.id.editLastname);

bttAddPlayer.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);

LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
builder.setView(layoutInflater.inflate(R.layout.dialog_add_player, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
databaseHelper.addPlayer(editFirstname.getText().toString(),editLastname.getText().toString());
playerAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}

最佳答案

您需要在您为 Alert 对话框扩充的 View 中搜索,假设您扩充的 View 如下:

    View view = inflater.inflate(R.layout.dialog_add_player, container);

那么你需要做

EditText editFirstName = (EditText) view.findViewById(R.id.editFirstName);
EditText editLastName = (EditText) view.findViewById(R.id.editLastName);

看起来你现在正试图为不存在的东西实例化一个变量,你没有引用 EditText 的实际位置,它试图查看当前 View 的内部,其中不包含 EditText

关于android - 来自 AlertDialog 的 findViewById(使用自定义布局)- NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24498182/

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