点击按钮时更改形状中文本的颜色

3
如何在用户触摸按钮时更改按钮中的文本颜色?以下是我的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>

以上内容仅用于您的按钮的背景吗? - Rob85
https://dev59.com/4G025IYBdhLWcg3wjGpO - Robert Harvey
https://dev59.com/nGw05IYBdhLWcg3wkik- - Robert Harvey
https://dev59.com/nnjZa4cB1Zd3GeqPcU_h - Robert Harvey
2个回答

12

请使用颜色选择器,类似于以下内容:

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" />

0

一旦您按下按钮,您可能希望执行其他操作,因此为什么不只创建一个普通按钮并将其背景设置为您的形状,然后在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;
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接