[英]How to create a Button that contains multiple Views?
在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
導致白色......
創建所需按鈕的布局,並將其設置為android:background
到@android:drawable/btn_default
。 制作包含其余clickable
且focusable
的最外層視圖,您就完成了。
我不確定,但你嘗試過ImageButton
課嗎? 我想你應該能夠將圖像設置在右側,你也應該能夠添加帶有新線條的標簽。
[更新]我錯過了“更靈活”的部分。 如果你想要一個更靈活的,我想你需要創建一個自己的實現與自己的OnTouchListener
來處理所有可能的狀態和檢測點擊。
我不會為此創建一個類。 它只是一個包含兩個TextView
和一個ImageView
的RelativeLayout
。
您可能知道, ViewGroup
擴展了View
, View
可以擁有Click監聽器。 因此,您需要創建布局並為其設置單擊偵聽器。
這里的問題是你如何處理狀態,你可以嘗試使用@android:drawable/btn_default
作為背景,如@ognian所說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.