我一直在使用普通的Android按鈕同時使用圖標(drawableTop)和文本。它的作品真的很差,如果你想有一個非標準尺寸的按鈕,所以我決定做一個LinearLayout中的自定義按鈕具有以下佈局:LinearLayout作爲自定義按鈕,OnClickListener從未調用過
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ButtonHoloDark"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:orientation="vertical" >
<ImageView
android:id="@+id/buttonIcon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:duplicateParentState="true" />
<TextView
android:id="@+id/buttonText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:duplicateParentState="true"
android:gravity="center"
android:textColor="@color/white" />
</LinearLayout>
的佈局使用自定義類:
public class CustomIconButton extends LinearLayout {
public CustomIconButton(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(context, attrs);
LayoutInflater.from(context).inflate(R.layout.custom_icon_button, this, true);
}
...
但是,當我在其父佈局的按鈕上設置OnClickListener時,它永遠不會被調用。如果將偵聽器設置爲ImageView和/或TextView,我只能接收點擊。當按鈕被點擊時,這導致兩種可能的效果:
- 點擊位於ImageView或TextView中。點擊註冊成功,但可繪製按鈕狀態不會改變,即不會出現按下狀態。
- 點擊位於按鈕的「空白區域」內。點擊未註冊,但可繪製狀態正常。
這些都不可行。我已經在LinearLayout中或其子女下列屬性玩耍了,但沒有真正似乎無論真假任何影響:
- duplicateParentState
- 點擊
- 可聚焦
似乎沒有任何合理的方式來獲得LinearLayout父接收點擊,而不是其子級。我已經看到了一些可能的解決方案覆蓋了自定義組件本身的dispatchTouchEvent或onInterceptTouchEvent,但是如果我必須開始分析觸摸事件以確定正確的點擊,那看起來真是一團糟。
因此OnClickListener的LinearLayout與children = no go?
編輯: 這是我目前如何將按鈕插入我的Fragment的主佈局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
...
<com.package.CustomIconButton
android:id="@+id/someButton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
mynamespace:buttonIcon="@drawable/someIcon"
mynamespace:text="@string/str_someText" />
...
而且按鈕在該片段中的代碼約束如下:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.main, container, false);
View customButton = v.findViewById(R.id.goButton);
customButton.setOnClickListener(onClickListener);
...
我不確定我是否跟着你。如果我使用合併,如何可以將按鈕視爲單個視圖?在合併的情況下,對於父LinearLayout是什麼意思? (我編輯了我的問題,以顯示我目前如何使用按鈕。) – ohra
@ohra不需要內部'LinearLayout'。這篇關於merge標籤的文章應該有助於你理解http://android-developers.blogspot.ro/2009/03/android-layout-tricks-3-optimize-by.html。樣式必須移動到您使用'CustomIconButton'(在片段/活動)佈局中的佈局。 – Luksprog
好的,謝謝,現在我明白了LinearLayout問題中的LinearLayout。我用合併代替了按鈕的LinearLayout,將樣式和其他一些屬性移動到主佈局,但由於某些原因,按鈕現在已經完全死亡。它們看起來很好風格明智,但狀態drawable(來自風格)不起作用,點擊仍未註冊。我還有什麼錯? – ohra