【问题标题】:How can I make a switch buttons change the background of an Android Studio TextView?如何让开关按钮更改 Android Studio TextView 的背景?
【发布时间】:2021-03-31 20:26:57
【问题描述】:

我想知道如何通过切换按钮更改 TextView 的背景颜色。有必要澄清一下,我的开关按钮在 MainActivy 中,而我的 TextView 在其他活动中,我可以这样访问:

tvBoton = (TextView) findViewViewById(R.id.Schedule);
        tvBoton.setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View v) {
                    Intent i = new Intent(MainActivity.this, central.class);
                    startActivity(i);
                 }
            });

我不知道它是否会影响任何东西,但我的开关按钮有 SharePreferences:

pol = (Switch) findViewById(R.id.switch18);
        sharpol = getSharedPreferences("pol", MODE_PRIVATE);
        final SharedPreferences.Editor editorpol = sharpol.edit();
        pol.setChecked(sharpol.getBoolean(ex, false));
        pol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean ispolChecked) {
                if (ispolChecked) {
                    editorpol.putBoolean(ex, true);
                    politica=(TextView) findViewViewById(R.id.polit);
                    politica.setText("Not working");
                } else {
                    editorpol.putBoolean(ex, false);
                }
                editorpol.commit();
            }
        });

就像在前面的代码中一样,我尝试在 ispolChecked 中,在 true 选项中引用 TetView,然后放入 setText,但是这个 TextView,在另一个布局中不起作用。我也把 setContentView(R.layout.main_activity) 放了好几次,换成各自的布局,也没用。

老实说,我不知道该怎么办了。感谢您的回答。

【问题讨论】:

  • I also put setContentView(R.layout.main_activity) several times 如果你正在这样做,你需要回顾一下这个函数的作用以及你为什么使用它,它应该是一些你了解并且永远不必怀疑的扎实的基础知识它的作用
  • 我用它来连接我的 java 类和我的 xml,但是我需要把我的 java 类和其他 xml 连接起来才能使用他们的 TextView。谢谢你的回答。
  • tvBoton = (TextView) findViewViewById(R.id.Schedule); tvBoton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, central.class); startActivity(i); } });。请问这段代码在哪个活动中?

标签: android background textview switch-statement


【解决方案1】:

使用SharedPreference 存储Switch 的状态,存储后转到下一个Activity 并根据SharePreference 的状态更改TextView 的背景颜色。

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 2021-07-05
    • 1970-01-01
    • 2021-02-07
    • 2022-01-12
    • 1970-01-01
    • 2021-12-19
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多