アイコン(drawableTop)とテキストの両方で一般的なAndroidボタンを使用しています。非標準サイズのボタンが必要な場合は、動作が非常に悪いため、次のレイアウトを持つLinearLayoutを使用してカスタムボタンを作成することにしました。
<?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に設定した場合にのみ、クリックを受け取ることができます。これにより、ボタンがクリックされたときに2つの影響が生じる可能性があります。
- クリックはImageViewまたはTextView内にあります。クリックは正常に登録されていますが、ボタンの状態は描画可能に変更されません。つまり、押されたようには見えません。
- クリックはボタンの「空の領域」内にあります。クリックは登録されていませんが、状態描画可能は問題なく動作します。
これらのどちらも実行可能ではありません。LinearLayoutまたはその子で次の属性を試してみましたが、trueかfalseかにかかわらず、実際には効果がないようです。
- DuplicateParentState
- クリック可能
- フォーカス可能
LinearLayoutの親が子ではなくクリックを受け取るようにする合理的な方法はないようです。カスタムコンポーネント自体でdispatchTouchEventまたはonInterceptTouchEventをオーバーライドするいくつかの可能な解決策を見てきましたが、適切なクリックを識別するためにタッチイベントの分析を開始する必要がある場合、それは本当に大きな混乱のように思えます。
したがって、子を含むLinearLayoutのOnClickListener = no go?
編集:これは、現在、フラグメントのメインレイアウトにボタンを挿入する方法です。
<?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);
...