سؤال

This is MainActivity.java and main.xml:

public class MainActivity extends Activity
{   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                ((LinearLayout) findViewById(R.id.main_layout)).setOnClickListener(new OnClickListener(){

                                @Override
                                public void onClick(View p1)
                                {
                                        Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
                                }
                        });       
    }   
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:gravity="center"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="#75F575">

    <LinearLayout
        android:layout_gravity="center"
        android:orientation="vertical"
        android:layout_width="250dp"
        android:layout_height="100dp"
        android:background="#C69817">

        <TextView
            android:ellipsize="end"
            android:layout_gravity="center_vertical"
            android:id="@+id/title_text"
            android:layout_width="228.0dip"
            android:layout_height="wrap_content"
            android:layout_marginLeft="9.299988dip"
            android:singleLine="true"
            android:text="Text"/>

    </LinearLayout>

</LinearLayout>

When I click on 1st (green) and 2nd (yellow) layout - a Toast will shows on both layouts. But I need the Toast to show up only when I click on 1st layout (@+id/main_layout), and NOT TO SHOW UP when I click on the child views (another (yellow) layout and other views). How do I do this?

هل كانت مفيدة؟

المحلول

You need to set attribute android:clickable="true" for the second LinearLayout (yellow one) with implementing NO listener to it (no changes in java). This will show the toast only when the first LinearLayout (green one) is clicked.

P.S. You still can implement listeners to childs of the second LinearLayout, e.g. TextView in your case.

نصائح أخرى

An easy way would be to setOnClickListener on each of your childviews with an onClick method doing nothing.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top