如何获取AlertDialog的标题?

19

我试着获取消息,以下代码行可以实现:

TextView dialogMessage = (TextView)dialogObject.findViewById(android.R.id.message);

但是当我尝试使用以下代码获取标题时,它会返回null

TextView dialogTitle = (TextView)dialogObject.findViewById(android.R.id.tittle);

id 是 alertTitle,我不确定它在外部是否可见。请尝试使用 android.R.id.alertTitle - Blackbelt
2
没有id alertTitle - alitha
5个回答

40

我查看了AlertDialog的代码。在内部,他们使用R.id.alertTitle来初始化AlertDialog标题的TextView。您可以使用getIdentifier来检索它:

int titleId = getResources().getIdentifier( "alertTitle", "id", "android" );
if (titleId > 0) {
   TextView dialogTitle = (TextView) dialogObject.findViewById(titleId);
   if (dialogTitle != null) {

   }
}

编辑:对于AppCompatgetIdentifier的第三个参数应该是您应用程序的包名。 您可以使用context.getPackageName()检索后者。


2
尽管有人说这不可能,但这是一个很好的答案。你应该得到黑带,非常感谢。 - smoothumut
6
对于 AppCompat AlertDialog,您应该使用 getResources().getIdentifier("alertTitle", "id", "your.package.name")。 - Sergei Belozerov
1
@Blackbelt的答案应该加上Sergei Belozerov的注释。 - Karol Kulbaka
1
@doctorram的回答是在2015年的。这真的取决于您正在导入哪个警报对话框。当时还没有像支持库中那样的花哨的警报对话框。 - Blackbelt
1
@黑带,不管花哨不花哨,现在的解决方案是什么?这个解决方案已经不再起作用了。 - doctorram
显示剩余6条评论

3
为了避免代码在将来谷歌更改其对话框标题视图ID时出现错误,这里提供了更可靠的解决方案。
我们将简单地返回遇到的第一个类型为 TextView 的 View,以避免代码出错。
//
// Usage: findFirstEncounteredType(getDialog().getWindow().getDecorView(), TextView.class)
//
public static View findFirstEncounteredType(View view, Class<? extends View> klass) {
    if (klass.isInstance(view)) {
        return view;
    } else {
        if (!(view instanceof ViewGroup)) {
            return null;
        }
    }

    ViewGroup viewGroup = (ViewGroup)view;

    for (int i=0, ei=viewGroup.getChildCount(); i<ei; i++) {
        View child = viewGroup.getChildAt(i);
        View result = findFirstEncounteredType(child, klass);
        if (result != null) {
            return result;
        }
    }

    return null;
}

应该是最佳答案。 - Anton A.
找不到任何TextView! - doctorram
直到我调用了dialog.show()后进行搜索,才找到任何TextView。 - EstevaoLuis

2

我知道这个问题提到了AlertDialog,但如果你是通过Google搜索并寻找DialogFragment的答案:

getDialog().findViewById(android.R.id.title))

0
你可以自行实现。创建自己的类,扩展android.app.AlertDialog.Builder。然后创建一个变量来存储您使用方法setTitle()后的值。
import android.content.Context;
import android.support.annotation.StringRes;

public class AlertDialog extends android.app.AlertDialog.Builder {

    private Context context;
    private String title;

    public AlertDialog(Context context) {
        super(context);
        this.context = context;
    }

    public AlertDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
    }

    /**
     * Set title using string
     */
    @Override
    public AlertDialog setTitle(CharSequence title) {

        // set the title
        this.title = title.toString();

        super.setTitle(title);
        return this;
    }

    /**
     * Set title using resource string
     */
    @Override
    public AlertDialog setTitle(@StringRes int titleId) {

        this.title = this.context.getText(titleId).toString();

        super.setTitle(titleId);
        return this;
    }

    // create public method
    public String getTitle(){
        return this.title;
    }
}

然后你可以将它用作普通的AlertDialog,使用已实现的方法获取其标题。然后你可以进行测试:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Crete new alert dialog
        AlertDialog dialog = new AlertDialog(this);
        dialog.setMessage("Type some message here :D");
        dialog.setTitle(R.string.settings_title);           // string resource
        dialog.setTitle("Dialog1 title");                   // string
        dialog.show();

        // Crete secondary dialog with same title
        // using getTitle() method
        new AlertDialog(this)
                .setTitle(dialog.getTitle())
                .setMessage("Copy title from first dialog.")
                .show();

    }
}

-1

我知道这是一个旧帖子,但我使用了被接受的答案并添加了对我有用的其他内容。您可以使用下面的代码使对话框标题多行(默认为1行)。我还读取了预设标题,因为我稍后使用ContentLoaders异步添加了txt。

int titleId = getResources().getIdentifier( "alertTitle", "id", "android" );
        if (titleId > 0) {
            TextView dialogTitle = (TextView) getDialog().findViewById(titleId);
            if (dialogTitle != null) {
                dialogTitle.setMaxLines(4);
                dialogTitle.setSingleLine(false);
                String txt = dialogTitle.getText().toString();
                String txt1 = txt + ":\n\n" + "next line txt";
                dialogTitle.setText(txt1);
            }
        }

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