2013-12-15 16 views

回答

6

您必須手動創建它。這是你應該實現的模式。您可以在操作欄中添加一個按鈕,點擊後可以啓用或禁用該功能並相應地更改繪圖。你可以使用開關標籤,但這只是在api 14中介紹的。例如,

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" > 

    <Switch 
     android:id="@+id/switchForActionBar" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="" /> 

</RelativeLayout> 

然後,在你mainmenu.xml添加的項目如下

<menu xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item 
     android:id="@+id/myswitch" 
     android:title="" 
     android:showAsAction="always" 
     android:actionLayout="@layout/switch_layout" 
    /> 
</menu> 

您可以添加使用本以及

public class TogglePreference extends Preference { 

    public TogglePreference(Context context) { 
     super(context); 
    } 

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

    public TogglePreference(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    public View getView(View convertView, ViewGroup parent) { 
     if (convertView == null) { 
      convertView = new LinearLayout(getContext()); 
      ((LinearLayout) convertView) 
        .setOrientation(LinearLayout.HORIZONTAL); 

      TextView txtInfo = new TextView(getContext()); 

      txtInfo.setText("Test"); 
      ((LinearLayout) convertView).addView(txtInfo, 
        new LinearLayout.LayoutParams(
          LinearLayout.LayoutParams.FILL_PARENT, 
          LinearLayout.LayoutParams.WRAP_CONTENT, 1)); 

      ToggleButton btn = new ToggleButton(getContext()); 
      ((LinearLayout) convertView).addView(btn); 
     } 

     return convertView; 
    } 

而且中的preferences.xml:

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 

    <PreferenceCategory android:title="Test custom preferences" > 

     <android.dumdum.TogglePreference /> 
    </PreferenceCategory> 

</PreferenceScreen> 
+0

謝謝。是否可以使用?然後它會自動保存該值。 – NoobieNoob

+0

再次添加到api 14.您的活動是偏好活動嗎? –

+0

不,這是一個正常的活動,在那裏我開始「SettingsFragment擴展PreferenceFragment」。我想知道android是如何在它自己的「設置」。 – NoobieNoob