gpt4 book ai didi

java - android - 动态添加按钮到自定义对话框

转载 作者:行者123 更新时间:2023-12-02 11:22:57 25 4
gpt4 key购买 nike

我正在编写一个Android应用程序,我有一个 Activity ,里面有一个按钮,它在单击监听器上使用以下代码从自定义 XML 打开一个对话框:

我想向该对话框添加另一个未在其 XML 文件中设置的按钮。

所有组件都在 XML 中删除并且工作正常,对话框打开,但我无法添加 b 按钮。

this.addCheer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog d = new Dialog(map.this);
LinearLayout layout = findViewById(R.id.dialog_layout_root);
LayoutInflater layoutInflater = d.getLayoutInflater();
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.cheer_dialog);// custom layout for the dialog
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
d.show();
d.getWindow().setAttributes(lp);
final EditText title = d.findViewById(R.id.cheerDialogText);

ImageButton addCheerOk = (ImageButton) d.findViewById(R.id.addCheerOk);

Button b = new Button(d.getContext());
b.setText("yo");

cheerDialogLayout.addView(b, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
}

我尝试使用 this例如,但它对我不起作用。我在这里做错了什么?谢谢!

最佳答案

试试下面的代码

this.addCheer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog d = new Dialog(map.this);
LayoutInflater layoutInflater = d.getLayoutInflater();
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.cheer_dialog);// custom layout for the dialog

WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
d.show();
d.getWindow().setAttributes(lp);

LinearLayout layout = d.findViewById(R.id.dialog_layout_root);
final EditText title = d.findViewById(R.id.cheerDialogText);

ImageButton addCheerOk = (ImageButton) d.findViewById(R.id.addCheerOk);

Button b = new Button(d.getContext());
b.setText("yo");

layout.addView(b, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
}

您仅使用 findViewById(R.id.dialog_layout_root); 而不是 d.findViewById(R.id.dialog_layout_root);

关于java - android - 动态添加按钮到自定义对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49796413/

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