【问题标题】:How to save a TextView background changed on click如何保存单击时更改的 TextView 背景
【发布时间】:2014-02-11 00:58:39
【问题描述】:

嗨,伙计们,我是 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);
        }
    });

【问题讨论】:

    标签: android background textview save sharedpreferences


    【解决方案1】:

    使用此代码获取 textview 背景颜色并将 int 放入 SharePreference

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

    【讨论】:

      【解决方案2】:

      我会说:

      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。

      【讨论】:

        猜你喜欢
        • 2014-06-12
        • 2011-06-05
        • 2013-09-27
        • 1970-01-01
        • 1970-01-01
        • 2011-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多