我有一个自定义的线性布局,上面有一个小部件Switch
和TextView
子。我希望能够单击LinearLayout
覆盖的区域,因此我将clickable=true
设置为LinearLayout
,但未触发Switch
。
我想在单击LinearLayout
时触发Switch
. 我也在Switch
尝试过android:duplicateParentState="true"
,但没有奏效。
我可以从XML
实现这一点吗?
<LinearLayout
android:background="@drawable/ripple"
android:clickable="true"
android:focusable="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:clickable="false"
android:paddingTop="8dp"
android:text="Visibility"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:clickable="false"
android:layout_marginRight="58dp"
android:maxLines="3"
android:text="@string/visibility_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="58dp" />
</LinearLayout>
设置线性布局和开关的ID,当您执行线性布局的单击时,您必须希望执行检查开关。
linearLayout.setOnClickListener
{
onClick()
{
Switch.setChecked(true);}
}
}
你可以尝试下面的代码通过XML来实现 -
<LinearLayout
android:background="@drawable/ripple"
android:clickable="true"
android:focusable="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:paddingTop="8dp"
android:text="Visibility"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:clickable="false"
android:layout_marginRight="58dp"
android:maxLines="3"
android:text="@string/visibility_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="58dp" />
</LinearLayout>
您可以尝试以下代码来获取所需的输出
<LinearLayout
android:id="@+id/lnrLayout"
android:background="@drawable/ripple"
android:clickable="true"
android:focusable="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:id="@+id/switch"
android:clickable="false"
android:paddingTop="8dp"
android:text="Visibility"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:clickable="false"
android:layout_marginRight="58dp"
android:maxLines="3"
android:text="@string/visibility_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="58dp" />
</LinearLayout>
然后设置 setOnClickListener 的线性布局:
lnrLayout.setOnClickListener{
switch.performClick()
}
或者,您可以将开关与文本一起使用。
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switch1"
style="@style/tvStyle_poppinsMedium_Small_Black"
android:text="@string/push_notifications"
android:layout_width="match_parent"
android:layout_height="wrap_content" />