Android 单击时如何突出显示 TextView 或 LinearLayout?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2181062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:51:17  来源:igfitidea点击:

How to highlight a TextView or LinearLayout when click it?

android

提问by user256239

I have a LinearLayout that contains three TextViews. I want to highlight a TextView or the whole Layout when user clicks on the TextView. Is they any way to make it happen?

我有一个包含三个 TextView 的 LinearLayout。当用户单击 TextView 时,我想突出显示一个 TextView 或整个布局。他们有什么办法让它发生吗?

Thanks.

谢谢。

回答by Anthone

I supperpose 2 Layout

我假设 2 布局

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"

    >

    <LinearLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?android:attr/selectableItemBackground"
        android:clickable="true"
        >
...
    </LinearLayout>
</LinearLayout>

findViewById(R.id.root).setOnClickListener(...);

回答by Jerry Brady

I couldn't get Roman's methods working, but found my answer hereinstead. Use an XML resource as the background drawable and voila! it worked like a charm.

我无法让 Roman 的方法起作用,而是在这里找到了我的答案。使用 XML 资源作为可绘制的背景,瞧!它就像一个魅力。

回答by Roman Nurik

There are a number of ways of doing this.

有多种方法可以做到这一点。

The simplest way of doing this is by playing around with various Viewattributes such as android:focusable, android:focusableInTouchMode, android:clickable, and TextViewattributes such as android:selectAllOnFocus.

这样做的最简单的方法是通过玩弄各种查看属性,例如android:focusableandroid:focusableInTouchModeandroid:clickable,和TextView的属性,例如android:selectAllOnFocus

You could also customize the appearance of your views by setting their backgrounds to StateListDrawables (a.k.a. <selector>drawables).

您还可以通过将视图的背景设置为StateListDrawables(又名<selector>可绘制对象)来自定义视图的外观。