【问题标题】:How to set the font size of the item in dialog when I click ListPreference in android?在android中单击ListPreference时如何设置对话框中项目的字体大小?
【发布时间】:2014-08-05 02:34:15
【问题描述】:

我在 PreferenceScreen 中有一个 ListPreference 控件,我希望在 ListPreference 对话框中更改项目的字体大小,我尝试在 ListPreference 中添加样式,但似乎不起作用,我该如何 做 ?谢谢!

顺便说一句,我看过custom row in a 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>

【问题讨论】:

标签: android


【解决方案1】:
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;
        }
    }
}

this answer

【讨论】:

    【解决方案2】:

    创建这个 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>
    

    【讨论】:

      【解决方案3】:

      要更改标题和摘要的 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

      【讨论】:

      • 谢谢!但我需要的是在 ListPreference 对话框中设置单选项目的字体。我知道如何设置标题和摘要的字体。
      【解决方案4】:

      我必须使用扩展 ListPreference 的自定义类。然后在其中我必须创建一个自定义适配器类,就像您为 ListView 所做的一样,并使用 builder.setAdapter() 将其设置为构建器。我还必须为单选按钮和处理取消选中单选按钮等的 ListView 行定义侦听器。我仍然存在的唯一问题是,我的自定义 ListPreference 有一个 OK 和一个 Cancel 按钮,而 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 方法中,请务必在扩展 this 的行中使用此 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>
      

      【讨论】:

      • 谢谢!但我需要的是在 ListPreference 对话框中设置单选项目的字体,我需要一个简单的方法来做到这一点。
      【解决方案5】:

      使用 FontManager 类可以在 Android 平台上实现一个简单而漂亮的字体选择对话框。

      这也是极少数 ListView 实现之一,它通过与 ListPreference 相同的方式正确继承 DialogPreference 来实现自定义 ListView。

      对于正在寻找一种以 ListPreference 样式绘制自定义项目的方法的任何人来说,这也可能会很有趣。

      了解更多

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

      【讨论】:

        猜你喜欢
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 2017-04-15
        • 2013-04-01
        • 1970-01-01
        • 2018-11-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多