Я не могу понять, как изменить размер текста на кнопках во всплывающем окне диалога EditTextPreference. Я хотел бы, чтобы весь мой текст в моем приложении был оптимизирован на 24 sp. Это происходит везде, кроме этого диалогового окна с PreferenceScreen. Как вы можете видеть в ListPreference, я разобрался, как скрыть positiveButtonText и absoluteButtonText.
Я хотел бы сделать это в XML, если это возможно. Я также хотел бы избежать создания собственного диалогового макета. В тэге EditTextPreference я могу редактировать заголовок и макет в диалоге, я просто не могу понять, как "дотронуться" до кнопок по умолчанию.
Вот мой pref_connection.xml:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Connection">
<ListPreference
android:defaultValue="box1"
android:entries="@array/pref_box_type_list_titles"
android:entryValues="@array/pref_box_type_list_values"
android:key="box_types_list"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:layout="@layout/preference_screen_layout"
android:title="@string/pref_title_box_type"/>
<EditTextPreference
android:defaultValue="@string/pref_default_internet_addr"
android:digits="0123456789."
android:inputType="number|numberDecimal"
android:key="internet_addr"
android:selectAllOnFocus="true"
android:singleLine="true"
android:layout="@layout/preference_screen_layout"
android:textSize="@dimen/text_size"
android:title="@string/pref_title_internet_addr"/>
<...>
</PreferenceScreen>
Вот макет:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@android:id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/large_margin"
android:paddingBottom="@dimen/margin"
android:textSize="@dimen/text_size"/>
<TextView android:id="@android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/large_margin"
android:textSize="@dimen/text_size"/>
</LinearLayout>
Хотелось бы сделать что-то простое, например стили:
<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:textSize">24sp</item>
</style>
или используйте dialogLayout внутри EditTextPreference:
android:dialogLayout="@layout/dialogLayout"
Но, похоже, никто из них не работает.
Надеюсь, что скриншоты моего приложения помогут понять, чего я пытаюсь достичь.
Это показывает мой экран предпочтений на левой стороне.
Это показывает диалоговое окно, которое появляется после нажатия EditTextPreference. Размер текста на кнопках отмены и ОК - вот что я пытаюсь изменить. Смотри красные стрелки. Другой текст в этом диалоговом окне управляется атрибутами в EditTextPreference.
Любая помощь будет принята с благодарностью.
Я обнаружил правильные параметры стиля для использования:
Определения AppTheme:
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:editTextPreferenceStyle">@style/DialogPreferenceStyle</item>
</style>
<style name="DialogPreferenceStyle" parent="Preference.DialogPreference.EditTextPreference">
<item name="android:positiveButtonText">TEST TEXT</item>
</style>
Скриншот:
Как вы можете видеть на скриншоте, я могу изменить текст кнопки, но не могу изменить размер текста.
Observations:
Посмотрев на исходный код DialogPreference
который является суперклассом EditTextPreference
, мы увидим, что нет никаких атрибутов для размера текста кнопки. Это означает, что невозможно изменить размер текста кнопок от style
и xml
обычном режиме.
DialogPreference.java
public DialogPreference( Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); final TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DialogPreference, defStyleAttr, defStyleRes); mDialogTitle = a.getString(com.android.internal.R.styleable.DialogPreference_dialogTitle); if (mDialogTitle == null) { // Fallback on the regular title of the preference // (the one that is seen in the list) mDialogTitle = getTitle(); } mDialogMessage = a.getString(com.android.internal.R.styleable.DialogPreference_dialogMessage); mDialogIcon = a.getDrawable(com.android.internal.R.styleable.DialogPreference_dialogIcon); mPositiveButtonText = a.getString(com.android.internal.R.styleable.DialogPreference_positiveButtonText); mNegativeButtonText = a.getString(com.android.internal.R.styleable.DialogPreference_negativeButtonText); mDialogLayoutResId = a.getResourceId(com.android.internal.R.styleable.DialogPreference_dialogLayout, mDialogLayoutResId); a.recycle(); }
Solution:
Поэтому единственный способ сделать такую настройку - это расширение EditTextPreference
. Я написал собственный класс, унаследованный от EditTextPreference
который переопределяет showDialog()
чтобы внести в него изменения. Посмотри пожалуйста:
MyEditTextPreference.java
package com.aminography;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.Button;
import com.aminography.R;
public class MyEditTextPreference extends EditTextPreference {
private float buttonTextSize = 0;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MyEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
public MyEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
public MyEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public MyEditTextPreference(Context context) {
super(context);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyEditTextPreference, defStyleAttr, defStyleRes);
buttonTextSize = typedArray.getDimension(R.styleable.MyEditTextPreference_buttonTextSize, 0);
typedArray.recycle();
}
@Override
protected void showDialog(Bundle state) {
super.showDialog(state);
AlertDialog dialog = (AlertDialog) getDialog();
if (dialog != null && buttonTextSize > 0) {
Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, buttonTextSize);
}
}
}
XML/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.aminography.MyEditTextPreference
android:key="@string/pref_key_username"
android:summary="Please enter your username:"
android:title="Your Name"
app:buttonTextSize="30sp" />
</PreferenceScreen>
Значения /attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyEditTextPreference">
<attr name="buttonTextSize" format="dimension"/>
</declare-styleable>
</resources>
,
Вы также можете установить размер текста на BUTTON_NEGATIVE
в showDialog()
.
Я нашел частичный ответ сам. Есть еще несколько вещей, чтобы выяснить.
Я обнаружил правильные параметры стиля для использования:
Определения AppTheme:
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:editTextPreferenceStyle">@style/DialogPreferenceStyle</item>
</style>
<style name="DialogPreferenceStyle" parent="Preference.DialogPreference.EditTextPreference">
<item name="android:positiveButtonText">TEST TEXT</item>
</style>
Скриншот:
Как вы можете видеть на скриншоте, я могу изменить текст кнопки. Проблемы у меня сейчас. , ,
Если кто-нибудь может помочь мне разобраться в этих 2 проблемах, я отвечу на этот вопрос.
Будет ли это работать?
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="First Category"
android:textSize="20px"
android:layout="@layout/mylayout">