2010-12-12 31 views
5

在Android上,我想創建一個包含一些其他視圖的按鈕。例如,這樣的事情:如何創建包含多個視圖的按鈕?

+---------------------------+ 
| Hello world! +-------+ | 
|     | image | | 
| Some more info +-------+ | 
+---------------------------+ 

但我希望它比這個具體的例子更靈活。理想情況下,按鈕只能包含一個ViewGroup,這樣我就可以在一個單獨的XML文件中實現其佈局。但是,由於Button擴展了View,而不是ViewGroup,這看起來不太可能。

有沒有什麼辦法可以使用標準的Android組件實現這一點,還是我不得不求助於編寫自定義按鈕類?


按照要求,一些示例XML,做的伎倆:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    android:focusable="true" 
    android:clickable="true" 
    android:background="@android:drawable/btn_default"> 
    <TextView 
     android:id="@+id/name" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="@android:color/primary_text_light"/> 
    <TextView 
     android:id="@+id/additional_line_1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="@android:color/primary_text_light"/> 
    <TextView 
     android:id="@+id/additional_line_2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="@android:color/primary_text_light"/> 
</LinearLayout> 

我必須設置明確的TextViews的顏色,否則他們就幾乎不可讀(他們是由默認的白色) 。我挖掘了SDK中的標識符:.../platforms/android-7/data/res/values/public.xml。奇怪的是,primary_text_light給出了黑色的文字,而primary_text_dark的結果是白色的...

+0

25.3k代表蘇,你問這個問題?我會給你一個提示......寫你自己的課......或者我錯過了這個觀點? – Squonk 2010-12-12 13:00:58

+7

真的嗎?名聲是否意味着一個傢伙永遠不會卡在某個地方並要求一些提示? – 2010-12-12 13:05:14

+0

我也想說,創建您自己的自定義View(Group)類。 – 2010-12-12 13:10:29

回答

4

創建所需按鈕的佈局,並將它的android:background設置爲@android:drawable/btn_default。製作包含其餘clickablefocusable的最外層視圖,即可完成。

+0

有趣... @Thomas:如果這個工作,請分享一個簡短的XML示例,我很感興趣:) – WarrenFaith 2010-12-12 14:01:16

+1

@WarrenFaith:那種工作很好。我已經使用'android:background =「@ android:drawable/edit_text」'設置爲'Button',使它看起來像一個'EditText'。 (使用日期選取器避免日期驗證:)) – Macarse 2010-12-12 14:04:17

+0

@WarrenFaith:我將XML放入問題中。 – Thomas 2010-12-13 08:46:53

1

我不確定,但你試過ImageButton類嗎?我想你應該能夠將圖像設置在右側,並且您應該也可以添加帶有新線條的標籤。

[更新]我錯過了「更靈活」的部分。如果你想有一個更靈活的,我想你需要創建一個自己的實現與自己的OnTouchListener來處理所有可能的狀態和檢測點擊。

0

我不會爲此創建一個類。這只是一個RelativeLayout兩個TextView s和一個ImageView

如您所知,ViewGroup延伸爲View,並且View可以具有點擊偵聽器。所以你需要創建佈局並設置一個點擊監聽器。

這裏的問題是你如何處理狀態,你可以嘗試使用@android:drawable/btn_default作爲背景,如@ognian所說。

相關問題