2012-01-11 59 views
12

我試圖創建一個類似按鈕的組件,左對齊ImageView,然後2 ImageView右邊的TextView,堆疊一個在另一個之上,格式不同,就像下面的例子:Android佈局作爲具有可選功能的按鈕

__________________________ 
|       | 
| |-----| Bold Main Text | 
| |Image|     | 
| |-----| Small Sub Text | 
|__________________________| 

我也想了ImageView的,這取決於外部容器的點擊狀態更改,就像一個標準按鈕會做與它相關聯的可選資源。所以當我點擊外框中的任何地方時,圖像可選狀態就會改變。

我知道我可以使用按鈕,設置'drawableLeft'屬性來創建與圖像相關聯的單行文本作爲按鈕,但似乎我只能使用此策略使用單個文本項目。

過去有沒有人實現過這樣的UI組件?

謝謝!

+1

那麼你可以使用自己的佈局,並添加一個OnClickListener到它,所以它會begave像一個按鈕。對於單擊狀態下的圖像更改,這可能需要更復雜的偵聽器邏輯,並且可能使用onTouchListener而不是 – Guillaume 2012-01-11 15:41:56

回答

14

您可以將android:duplicateParentState="true"添加到ImageView小部件。您還需要使ImageView的家長可以點擊並且可以對焦。

在下面的代碼的RelativeLayout將作爲Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout:height="match_parent" 
    android:orientation="vertical"> 

    <RelativeLayout 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:clickable="true" 
     android:focusable="true"> 

     <ImageView 
      android:id="@+id/image" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentTop="true" 
      android:duplicateParentState="true" 
      android:src="@drawable/icon" /> 
     <TextView 
      android:id="@+id/text1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_toRightOf="@+id/image" 
      android:layout_alignTop="@+id/image" 
      android:layout_alignWithParentIfMissing="true" 
      android:duplicateParentState="true" /> 
     <TextView 
      android:id="@+id/text2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"    
      android:layout_toRightOf="@+id/image" 
      android:layout_below="@+id/text1" 
      android:layout_alignWithParentIfMissing="true" 
      android:duplicateParentState="true" /> 
    </RelativeLayout> 
</LinearLayout> 
+1

感謝Pixie,它完美地工作。 – 2012-01-12 19:25:31

+0

不客氣!很高興幫助。 – Michael 2012-01-12 19:49:00

+1

真棒解決方案!現在試圖做幾個小時。這件事情讓我感到很快樂。謝謝! – VM4 2013-09-11 13:30:03