Android:使用TextView和Button onClick on LinearLayout

Ter*_*rry 5 android onclick android-layout android-xml

我有一个使用以下XML布局的Fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/card"
    android:clickable="true"
    android:onClick="editActions"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title"
        style="@style/CardTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:duplicateParentState="true"
        android:text="@string/title_workstation" />

    <Button
        android:id="@+id/factory_button_edit"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:duplicateParentState="true"
        android:text="@string/label_edit" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

如您所见,我有一个onClick参数设置LinearLayout.现在,TextView这个正确触发,并在所有空白区域.就在Button它上面没有调用我设置的onClick方法.

这是正常的吗?我该怎么做才能在所有地方调用onClick方法LinearLayout

小智 10

这是您在LinearLayout中所需要的:

android:onClick="editActions" 
android:clickable="true"
Run Code Online (Sandbox Code Playgroud)

并且在你的类中调用xml的一些方法:

public void editActions(View view){

           //something TODO

    }
Run Code Online (Sandbox Code Playgroud)


小智 6

在代码中直接为你的按钮添加onClick Action,如下所示:

Button btn = findViewById(R.id.factory_button_edit);
btn.setOnClickListener(button_click);

      OnClickListener button_click = new OnClickListener() {

        @Override
        public void onClick(View v) {
            editActions;
        }
    };
Run Code Online (Sandbox Code Playgroud)

或者xml添加

android:onClick="editActions"
Run Code Online (Sandbox Code Playgroud)

到你的按钮

  • 我通过在我的按钮中添加`android:clickable ="false"`解决了这个问题.但是你的解决方案有相同的结果,所以我接受它作为正确的答案. (5认同)
  • @Terry,你的答案更好,因为按钮实际上是从它的父布局"窃取"事件,因此将其可点击的attr设置为false更合适. (2认同)

Yur*_*ets 5

要使您的布局与其子级可点击,您需要为每个子级添加此选项:

 android:clickable="false"
Run Code Online (Sandbox Code Playgroud)

然后点击处理将上升parent