2014-01-11 41 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