2010-11-24 3 views
5

Я пишу экран предпочтений в xml для моего приложения для Android. Моя проблема в том, что некоторые из названий настроек слишком длинны и не будут обертывать страницу. Рассмотрим мой пример:Как изменить размер заголовка CheckBox или сделать его обернуть в XML-файл PreferenceScreen?

<CheckBoxPreference 
       android:title="Language Detection (BETA)" 
       android:defaultValue="false" 
       android:summary="Automatically decide which language to use" 
       android:key="lan_det_pref" 
       android:textSize="15px" 
       android:lines="4" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 

       /> 

Возможно, у меня что-то не хватает, но я попытался использовать ряд других свойств без каких-либо положительных результатов. Я пробовал android: singleLine, android: lines и т. Д., И ни один из них, похоже, не влияет на название предпочтения. Также существует способ уменьшить размер заголовка CheckBox?

Любая помощь была бы принята с благодарностью.

спасибо :)

ответ

11

CheckBoxPreference не является производным от View, поэтому обычные атрибуты вид не применяются.

Вместо этого CheckBoxPreference привязан к представлению, которое имеет предопределенный макет.

Вы можете получить класс из CheckBoxPreference и переопределить onBindView. В своем классе «onBindView» найдите представление CheckBox и настройте его атрибуты вида по своему вкусу.

class MyCBPref extends CheckBoxPreference{ 
    public MyCBPref(Context context, AttributeSet attrs){ 
    super(context, attrs); 
    } 
    protected void onBindView(View view){ 
    super.onBindView(view); 
    makeMultiline(view); 
    } 
    protected void makeMultiline(View view) 
    { 
    if (view instanceof ViewGroup){ 

     ViewGroup grp=(ViewGroup)view; 

     for (int index = 0; index < grp.getChildCount(); index++) 
     { 
      makeMultiline(grp.getChildAt(index)); 
     } 
    } else if (view instanceof TextView){ 
     TextView t = (TextView)view; 
     t.setSingleLine(false); 
     t.setEllipsize(null); 
    } 
    } 
} 

Затем в макете, укажите свой класс вместо CheckBoxPreference:

<com.mycorp.packagename.MyCBPref android:title="..." ... /> 
+0

i donot получить результат, я также получить одну строку – pengwang 2010-11-25 14:46:37

+0

извините, моя память служила мне немного неправильно. Редактирование. Найдите TextViews (не CheckBox) и просто отключите флаг одной строки и установите для Ellipsize значение null. Если вы хотите применить это только к заголовку, а не к итогу, также вставьте «break;» так как заголовок идет первым. Следует отметить, что это своего рода хак, поскольку это может оказаться неэффективным, если инфраструктура Android изменит макет настроек флажка в будущей версии. Тем не менее, он всегда сделает все текстовые комментарии в элементе Checkbox показан всем предоставленным текстом, который обычно должен быть в порядке. – Thorstenvv 2010-11-26 17:14:26

2

Вы можете настроить вы CheckBox так: MyPreference.xml

<CheckBoxPreference android:key="testcheckbox" 
    android:title="Checkbox Title" 
    android:summary="Checkbox Summary..." 
    android:layout="@layout/custom_checkbox_preference_layout"> 
</CheckBoxPreference> 

и custom_checkbox_preference_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:minHeight="?android:attr/listPreferredItemHeight" 
    android:gravity="center_vertical" 
    android:paddingLeft="16dip" 
    android:paddingRight="?android:attr/scrollbarSize"> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:gravity="center" 
     android:orientation="horizontal"> 
     <ImageView 
      android:id="@+android:id/icon" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      /> 
    </LinearLayout> 

    <RelativeLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginRight="6dip" 
     android:layout_marginTop="6dip" 
     android:layout_marginBottom="6dip" 
     android:layout_weight="1"> 

     <TextView android:id="@+android:id/title" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:singleLine="false" 
      android:textAppearance="?android:attr/textAppearanceMedium" 
      android:ellipsize="marquee" 
      android:fadingEdge="horizontal" /> 

     <TextView android:id="@+android:id/summary" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@android:id/title" 
      android:layout_alignLeft="@android:id/title" 
      android:textAppearance="?android:attr/textAppearanceSmall" 
      android:textColor="?android:attr/textColorSecondary" 
      android:maxLines="4" /> 

    </RelativeLayout> 

    <!-- Preference should place its actual preference widget here. --> 
    <LinearLayout android:id="@+android:id/widget_frame" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:gravity="center" 
     android:orientation="vertical" /> 

</LinearLayout> 

пункт андроида: singleLine = "false" ".

0

Вы можете получить класс от CheckBoxPreference и переопределить onBindView. В своем классе onBindView найдите CheckBox и отредактируйте его атрибуты вида.