我想将以下xml形状设置为线性布局背景:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke
android:width="2dp"
android:color="#D50000">
</stroke>
<solid
android:color="@android:color/transparent">
</solid>
</shape>
我还想通过这些代码行来显示新闻效果:
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
android:background="?android:selectableItemBackground"
但是,正如您所知,一个视图不可能有两个background
。那么,解决方案是什么?
答案 0 :(得分:1)
尝试一下:
<LinearLayout
android:layout_margin="16dp"
app:layout_constraintTop_toTopOf="parent"
android:background="@drawable/ll_background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:onClick="doSomething"
android:padding="8dp"
android:weightSum="3">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Greeting" />
<TextView
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
然后在drawable /文件夹中添加:
button_normal.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke
android:width="2dp"
android:color="#D50000">
</stroke>
</shape>
button_pressed.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid
android:color="#D50000">
</solid>
<stroke android:color="#D50000" android:width="2dp"/>
</shape>
然后创建ll_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/button_pressed"/>
<item android:drawable="@drawable/button_normal"/>
</selector>
最后为创建涟漪图创建drawable-v21文件夹并添加ll_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#D50000">
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<stroke
android:color="#D50000"
android:width="1dp" />
</shape>
</item>
</ripple>
前三个文件(button_normal.xml,button_pressed.xml和ll_background.xml)适用于api <21,而第4个文件(ll_background.xml)适用于所有其他设备,包括api 21及更高版本。
祝你好运,编码愉快!