将onFocus以及背景图片添加到视图中

时间:2019-01-27 19:59:22

标签: android android-layout

我有一个LinearLayout视图,需要以编程方式将其设置为背景图像。但是,当此视图成为焦点时,我需要在其周围显示笔触。

我在做什么: 显示onFocus效果的背景资源(view_onfocus_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <stroke android:width="5dp" android:color="#F7CA18" />
        </shape>
    </item>
</selector>

在布局XML中,我如下添加背景以应用具有onFocus效果的背景。:

android:background="@drawable/view_onfocus_background"

但是,在代码中,我必须为布局设置不同的背景图像。

myLayout.setBackgroundResource(R.drawable.custom_image);

因此,很明显,我在布局XML中添加的view_onfocus_background不再适用!

问题: 如何实现onFocus效果以及布局的自定义图像背景?

1 个答案:

答案 0 :(得分:0)

我发现无法通过XML将背景效果以及图像背景应用于LinearLayout。我唯一能做的就是拥有两个LinearLayouts(父级和子级)。将XML应用于父布局。将图像背景应用于子布局。在父布局中添加一些填充以显示onFocus效果。 示例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/customFocusLayout"
    android:padding="5dp"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:clickable="true"
    android:focusable="true"
    android:orientation="vertical"
    android:background="@drawable/view_onfocus_background"
     >
    <LinearLayout
        android:id="@+id/customTestLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="false"
        android:padding="0dp"
        android:layout_gravity="bottom"
        android:background="@drawable/custom_image"
        android:orientation="vertical">

        <!-- more stuff here-->

    </LinearLayout>
</LinearLayout>
相关问题