【问题标题】:Android: On Textview Tap Change background color of only the text excluding margin/paddingAndroid:在Textview上点击仅更改文本的背景颜色,不包括边距/填充
【发布时间】:2016-02-11 01:40:06
【问题描述】:

我有一个 TextView,它与占用剩余空间的其他 2 个项目对齐。 TextView 是可点击的,并且 textview 的背景颜色在点击时会发生变化。问题是更改了完整视图的背景,而不仅仅是 textview 中的文本。有没有办法只为文本更改背景颜色?

<TextView
        android:id="@+id/client_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:gravity="center_horizontal"
        android:layout_toStartOf="@+id/client_header_end_text"
        android:layout_toEndOf="@id/client_header_back"
        android:background="@drawable/action_bar_item_background"
        android:ellipsize="end"
        android:maxLines="1"/>

action_bar_item_background:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/action_bar_item_background_pressed" />
</selector>

action_bar_item_background_pressed:

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/light_grey" />
</shape>

【问题讨论】:

  • 你可以通过 text.setTextColor();

标签: android textview


【解决方案1】:

将您的 TextView 包裹在 FrameLayout 上,并将 TextView 的 layout_width 更改为 wrap_content,并水平居中。但是,您将减少“触摸区域”...要解决此问题,请在 FrameLayout 上注册您的触摸侦听器(移动 TextView ID?),并告诉 TextView 重复ParentState =“true”。比如:

<FrameLayout
    android:id="@+id/client_header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toStartOf="@+id/client_header_end_text"
    android:layout_toEndOf="@id/client_header_back">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/action_bar_item_background"
        android:duplicateParentState="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Hellooooo" />
</FrameLayout>

如果只是要更改的文本颜色,请参阅android TextView : Change Text Color on click

【讨论】:

    【解决方案2】:
    onclick() {
            textview = (TextView) findViewById(R.id.client_header);
            textview.setTextColor(yourColor);
        }
    

    您可以通过这种方式更改 Activity 中的颜色

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 2018-12-10
      • 2011-01-29
      • 1970-01-01
      • 2014-06-12
      • 2011-06-05
      相关资源
      最近更新 更多