2014-01-11 3 views
0

나는 많은 문제를 해결하기 위해 내 문제를 해결하려고 노력했다. 게시물의 제목조차 변경합니다. 환경 설정에서 이미지 뷰 배경색을 성공적으로 변경할 수 있습니다. 그러나 단편을 떠나 다시 시작한 후에는 이전과 같은 방식으로 UI를 업데이트 할 수 없습니다.환경 설정에서 이미지 뷰 배경색을 Android에서 어떻게 변경합니까?

우선 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

012 31,676,398,

이이 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> 

내가이 게시물의 이전 버전을 썼던 것처럼에게있다는 위의 코드는 조각로드, 이미지 뷰 배경색 처음에 성공적으로 실행 환경 설정 ui에서 업데이트되었습니다. 단계별로 실패 조건을 작성하려고합니다 :

1. 액션 바에서 세 번째 막대를 선택하고 버튼을 포함하여로드 된 단편을 선택합니다.
2. 환경 설정 조각을로드하는 버튼을 누릅니다 (위 코드를 볼 수 있습니다)
3. 이 환경 설정 조각에는 textview 및 imageview를 포함한 기본 설정이 있습니다 (위의 세부 정보 참조)
4. 이 환경 설정을 클릭하면 색상 선택 도구가 실행됩니다 (세부 정보는 위 참조)
5. 색상 선택 도구에서 색상을 선택하여 공유 미리보기로 저장합니다 (위의 세부 정보 참조)
6. onsharedpreferencechanged 이벤트가 발생하고 이미지 뷰의 배경색을 변경합니다 (위의 세부 정보를 볼 수 있습니다).
7. 작업 표시 줄에서 다른 탭을 선택하거나 뒷면 버튼을 사용하여 조각을 남깁니다.
8. 제 3의 막대기에있는 동일한 단추를 누르기에 나는 동일한 조각을 발사한다.
9. 다시 색상 선택기를 사용하고 onsharedpreferencechanged 이벤트가 트리거됩니다.
10. true color 코드가 sharedpreference에서 가져온 것으로 디버깅 할 때 이미지 뷰 배경색으로 설정하고 아래 코드를 실행하면 볼 수 있습니다.
getActivity(). getSupportFragmentManager(). beginTransaction(). detach (this) .commit (); getActivity(). getSupportFragmentManager(). executePendingTransactions(); getActivity(). getSupportFragmentManager(). beginTransaction(). attach (this) .commit(); getActivity(). getSupportFragmentManager(). executePendingTransactions();

11. 그러나이 시간에는 선호도가 업데이트되지 않습니다.오래된 색상 또는 검은 색이 imageview에 표시됩니다.

는 당신에게 커밋 후 을 커밍

답변

0

내가 문제를 해결하고 정말 간단 FragmentManager.detach API를() 메서드를 ... 발견되지 않았다. 이 게시물이 동적 환경 설정 업데이트에 문제가있는 사용자에게 도움이되기를 바랍니다.

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)에서 썼다, 해결책은 단지 안드로이드 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

나는 마침내

+0

답장을 보내 주셔서 감사합니다. 마지막 편집을 위해 죄송합니다. 나는 지금 내 마음에서 포스트에 코드를 쓴다. 그래서 실수 할 수도 있습니다. 최대한 빨리 원본 코드를 사용하여 코드를 편집합니다. 또한, 나는 당신이 전에 쓴 코드를 시도했다. 내 말은, 나는 첫째로 detach를 사용하고 executependingtransactions를 사용하고 나서 attach를 사용하고 executependingtransactions를 사용한다. 불행히도, 그것은 작동하지 않았다. – user3184643

+0

안녕하세요, 내 게시물을 업데이트합니다. 내 코드에 이상한 점이 있으면 알려주십시오. 감사. – user3184643