如何改变在Android上preference ImageView的背景颜色? [英] How to change imageview background color in a preference in android?

查看:839
本文介绍了如何改变在Android上preference ImageView的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过,所以我改变了这么多code,以解决我的问题。更改后的甚至称号。
我可以成功地改变ImageView的背景颜色preferences UI。但离开片段和启动后再次,用户界面​​不能在像以前相同的方式进行更新。

首先,我用sherlockactionbar。有3个标签。当第3条是pssed $ P $,一个片段,包括按钮,加载。当按钮中的一个是pressed,另一个preference片段被加载。

在code以下显示了如何调用preference片段当按钮之一pssed $ P $:
SettingsMenuFragment.java

 公共类SettingsMenuFragment扩展SherlockFragment {
@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){按钮ICSbutton =(按钮)view.findViewById(R.id.C​​allSearchSettingsButton);
      ICSbutton.setOnClickListener(新View.OnClickListener()
      {
          @覆盖
          公共无效的onClick(视图v)
          {                clearFragmentStack();
                SettingsIncomingSearchFragment removeSISF =(SettingsIncomingSearchFragment)getActivity()getSupportFragmentManager()findFragmentByTag(SISF)。。
                如果(removeSISF!= NULL)
                {
                    。getActivity()getSupportFragmentManager()调用BeginTransaction()删除(removeSISF).commit()。
                    。getActivity()getSupportFragmentManager()executePendingTransactions()。
                }
                SettingsIncomingSearchFragment prefrag =新SettingsIncomingSearchFragment();
                FragmentTransaction交易= getActivity()getSupportFragmentManager()调用BeginTransaction()。
                transaction.replace(android.R.id.content,prefrag,SISF);
                transaction.addToBackStack(NULL);
                器transaction.commit();
                。getActivity()getSupportFragmentManager()executePendingTransactions()。          }
      });}}

和code以下说明preferencefragment:

 公共类SettingsIncomingSearchFragment扩展preferenceListFragment工具Shared$p$pferences.OnShared$p$pferenceChangeListener,$p$pferenceListFragment.On$p$pferenceAttachedListener {上下文CTX;
公共静态最后弦乐SHARED_ preFS_NAME =设置;
的LinearLayout mainlayout;
的LinearLayout sublayout;
查看视图。
preference我的preF;
ImageView的IMG;
共享preferences SP;
@覆盖
公共无效的onCreate(捆绑冰柱){
    CTX = getActivity();
    super.onCreate(冰柱);
    加preferencesFromResource(R.xml pref_incomingsearchsettings);
    我的preF =(preference)找到preference(incomingsearchbackgroundcolor);
    的setColor();    我的pref.setOn preferenceClickListener(新在preferenceClickListener(){
                 在preferenceClick(preference preference)公共布尔{                     HSVColorPickerDialog CPD =新HSVColorPickerDialog(CTX,0xFF4488CC,新OnColorSelectedListener(){
                            @覆盖
                            公共无效colorSelected(整数颜色)
                            {
                                。sp.edit()putString(incomingsearchbackgroundcolor,将String.valueOf(彩色))提交();
                            }
                        });
                        cpd.setTitle(选择颜色);
                        cpd.show();
                     返回true;                 }
             });
}私人无效的setColor(){
    // TODO自动生成方法存根
     LayoutInflater吹气=(LayoutInflater)
                。getActivity()getSystemService(Context.LAYOUT_INFLATER_SERVICE);        鉴于= 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.getShared preferences(SHARED_ preFS_NAME,ctx.MODE_PRIVATE);
        字符串利用DefValue = NULL;
        利用DefValue = sp.getString(incomingsearchbackgroundcolor,NULL);
        IMG =(ImageView的)sublayout.findViewById(R.id.iv_priority);
        img.setBackgroundColor(的Integer.parseInt(利用DefValue));
}@覆盖
在preferenceAttached公共无效(preferenceScreen根,诠释xmlId){
    // TODO自动生成方法存根}@覆盖
公共无效onShared preferenceChanged(共享preferences共享preferences,
        字符串键){
    // TODO自动生成方法存根
    如果(key.equals(incomingsearchbackgroundcolor))
    {
     SP = ctx.getShared preferences(SHARED_ preFS_NAME,ctx.MODE_PRIVATE);
     字符串利用DefValue = NULL;
     利用DefValue = sp.getString(incomingsearchbackgroundcolor,NULL);
     Log.d(调试,利用DefValue);
     INT的iColor =的Integer.parseInt(利用DefValue);
     img.setBackgroundColor(的iColor);
     img.invalidate();        如果(this.isAdded())
        {
            。getActivity()getSupportFragmentManager()调用BeginTransaction()分离(本).commit()。
            。getActivity()getSupportFragmentManager()executePendingTransactions()。
            。getActivity()getSupportFragmentManager()调用BeginTransaction()连接(本).commit()。
            。getActivity()getSupportFragmentManager()executePendingTransactions()。
        }
    }}@覆盖
公共无效onResume()
{
    super.onResume();
    sp.registerOnShared preferenceChangeListener(本);}@覆盖
公共无效的onPause(){
    super.onPause();
    sp.unregisterOnShared preferenceChangeListener(本);
}

}

这是preference XML

 < preferenceScreen的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android>
< preferenceCategory机器人:总结=选项机器人:标题=OPTIONS机器人:键=选项>
    <复选框preference安卓键=IncomingCallSearch机器人:总结=ON / OFF机器人:标题=启用来电查询机器人:设置defaultValue =真/>
< / preferenceCategory>
< preferenceCategory机器人:总结=画面设置机器人:标题=画面设置机器人:键=ScreenSettings>
<名单preference
      机器人:项=@阵列/ screenLocOptions
      机器人:entryValues​​ =@阵列/ screenLocValues​​
      机器人:键=incomingcallsearch_screenlocation
      机器人:标题=位置
      机器人:设置defaultValue =顶部/>< preference        机器人:设置defaultValue =0xFF000000
        机器人:键=incomingsearchbackgroundcolor
        机器人:标题=背景色
        机器人:布局=@布局/ rectangle_layout/>
< / preferenceCategory>

和这是rectangle_layout XML

<?pre> &LT; XML版本=1.0编码=UTF-8&GT;&LT; LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk / RES / Android的
              机器人:layout_width =FILL_PARENT
              机器人:layout_height =WRAP_CONTENT
              机器人:填充=5DP
              机器人:ID =@ + ID / rectangle_main_layout_ll&GT;
   &LT;的TextView
        机器人:ID =@ + ID / textView1
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:TEXTSIZE =16SP
        机器人:文字=背景颜色
        机器人:layout_weight =0.9/&GT;    &LT;的LinearLayout
        机器人:layout_width =50dp
        机器人:layout_height =50dp
        机器人:方向=垂直
        机器人:layout_weight =0.1
        机器人:ID =@ + ID / rectangle_layout_ll&GT;
           &LT; ImageView的
            机器人:ID =@ + ID / iv_priority
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =FILL_PARENT
            机器人:背景=#000000
            /&GT;
    &LT; / LinearLayout中&GT;

由于我写这​​篇文章的previous版本中,code以上成功运行的第一个在preferences UI更新加载的片段,ImageView的背景颜色。我试着写一步故障情况步:

1。我选择动作条第3栏和包括按钮加载的片段。结果2。我preSS加载preferences片段按钮(你可以看到上面的code)结果
3。在这个preferencefragment,有一个preference包括的TextView和ImageView的(你可以看到上面的细节)结果
4。当我点击这个preference,颜色选择器跑了。(你可以在上面看到的细节)结果
5。我选择拾色器颜色并将其保存到共享preference。(你可以在上面看到的细节)结果
6。 onshared preferencechanged事件触发和我改变的ImageView的背景颜色成功地(你可以看到上面的细节)。结果
7。我离开片段与选择的操作栏或使用回preSS按钮另一个选项卡。结果
8。我启动在第3栏pressing相同的按钮相同的片段。结果
9。我再次使用颜色选择器和onshared $ P $触发pferencechanged事件。结果
10。我可以调试看到真彩code是从共享preference采取和将其设置为ImageView的背景颜色和code以下运行:结果。getActivity()getSupportFragmentManager()调用BeginTransaction()分离(本).commit()。
            。getActivity()getSupportFragmentManager()executePendingTransactions()。
            。getActivity()getSupportFragmentManager()调用BeginTransaction()连接(本).commit()。
            。getActivity()getSupportFragmentManager()executePendingTransactions();搜索

11。但是,preference不更新就在这个时候。的旧的彩色或黑色被认为是在ImageView的。

非常感谢你。


最后
解决方案

我解决了这个问题,这是非常简单的。我希望这篇文章可以帮助任何人谁拥有动态preference更新的问题。

 公共类SettingsIncomingSearchFragment扩展preferenceListFragment
实现共享preferences.OnShared preferenceChangeListener,
preferenceListFragment.On $ P $ {pferenceAttachedListener上下文CTX;
公共静态最后弦乐SHARED_ preFS_NAME =设置;
&LT; - 开始:我删除这些全局变量和方法,在本地定义它们和
设置方法的值 - &GT;
的LinearLayout mainlayout;
的LinearLayout sublayout;
查看视图。
preference我的preF;
ImageView的IMG;
共享preferences SP;
&LT; - 结束:我删除这些全局变量和方法,在本地定义它们和
设置方法的值 - &GT;

I tried to solve my problem so i changed so much code. I change even title of the post. I can change the color of imageview background in preferences ui successfully. But after leaving fragment and launch again, the ui can not be updated in the same way as before.

First of all, I use sherlockactionbar . There are 3 tabs . when 3rd bar is pressed, a fragment is , including buttons, is loaded. When one of button is pressed, another preference fragment is loaded.

The code below shows how to call preference fragment when one of the button is pressed : 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();           

          }
      } );}}

and the code below shows 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);
}

}

and this is preference 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>

and this is the 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>

As i wrote previous version of this post, the code above runs successfully in the first the the fragment loaded, imageview background color updated in preferences ui. I try to write failure condition step by step :

1 . I select the 3rd bar from actionbar and a fragment loaded including buttons.
2 . I press the button that loads preferences fragment(you can see the code above)
3 . In this preferencefragment, there is a preference including textview and imageview(you can see the details above)
4 . When i click this preference, a color picker ran.(you can see the details above)
5 . I choose a color from color picker and save it to sharedpreference.(you can see the details above)
6 . onsharedpreferencechanged event triggered and i change the background color of imageview(you can see the details above) succesfully.
7 . I leave fragment with choosing another tab from action bar or with using backpress button.
8 . I launch same fragment with pressing same button in 3rd bar.
9 . I again use color picker and onsharedpreferencechanged event is triggered.
10 . I can see with debugging that true color code is taken from sharedpreference and it is set to imageview background color and the code below is run :
getActivity().getSupportFragmentManager().beginTransaction().detach(this).commit() ; getActivity().getSupportFragmentManager().executePendingTransactions(); getActivity().getSupportFragmentManager().beginTransaction().attach(this).commit(); getActivity().getSupportFragmentManager().executePendingTransactions();

11 . But preference is not updated in this time. The old color or black is seen in imageview.

Thank you very much

解决方案

at last i solved the problem and it is really simple . I hope this post helps anyone who has problem with dynamic preference updating.

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

这篇关于如何改变在Android上preference ImageView的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆