簡體   English   中英

當我在android中單擊ListPreference時,如何在對話框中設置項目的字體大小?

[英]How to set the font size of the item in dialog when I click ListPreference in android?

我在PreferenceScreen中有一個ListPreference控件,希望在ListPreference對話框中更改項目的字體大小,我嘗試在ListPreference中添加樣式,但似乎不起作用,該怎么辦? 謝謝!

順便說一句,我已經閱讀了listPreference中的文章自定義行? ,我認為它太復雜了,我只需要更改ListPreference對話框中列出項目的字體大小。

<ListPreference
style="@style/Text.ListPreference"/>

<style name="Text.ListPreference">
    <item name="android:textSize">15sp</item>
</style>





<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:robobunny="http://robobunny.com"
    android:key="AppPreference"
    android:summary="@string/PreferenceSummary"
    android:title="@string/Preference" >

     <PreferenceCategory android:title="@string/PreferenceCallCategory"
        android:layout="@layout/preference_category_layout">         

       <ListPreference
          android:key="CallOption"
          android:defaultValue="AllNumber"       
          android:entries="@array/CallAndSMSOption"
          android:entryValues="@array/CallAndSMSOption_values"       
          android:title="@string/CallOptionTitle"
          android:summary="@string/CallOptionSummary" 
          style="@style/myTextLarge"    
          android:layout="@layout/preference_layout"  
        /> 

      </PreferenceCategory> 


</PreferenceScreen>

要更改標題和摘要的textSize,您可以簡單地使用自定義布局:

<?xml version="1.0" encoding="utf-8"?>

<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="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="20sp"/>

    <TextView android:id="@android:id/summary"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="20sp"/>

</LinearLayout>

編輯:

自定義對話框是一個全新的故事。 煩人的對話框很難配置。

要更改對話框項的文本大小,不幸的是,您必須為對話框使用自定義適配器。 這是您可以從PreferenceActivity

final ListPreference listPreference = (ListPreference) findPreference("CallOption");
if (listPreference == null) {
    Log.e("TAG", "Couldn't find the ListPreference");
    return;
}

listPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        AlertDialog dialog = (AlertDialog) listPreference.getDialog();
        if (dialog == null) {
            Log.e(TAG, "Couldn't find the dialog");
            return true;
        } else {
            Log.e(TAG, "Dialog found");
        }

        ListView listView = dialog.getListView();
        if (listView == null) {
            Log.e(TAG, "Couldn't find the ListView");
            return true;
        }

        listView.setAdapter(listAdapter);

        return true;
    }
});

筆記:

  • 您的適配器將必須使用CheckedTextView ,以便可以檢查它們。
  • 您可能必須確保正確保存了設置
    • (提示: listView.setOnItemClickListener();
  • 您甚至可能首先要使用自定義ListPreference

創建此custom_pref_layout.xml:

 <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="wrap_content" 
        android:layout_height="wrap_content" 
        android:textSize="40px"/>  

    <TextView android:id="@+android:id/summary"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textSize="26px"/>

</LinearLayout>

並將其添加到所需的首選項對象中:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="My Category">             

        <CheckBoxPreference
            android:title="I am a Checkbox Preference"
            android:defaultValue="false"
            android:summary="This is a Checkbox preference"
            android:key="checkboxPref"
            android:layout="@layout/custom_pref_layout"/>

    </PreferenceCategory>
</PreferenceScreen>

我必須使用擴展ListPreference的自定義類。 然后在其中,我必須像創建ListView一樣創建一個自定義適配器類,並使用builder.setAdapter()將其設置為構建器。 我還必須為單選按鈕和處理未選中單選按鈕等的ListView行定義偵聽器。 我唯一仍然遇到的問題是,我的自定義ListPreference同時具有“確定”和“取消”按鈕,而ListPreference僅具有“取消”按鈕。 我不知道如何刪除“確定”按鈕。 另外,當我單擊常規的ListPreference中的行時,也無法突出顯示行。

自定義ListPreference類的Java代碼。 一定要注意諸如程序包名稱,首選項名稱(鍵),ListPreference的條目和值以及xml項的名稱之類的事情。

 package your.package.here;

 import java.util.ArrayList;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.SharedPreferences;
 import android.graphics.Color;
 import android.preference.ListPreference;
 import android.preference.PreferenceManager;
 import android.util.AttributeSet;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import android.widget.CompoundButton;
 import android.widget.RadioButton;
 import android.widget.TextView;
 import android.app.Dialog;
 import android.app.AlertDialog.Builder;

public class CustomListPreference extends ListPreference
{   
CustomListPreferenceAdapter customListPreferenceAdapter = null;
Context mContext;
private LayoutInflater mInflater;
CharSequence[] entries;
CharSequence[] entryValues;
ArrayList<RadioButton> rButtonList;
SharedPreferences prefs;
SharedPreferences.Editor editor;

public CustomListPreference(Context context, AttributeSet attrs)
{
    super(context, attrs);
    mContext = context;
    mInflater = LayoutInflater.from(context);
    rButtonList = new ArrayList<RadioButton>();
    prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    editor = prefs.edit();
}

@Override
protected void onPrepareDialogBuilder(Builder builder)
{
    entries = getEntries();
    entryValues = getEntryValues();

    if (entries == null || entryValues == null || entries.length != entryValues.length )
    {
        throw new IllegalStateException(
                "ListPreference requires an entries array and an entryValues array which are both the same length");
    }

    customListPreferenceAdapter = new CustomListPreferenceAdapter(mContext);

    builder.setAdapter(customListPreferenceAdapter, new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {

        }
    });
}

private class CustomListPreferenceAdapter extends BaseAdapter
{        
    public CustomListPreferenceAdapter(Context context)
    {

    }

    public int getCount()
    {
        return entries.length;
    }

    public Object getItem(int position)
    {
        return position;
    }

    public long getItemId(int position)
    {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent)
    {  
        View row = convertView;
        CustomHolder holder = null;

        if(row == null)
        {                                                                   
            row = mInflater.inflate(R.layout.custom_list_preference_row, parent, false);
            holder = new CustomHolder(row, position);
            row.setTag(holder);

            // do whatever you need here, for me I wanted the last item to be greyed out and unclickable
            if(position != 3)
            {
                row.setClickable(true);
                row.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        for(RadioButton rb : rButtonList)
                        {
                            if(rb.getId() != position)
                                rb.setChecked(false);
                        }

                        int index = position;
                        int value = Integer.valueOf((String) entryValues[index]);
                        editor.putInt("yourPref", value);

                        Dialog mDialog = getDialog();
                        mDialog.dismiss();
                    }
                });
            }
        }

        return row;
    }

    class CustomHolder
    {
        private TextView text = null;
        private RadioButton rButton = null;

        CustomHolder(View row, int position)
        {    
            text = (TextView)row.findViewById(R.id.custom_list_view_row_text_view);
            text.setText(entries[position]);
            rButton = (RadioButton)row.findViewById(R.id.custom_list_view_row_radio_button);
            rButton.setId(position);

            // again do whatever you need to, for me I wanted this item to be greyed out and unclickable
            if(position == 3)
            {
                text.setTextColor(Color.LTGRAY);
                rButton.setClickable(false);
            }

            // also need to do something to check your preference and set the right button as checked

            rButtonList.add(rButton);
            rButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
            {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    if(isChecked)
                    {
                        for(RadioButton rb : rButtonList)
                        {
                            if(rb != buttonView)
                                rb.setChecked(false);
                        }

                        int index = buttonView.getId();
                        int value = Integer.valueOf((String) entryValues[index]);
                        editor.putInt("yourPref", value);

                        Dialog mDialog = getDialog();
                        mDialog.dismiss();
                    }
                }
            });
        }
    }
}

}

我的PreferenceActivity的xml。 這不是我的完整xml,為簡單起見,我也刪除了其他優先項。 同樣,請務必注意包名,包名必須引用自定義ListPreference類。 還請注意首選項的名稱以及保存條目和值的數組名稱。

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
            android:title="Your Title">

            <your.package.here.CustomListPreference
                android:key="yourPref"
                android:title="Your Title"
                android:dialogTitle="Your Title"
                android:summary="Your Summary"
                android:defaultValue="1"
                android:entries="@array/yourArray"
                android:entryValues="@array/yourValues"/>

    </PreferenceCategory>
    </PreferenceScreen>

對話框列表視圖行的XML。 在getView方法中,請確保在將其誇大的行中使用此xml文件的名稱。

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="8dip"
android:paddingTop="8dip"
android:paddingLeft="10dip"
android:paddingRight="10dip">

<TableLayout
    android:id="@+id/custom_list_view_row_table_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="0">

    <TableRow
        android:id="@+id/custom_list_view_row_table_row"
        android:gravity="center_vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/custom_list_view_row_text_view"
            android:textSize="22sp"
            android:textColor="#000000"  
            android:gravity="center_vertical"
            android:layout_width="160dip" 
            android:layout_height="40dip" />

        <RadioButton
            android:checked="false"
            android:id="@+id/custom_list_view_row_radio_button"/>
    </TableRow>
    </TableLayout>

   </LinearLayout>

最后,在res / values下面是我的array.xml,其中包含ListPreference的條目名稱和值。 再次,為簡化起見,縮短了我的代碼。

  <?xml version="1.0" encoding="utf-8"?>
  <resources> 
  <string-array name="yourArray">
    <item>Item 1</item>
    <item>Item 2</item>
    <item>Item 3</item>
    <item>Item 4</item>
  </string-array>

  <string-array name="yourValues">
    <item>0</item>
    <item>1</item>
    <item>2</item>
    <item>3</item>
 </string-array>
 </resources>

使用FontManager類可以在Android平台上實現一個簡單而漂亮的字體選擇對話框。

這也是為數不多的ListView實現之一,該實現通過以與ListPreference相同的方式正確地對DialogPreference進行子類化來實現自定義ListView。

對於任何尋求以ListPreference樣式繪制自定義項目的人來說,它也可能很有趣。

了解更多

http://www.ulduzsoft.com/2012/01/fontpreference-dialog-for-android/

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class FontPreference extends DialogPreference implements DialogInterface.OnClickListener {

    // Keeps the font file paths and names in separate arrays
    private List<String> m_fontPaths;
    private List<String> m_fontNames;

    public FontPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onPrepareDialogBuilder(Builder builder) {
        super.onPrepareDialogBuilder(builder);
        // Get the fonts on the device
        HashMap<String, String> fonts = FontManager.enumerateFonts();
        m_fontPaths = new ArrayList<String>();
        m_fontNames = new ArrayList<String>();
        // Get the current value to find the checked item
        String selectedFontPath = getSharedPreferences().getString(getKey(), "");
        int idx = 0, checked_item = 0;
        for (String path : fonts.keySet()) {
            if (path.equals(selectedFontPath))
                checked_item = idx;
            m_fontPaths.add(path);
            m_fontNames.add(fonts.get(path));
            idx++;
        }
        // Create out adapter
        // If you're building for API 11 and up, you can pass builder.getContext
        // instead of current context
        FontAdapter adapter = new FontAdapter();
        builder.setSingleChoiceItems(adapter, checked_item, this);
        // The typical interaction for list-based dialogs is to have click-on-an-item dismiss the dialog
        builder.setPositiveButton(null, null);
    }

    public void onClick(DialogInterface dialog, int which) {
        if (which >= 0 && which < m_fontPaths.size()) {
            String selectedFontPath = m_fontPaths.get(which);
            Editor editor = getSharedPreferences().edit();
            editor.putString(getKey(), selectedFontPath);
            editor.commit();
            dialog.dismiss();
        }
    }


    // Font adaptor responsible for redrawing the item TextView with the appropriate font.
    // We use BaseAdapter since we need both arrays, and the effort is quite small.
    public class FontAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return m_fontNames.size();
        }

        @Override
        public Object getItem(int position) {
            return m_fontNames.get(position);
        }

        @Override
        public long getItemId(int position) {
            // We use the position as ID
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            // This function may be called in two cases: a new view needs to be created,
            // or an existing view needs to be reused
            if (view == null) {
                // Since we're using the system list for the layout, use the system inflater
                final LayoutInflater inflater = (LayoutInflater)
                        getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                // And inflate the view android.R.layout.select_dialog_singlechoice
                // Why? See com.android.internal.app.AlertController method createListView()
                view = inflater.inflate(android.R.layout.select_dialog_singlechoice, parent, false);
            }
            if (view != null) {
                // Find the text view from our interface
                CheckedTextView tv = (CheckedTextView) view.findViewById(android.R.id.text1);
                // Replace the string with the current font name using our typeface
                Typeface tface = Typeface.createFromFile(m_fontPaths.get(position));
                tv.setTypeface(tface);
                // If you want to make the selected item having different foreground or background color,
                // be aware of themes. In some of them your foreground color may be the background color.
                // So we don't mess with anything here and just add the extra stars to have the selected
                // font to stand out.
                tv.setText(m_fontNames.get(position));
            }
            return view;
        }
    }
}

結束看到這個答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM