2014-01-11 40 views
0

我試圖解決我的問題,所以我改變了這麼多的代碼。我甚至改變帖子的標題。 我可以成功地在首選項ui中更改imageview背景的顏色。但在離開碎片並再次啓動後,用戶界面無法像以前一樣更新。如何在android中首選更改imageview背景顏色?

首先,我使用sherlockactionbar。有3個選項卡。當按下第三欄時,加載一個片段,包括按鈕。當按下其中一個按鈕時,將加載另一首選項片段。

下面的代碼示出了如何調用偏好片段當按下按鈕之一: SettingsMenuFragment.java

public class SettingsMenuFragment extends SherlockFragment { 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button ICSbutton= (Button) view.findViewById(R.id.CallSearchSettingsButton);     
     ICSbutton.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 

       clearFragmentStack(); 
       SettingsIncomingSearchFragment removeSISF = (SettingsIncomingSearchFragment) getActivity().getSupportFragmentManager().findFragmentByTag("SISF"); 
       if(removeSISF != null) 
       { 
        getActivity().getSupportFragmentManager().beginTransaction().remove(removeSISF).commit() ; 
        getActivity().getSupportFragmentManager().executePendingTransactions(); 
       } 
       SettingsIncomingSearchFragment Prefrag = new SettingsIncomingSearchFragment(); 
       FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); 
       transaction.replace(android.R.id.content, Prefrag ,"SISF");     
       transaction.addToBackStack(null); 
       transaction.commit(); 
       getActivity().getSupportFragmentManager().executePendingTransactions();   

      } 
     });}} 

和下面的代碼顯示preferencefragment:

public class SettingsIncomingSearchFragment extends PreferenceListFragment implements SharedPreferences.OnSharedPreferenceChangeListener,PreferenceListFragment.OnPreferenceAttachedListener { 

Context ctx ; 
public static final String SHARED_PREFS_NAME = "settings"; 
LinearLayout mainlayout ; 
LinearLayout sublayout ; 
View view ; 
Preference myPref ; 
ImageView img ; 
SharedPreferences sp ; 


@Override 
public void onCreate(Bundle icicle) { 


    ctx = getActivity() ;  
    super.onCreate(icicle); 
    addPreferencesFromResource(R.xml.pref_incomingsearchsettings); 
    myPref = (Preference) findPreference("incomingsearchbackgroundcolor"); 
    setColor() ;  

    myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { 
       public boolean onPreferenceClick(Preference preference) {      

        HSVColorPickerDialog cpd = new HSVColorPickerDialog(ctx, 0xFF4488CC, new OnColorSelectedListener() { 
          @Override 
          public void colorSelected(Integer color) 
          { 
           sp.edit().putString("incomingsearchbackgroundcolor", String.valueOf(color)).commit();        
          } 
         }); 
         cpd.setTitle("Pick a color"); 
         cpd.show(); 
        return true ; 

       } 
      });   
} 

private void setColor() { 
    // TODO Auto-generated method stub 
    LayoutInflater inflater = (LayoutInflater) 
       getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     view = inflater.inflate(R.layout.rectangle_layout, null); 
     mainlayout = (LinearLayout)view.findViewById(R.id.rectangle_main_layout_ll); 
     sublayout = (LinearLayout)mainlayout.findViewById(R.id.rectangle_layout_ll);    
     sp = ctx.getSharedPreferences(SHARED_PREFS_NAME, ctx.MODE_PRIVATE);   
     String defValue = null ;  
     defValue = sp.getString("incomingsearchbackgroundcolor", null); 
     img = (ImageView)sublayout.findViewById(R.id.iv_priority); 
     img.setBackgroundColor(Integer.parseInt(defValue)); 
} 



@Override 
public void onPreferenceAttached(PreferenceScreen root, int xmlId) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, 
     String key) { 
    // TODO Auto-generated method stub 
    if(key.equals("incomingsearchbackgroundcolor")) 
    {  
    sp = ctx.getSharedPreferences(SHARED_PREFS_NAME, ctx.MODE_PRIVATE); 
    String defValue = null ; 
    defValue = sp.getString("incomingsearchbackgroundcolor", null);  
    Log.d("Debug", defValue); 
    int iColor = Integer.parseInt(defValue); 
    img.setBackgroundColor(iColor); 
    img.invalidate(); 

     if(this.isAdded()) 
     {    
      getActivity().getSupportFragmentManager().beginTransaction().detach(this).commit() ; 
      getActivity().getSupportFragmentManager().executePendingTransactions(); 
      getActivity().getSupportFragmentManager().beginTransaction().attach(this).commit(); 
      getActivity().getSupportFragmentManager().executePendingTransactions(); 
     }   
    } 

} 

@Override 
public void onResume() 
{ 
    super.onResume(); 
    sp.registerOnSharedPreferenceChangeListener(this); 

} 

@Override 
public void onPause() { 
    super.onPause(); 
    sp.unregisterOnSharedPreferenceChangeListener(this); 
} 

}

這是首選xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 
<PreferenceCategory android:summary = "Options" android:title = "OPTIONS" android:key="options"> 
    <CheckBoxPreference android:key="IncomingCallSearch" android:summary="On/Off" android:title="Enable Incoming Call Search" android:defaultValue="true"/> 
</PreferenceCategory> 
<PreferenceCategory android:summary = "Screen Settings" android:title = "Screen settings" android:key="ScreenSettings" > 
<ListPreference 
     android:entries="@array/screenLocOptions" 
     android:entryValues="@array/screenLocValues" 
     android:key="incomingcallsearch_screenlocation" 
     android:title="Location" 
     android:defaultValue="Top"/> 

<Preference 

     android:defaultValue="0xFF000000" 
     android:key="incomingsearchbackgroundcolor"    
     android:title="Background Color"    
     android:layout="@layout/rectangle_layout" /> 
</PreferenceCategory> 

,這是rectangle_layout XML

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:padding="5dp" 
       android:id="@+id/rectangle_main_layout_ll"> 
    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textSize="16sp" 
     android:text="Background color" 
     android:layout_weight= "0.9"/> 

    <LinearLayout 
     android:layout_width="50dp" 
     android:layout_height="50dp"    
     android:orientation="vertical" 
     android:layout_weight= "0.1" 
     android:id="@+id/rectangle_layout_ll"> 
      <ImageView 
      android:id="@+id/iv_priority"    
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:background="#000000" 
      /> 
    </LinearLayout> 

我寫這篇文章的先前版本,上面的代碼成功運行在第一個片段加載,ImageView的背景顏色在偏好ui中更新。我嘗試逐步寫入失敗狀態:

1。我從操作欄中選擇第三個小節,並加載一個包含按鈕的片段。 2。我按下加載首選項片段的按鈕(可以看到上面的代碼)
3。在這個偏好片段中,有一個偏好,包括textview和imageview(你可以看到上面的細節)
4。當我點擊這個首選項時,一個顏色選擇器跑了(你可以看到上面的細節)
5。我從顏色選擇器中選擇顏色並將其保存爲共享首選項(您可以看到上述詳細信息)
6。 onsharedpreferencechanged事件觸發,我改變了imageview的背景顏色(你可以看到上面的細節)成功。
7。我通過從操作欄選擇另一個選項卡或使用後備按鈕離開片段。
8。我在第3欄中按相同的按鈕啓動相同的片段。
9。我再次使用顏色選擇器,並觸發onsharedpreferencechanged事件。
10。我可以在調試中看到真正的顏色代碼來自sharedpreference,並將其設置爲imageview背景顏色,並運行以下代碼:
getActivity()。getSupportFragmentManager()。beginTransaction()。detach(this).commit( ); getActivity()。getSupportFragmentManager()。executePendingTransactions(); getActivity()。getSupportFragmentManager()。beginTransaction()。attach(this).commit(); getActivity()。getSupportFragmentManager()。executePendingTransactions();

11。但是此時不會更新偏好。在Imageview中看到舊的顏色或黑色。

非常感謝您

回答

0

我終於解決了這個問題,這是非常簡單的。我希望這篇文章能夠幫助任何有動態偏好更新問題的人。

public class SettingsIncomingSearchFragment extends PreferenceListFragment 
implements SharedPreferences.OnSharedPreferenceChangeListener, 
PreferenceListFragment.OnPreferenceAttachedListener { 

Context ctx ; 
public static final String SHARED_PREFS_NAME = "settings"; 
<-- Begin : i delete these global variables and define them in methods locally and 
set the values in methods --> 
LinearLayout mainlayout ; 
LinearLayout sublayout ; 
View view ; 
Preference myPref ; 
ImageView img ; 
SharedPreferences sp ; 
<-- End : i delete these global variables and define them in methods locally and 
set the values in methods -->  
+0

正如我在這個問題(http://stackoverflow.com/questions/21360959/imageview-setbackgroundcolor-is-not-working-in-android)寫的,該解決方案只適用於android 4.1.2。 – user3184643

0
getSupportFragmentmanager().detach(this).attach(this).commit() 

所有變更後提交卡明。所以如果你在中間沒有提交的話你會撥打detach(this)attach(this)你什麼也沒改變。

嘗試做一些事情是這樣的:

getSupportFragmentmanager().detach(this).commit(); 
getSupportFragmentmanager().attach(this).commit(); 

這是停留在承諾背後的思想。

P.S

我沒有發現FragmentManager.detach在API()方法...

+0

感謝您的回覆。對不起,我最後一次編輯。現在我從腦海裏寫下代碼。所以我可能會犯錯誤。我將盡快使用原始代碼編輯我的代碼。另外,我嘗試了你之前編寫的代碼。我的意思是,我首先使用detach並提交也使用executependingtransactions,然後我使用attach和commit也使用executependingtransactions。不幸的是,它沒有工作。 – user3184643

+0

嗨,我更新了我的帖子。如果您在我的代碼中看到任何錯誤,請告訴我。謝謝。 – user3184643