查找AlertDialog的视图

8
我想从AlertDialog中获取一个View:
Button R = (Button) findViewById(R.id.toggleButtonA);

但是如果我这样做,它总是为空。我该怎么做才能获取并编辑视图?

以下是相关代码:

创建对话框的部分:

public void openSelection(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
    LayoutInflater inflater = this.getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.dialayout, null));
    AlertDialog dialog = builder.create();
    dialog.show();
}

The dialayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/toggleButtonA"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:onClick="select"
        android:text="All"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toggleButtonM" />


</android.support.constraint.ConstraintLayout>

</LinearLayout>

请发布您的XML文件... - Amit Upadhyay
@AmitUpadhyay 已添加所有相关内容,感谢提示! - newToEverything
2个回答

15

你需要先将充气的视图赋值给一个变量。例如:

public void openSelection(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    LayoutInflater inflater = this.getLayoutInflater();
    View v = inflater.inflate(R.layout.activity_main, null);  // this line
    builder.setView(v);
    AlertDialog dialog = builder.create();
    dialog.show();

    Button RR = (Button) v.findViewById(R.id.toggleButtonA); // this is how you get a view of the button
}

请将您的按钮变量名称R重新命名为其他名称,因为R是一个保留字。


我已经接近成功了,但这让一切都恰到好处。谢谢! - Jeff.H
View v = inflater.inflate(R.layout.activity_main, null); 会产生一个警告。使用 View.inflate(..., null, false) 只是隐藏了警告,但并没有解决问题。正确的方法是使用 builder.setView(R.layout.edit_account_dialog); dialog = builder.create(); 但是只有在活动调用 dialog.show() 后才能使用 findViewById;这又引起了另一个问题:对话框的 findViewByIdshow() 之前不可用,而在 show() 之后也不容易调用。顺便说一下,在 dialog.show() 后立即在活动中调用 findViewById 不是一个好的做法。 - JarsOfJam-Scheduler

2

首先膨胀父布局,

 LayoutInflater inflater = this.getLayoutInflater();
View parent = inflater.inflate(R.layout.activity_main, null);

然后将您的构建器设置为该父视图。builder.setView(parent);

接下来,您可以使用该父充气视图执行任何视图查找。或者您可以调用 AlertDialog diag = builder.create(); 并使用 diag.findViewById(R.id.name); 进行查找。

因此,Button btR = (Button) diag.findViewById(R.id.toggleButtonA);

或者 Button btR = (Button) parent.findViewById(R.id.toggleButtonA);


将你的变量从像R这样的特殊关键字重命名,但不要使用R。 - Remario
感谢您提供详细的问题和答案,对我非常有帮助。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接