【问题标题】:Change text color in shape on touch of button通过触摸按钮更改形状中的文本颜色
【发布时间】:2014-08-09 21:54:02
【问题描述】:

当用户触摸该按钮时如何改变按钮中的颜色文本?

这是我的 shape.xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >


 <item android:state_pressed="true" >
<shape android:shape="rectangle">
  <gradient android:startColor="#ffcc33" 
    android:endColor="#ffcc33"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

  <item android:state_focused="true" >
<shape android:shape="rectangle">
  <gradient android:startColor="#ffcc33" 
    android:endColor="#ffcc33"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

  <item >
<shape android:shape="rectangle">
  <gradient android:startColor="#333333" 
    android:endColor="#333333"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

</selector>

【问题讨论】:

标签: android xml android-layout colors


【解决方案1】:

使用颜色选择器,类似这样的

src/color/button_text.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true" android:color="#000000" /> 
     <item android:state_focused="true" android:color="#000000" />
     <item android:color="#FFFFFF" />
 </selector>

然后在按钮中执行此操作

<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/text"
   android:textColor="@color/button_text" />

【讨论】:

    【解决方案2】:

    一旦按下按钮,您可能会想做其他事情,那么为什么不创建一个普通按钮并将其背景设置为您的形状,然后在 java 中为该按钮创建一个 onTouch 事件

        Button.setOnTouchListener(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if (event.getAction() == MotionEvent.ACTION_DOWN)
                {
                    // do other stuff     
                    Button.setTextColor(Color.parseColor("#000000"));
                }
                else if (event.getAction() == MotionEvent.ACTION_UP)
                {
                    Button.setTextColor(Color.parseColor("#FFFFFF"));
                }
                return false;
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多