我一直在使用带有图标(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,我只能接收点击。单击按钮时,这会导致两种可能的效果:
- 单击位于 ImageView 或 TextView 内部。单击已注册正常,但按钮状态可绘制并没有改变,即它没有显示为按下状态。
- 单击位于按钮的“空白区域”内。点击未注册,但状态可绘制工作正常。
这两种方法都不可行。我已经在 LinearLayout 或其子级上使用了以下属性,但无论 true 或 false,似乎都没有任何效果:
- 重复父状态
- 可点击
- 可聚焦
似乎没有任何合理的方法可以让 LinearLayout 父级而不是其子级接收点击。我已经看到一些可能的解决方案覆盖自定义组件本身的dispatchTouchEvent或onInterceptTouchEvent,但如果我必须开始分析触摸事件来识别正确的点击,那确实看起来很困惑。
那么带有子项的 LinearLayout 上的 OnClickListener = 不行吗?
编辑: 这就是我目前将按钮插入 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" />
...
按钮在Fragment的代码中绑定(bind)如下:
@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
上设置了监听器吗(因为您有两个,父级和膨胀布局中的一个)。前段时间我制作了一个类似的组件,监听器工作没有任何问题(我不知道你在这些样式中有什么)。唯一的区别是我没有添加(不需要的)LinearLayout
,而是使用了merge
标记:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<ImageView
android:id="@+id/buttonIcon"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/buttonText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/white" />
</merge>
并在父LinearLayout
上设置样式。
关于android - LinearLayout 作为自定义按钮,OnClickListener 从未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12234543/