簡體   English   中英

用於布局的Android xml選擇器

[英]Android xml selector for layouts

我想知道是否有一個布局的選擇器,就像drawables一樣。

帶drawable的選擇器示例:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected -->
<item android:drawable="@drawable/tab_library_clicked"
      android:state_selected="true" />
<!-- When not selected -->
<item android:drawable="@drawable/tab_library_not_clicked" />

但是有可能有這樣的東西(下面的代碼對我不起作用,但它應該讓你知道我想要完成的事情):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected -->
<item android:layout="@layout/tab_library_clicked"
      android:state_selected="true" />
<!-- When not selected -->
<item android:layout="@layout/tab_library_not_clicked" />

我可能錯了,但我很確定這不存在。

使用XML中的選擇器可以做的最“復雜”可能是使用可繪制層列表將多個drawable組合到一個狀態。

或者,您可以嘗試使用touch_down和touch_up事件以編程方式調用布局上的setVisibility() ,但我認為性能將非常差。

好的,您正在尋找的是一種將父級狀態傳播到其子視圖的方法。 這樣,只要指示器狀態改變(選擇,不選擇),圖像視圖狀態就會改變。

android已經有了xml屬性。

android:duplicateParentState="true"

將它與布局文件中的子視圖一起使用,並將其與選擇器結合使用。 例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#f00" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:duplicateParentState="true"
     />

<ImageView
    android:id="@+id/imageView1"
    android:duplicateParentState="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:src="@drawable/selector" />

默認選擇器機制僅提供屬性的替代(例如可繪制使用等),具體取決於視圖的狀態。 它不會取代視圖本身。 您要求的功能不可用。

View的選定狀態綁定到View類中*_STATE_SET字段的值之一。 通過getDrawableState()檢索視圖的組合狀態。

您可以擴展View類並使用這些狀態來執行自定義操作。 或者,您可以開發自定義布局控制器,該控制器監視View樹中的狀態更改並根據xml資源替換子視圖。

但是努力是不值得的,因為:

  1. 在用戶與其交互期間,視圖/布局結構必須保持不變。 當用戶選擇按鈕時,您不應該將按鈕更改為復選框,替換視圖/布局就像這樣簡單地混淆了UX。

  2. 您只需修改用戶交互視圖的外觀,這已由基於選擇器的繪圖和顏色提供。

文檔中沒有這樣的屬性android:layout for item 它應該與android:drawable一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM