【问题标题】:Change position of Text on Button when pressed按下时更改按钮上文本的位置
【发布时间】:2016-02-27 08:05:47
【问题描述】:

我有带有文本和自定义背景的按钮。当我按下按钮时,背景会略微向下移动(“按下效果”)。但是文本保持在同一位置。

当按下按钮时,我应该怎么做才能移动文本?

我尝试过文本选择器、选择器填充,但对我不起作用。

按钮:

<Button
     android:background="@drawable/button_blue"  
     android:layout_height="wrap_content"
     android:textSize="30sp"
     android:textColor="@drawable/selector_txt"
     android:text="Push me"/>

选择器:

<selector>
  <item android:drawable="@drawable/button_blue_pressed" android:state_pressed="true" />
  <item android:drawable="@drawable/button_blue_unpressed" />
</selector>

按钮状态:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:right="3dp"
    android:top="3dp">
    <shape>
        <solid android:color="#aac2bfbf" />
    </shape>
</item>
<item android:right="2dp"
    android:top="2dp">
    <shape >
        <gradient
            android:endColor="@color/darkFab"
            android:startColor="@color/actionBackColor" />
    </shape>
</item>
</layer-list>

<layer-list>
<item
    android:right="3dp"
    android:top="3dp">
    <shape>
        <solid android:color="#aac2bfbf" />
    </shape>
</item>
<item
    android:bottom="2dp"
    android:left="2dp">
    <shape>
        <gradient
            android:endColor="@color/darkFab"
            android:startColor="@color/actionBackColor" />
        <stroke
            android:width="1dp"
            android:color="@color/disabled" />
    </shape>
</item>
</layer-list>

文本选择器:

<selector>
  <item  android:color="@color/colorPrimary" android:state_pressed="true" />
  <item android:color="@color/colorAccent" />
</selector>

【问题讨论】:

标签: android button text


【解决方案1】:

您可以在按下按钮时以编程方式更改按钮的填充。

在您的 XML 文件中为按钮分配一个 ID:

android:id="@+id/button_id

然后,无论您在哪里处理按钮按下:

Button myButton = (Button) findViewById(R.id.button_id);
myButton.paddingTop(0, X, 0, 0); // X will be in pixles, I believe

方法定义为:

public void setPadding (int left, int top, int right, int bottom)

在 Android SDK 的 View 类中。

【讨论】:

  • 是的,我也试过了。问题:单击后应用填充。 TouchEvent 不合适。我认为,有一种更简单的方法。谢谢回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 2017-12-28
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多