如何保存单击时更改的TextView背景

时间:2014-02-11 00:58:39

标签: android background textview save sharedpreferences

嘿伙计们,我是android的新手,我一直在寻找一个例子,说明如何保存(即使我退出应用程序)TextView的背景颜色,它是'单击使用SharedPreferences或其他任何内容时更改。

并将其与此代码一起使用

Da = (TextView) findViewById(R.id.dreaptaDA);       
    Nu = (TextView) findViewById(R.id.stangaNU);        
    Da.setOnClickListener(new TextView.OnClickListener(){
        public void onClick(View v)
        {                                       
                Da.setBackgroundResource(R.color.Green);
                Nu.setBackgroundResource(R.color.Gray);
        }
    });

    Nu.setOnClickListener(new TextView.OnClickListener(){
        public void onClick(View v)
        {
                Nu.setBackgroundResource(R.color.Red);
                Da.setBackgroundResource(R.color.Gray);
        }
    });

2 个答案:

答案 0 :(得分:0)

使用此代码获取textview背景颜色并将其放入共享首选项

ColorDrawable cd = (ColorDrawable)textView.getBackground();
int i = cd.getColor();
SharePreference prefs = getSharedPreferences("db",0);
Editor edit = prefs.edit();
edit.putInt("color", i);
edit.commit();

答案 1 :(得分:0)

我会说:

ColorDrawable cd = (ColorDrawable) textView.getBackground();
int i = cd.getColor();
SharePreference prefs = getDefaultSharedPreferences(this); // no need to have
// named preferences - call this from an activity or other context
prefs.edit().putInt("color", i).commit();

this表示您在某个扩展上下文的类中。

然后当你需要颜色时

int col = getDefaultSharedPreferences(this).getInt("color",DEFAULT_COLOR);

其中DEFAULT_COLOR是您定义为最终字段的int。

相关问题