2014-12-30 70 views
1

我已經在customlayout中使用PreferenceScreen開發了一個設置頁面。有一個switchpreference,我想改變顏色。目前它採用默認顏色。但是當用戶打開和關閉時,我想要改變它的顏色。當用戶打開時,側面應該是紅色,當用戶切換到關閉側時,「關閉」側應該是淺灰色。我Switchpreference代碼如下:自定義佈局中開關首選項的開/關切換顏色變化

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

<PreferenceCategory android:key="pref" > 

    <SwitchPreference 
     android:key="switchbutton" 
     android:summaryOff="OFF" 
     android:summaryOn="ON" 
     android:title="start" /> 
</PreferenceCategory> 

我一個新手到Android編程,請共同operate.I會很高興,如果有人可以幫助我.Thanks提前! !

回答

0

試試這個:

mViewSwitcher.setOnDragListener(new View.OnDragListener() { 
@Override 
public boolean onDrag(View v, DragEvent event) { 
// set color here 
return false; 
} 
}); 
+0

它給出了一個錯誤稱爲-The方法setOnDragListener(new View.OnDragListener(){})未定義類型SwitchPreference –

+0

@android_newcomer也可以嘗試此解決方案http://stackoverflow.com/a/21854548 – QArea

1

我在一個類似的問題張貼了這個答案在Custom SwitchPreference in Android這樣的

一種方式是繼承SwitchPreference並重寫onBindView方法。這樣做,你要還是叫super.onBindView(視圖)在該方法中,但後來發現孩子的意見交換機和風格在適當的情況:

package com.example; 

import android.annotation.SuppressLint; 
import android.content.Context; 
import android.preference.SwitchPreference; 
import android.util.AttributeSet; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Switch; 

import com.example.R; 


public class CustomSwitchPreference extends SwitchPreference { 

    @SuppressLint("NewApi") 
    public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 
    } 

    public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

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

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

    @Override 
    protected void onBindView(View view) { 

     super.onBindView(view); 
     Switch theSwitch = findSwitchInChildviews((ViewGroup) view); 
     if (theSwitch!=null) { 
      //do styling here 
      theSwitch.setThumbResource(R.drawable.new_thumb_resource); 
     } 

    } 

    private Switch findSwitchInChildviews(ViewGroup view) { 
     for (int i=0;i<view.getChildCount();i++) { 
      View thisChildview = view.getChildAt(i); 
      if (thisChildview instanceof Switch) { 
       return (Switch)thisChildview; 
      } 
      else if (thisChildview instanceof ViewGroup) { 
       Switch theSwitch = findSwitchInChildviews((ViewGroup) thisChildview); 
       if (theSwitch!=null) return theSwitch; 
      } 
     } 
     return null; 
    } 
}