【问题标题】:How to change button and text color dynamically on android如何在android上动态更改按钮和文本颜色
【发布时间】:2012-09-27 13:31:22
【问题描述】:

如何动态/编程更改按钮文本颜色和按钮形状(矩形)?

【问题讨论】:

标签: android button


【解决方案1】:

如果您的 main.xml 中有一个 id=button1 的按钮,那么您可以按如下方式使用它:

setContentView(R.layout.main);

Button mButton=(Button)findViewById(R.id.button1);
mButton.setTextColor(Color.parseColor("#FF0000")); // custom color
//mButton.setTextColor(Color.RED); // use default color
mButton.setBackgroundResource(R.drawable.button_shape);

R.drawable.button_shape(button_shape.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#70ffffff"
      android:centerColor="#70ffffff"
      android:endColor="#70ffffff"
      android:angle="270" />
  <corners 
        android:bottomRightRadius="8dp"
        android:bottomLeftRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp"/>  
</shape>

您可以拥有自己的形状文件。根据需要进行更改。

【讨论】:

    【解决方案2】:

    你可以像动态改变按钮文本颜色

    按钮 btnChangeTextColor = (Button)findViewbyId(btnChange); btnChangeTextColor.setTextColor(Color.BLUE);

    【讨论】:

      【解决方案3】:

      基本上你必须遵循这个方案:

      1) 获取要更改的对象的引用

      findViewById(R.id.<your_object_id>);
      

      2) 将其转换为对象类型

      Button btnYourButton = (Button) findViewById(R.id.<your_object_id>);
      

      3) 在对象“btnYourButton”上使用设置器

      4) 重绘您的视图(可能调用 invalidate());

      这取决于您希望何时进行更改。我假设你会有一个 eventListener 附加到您的对象,并在事件触发后执行您的更改。

      【讨论】:

        【解决方案4】:

        您将需要某种类型的侦听器来侦听发生的事件,以及何时使用某些设置方法更改形状/文本颜色。

        试试:

        http://developer.android.com/reference/android/view/View.OnClickListener.html

        为了提供更明确的反馈,我需要知道您想要什么信号来更改文本颜色和形状。您能否详细说明动态更改的含义?

        【讨论】:

          【解决方案5】:

          @覆盖 public boolean onTouchEvent(MotionEvent 事件) {

              if (event.getAction() == MotionEvent.ACTION_DOWN) {
          
                  start_x = event.getX();
                  start_y = event.getY();
          
              } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
          
                  setTitle(event.getX() + "y pos" + event.getY());
                  RelativeLayout layout = (RelativeLayout) findViewById(R.id.lay);
          
                  layout.setBackgroundColor(Color.rgb((int) start_x, (int) start_y, 0));
              } else if (event.getAction() == MotionEvent.ACTION_UP) {
          
          
          
              }
              return true;
          }
          

          【讨论】:

            猜你喜欢
            • 2021-04-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-24
            • 2020-11-07
            • 2019-09-24
            相关资源
            最近更新 更多