Подтвердить что ты не робот

Как получить название AlertDialog?

Я попытался получить сообщение, и следующая строка кода работает:

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

Но когда я пытаюсь получить заголовок, используя следующую строку, он возвращает null

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

Ответ 1

Я проверил код 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) {

   }
}

Ответ 2

Я знаю, что вопрос упоминает AlertDialog, но если вы пришли сюда через поиск в Google и искали ответ для DialogFragment:

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

Ответ 3

Я знаю, что это старый пост, но я использовал принятый ответ и добавил что-то еще полезное для меня. Вы можете сделать заголовок Dialog многострочным (по умолчанию 1 строка), используя код ниже. Я также прочитал заданный заголовок, потому что позже я добавил txt асинхронно с помощью ContentLoaders

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);
            }
        }

Ответ 4

Вы можете реализовать это самостоятельно. Создайте свой собственный класс, который расширяет 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();

    }
}

Ответ 5

Чтобы избежать взлома кода, когда Google решит изменить идентификатор представления заголовка диалога в будущем, здесь есть более надежное решение.

Мы просто вернем первый встреченный View, тип которого TextView.

//
// 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;
}