简体   繁体   中英

On Click event for Parent and Child view

I have a RelativeLayout and an ImageView .
The layout is given below -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rlMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black" >

<ImageView
    android:id="@+id/ivIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_launcher" />

</RelativeLayout>

The Activity code is -

public class MainActivity extends Activity implements OnClickListener{

private RelativeLayout rlMain;
private ImageView ivIcon;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rlMain = (RelativeLayout) findViewById(R.id.rlMain);
    ivIcon = (ImageView) findViewById(R.id.ivIcon);
    rlMain.setOnClickListener(this);
    ivIcon.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.rlMain:
        Toast.makeText(this, "Relative Layout clicked", Toast.LENGTH_SHORT).show();
        break;

    case R.id.ivIcon:
        Toast.makeText(this, "Image View clicked", Toast.LENGTH_SHORT).show();
        break;
    }

}

}

I have applied the on click listener for both the RelativeLayout (parent) and the ImageView (child).
While clicking on the relative layout - it is handled by the relative layout click handler.(This seems to be correct).

While clicking on the Imagview - It is handled by the imageview. (Here is the confusion).

Should the click on the imageview get handled by both the parent(relative layout) and child (imageview)? What is the logic if only the child view is handling the click?

A clickEvent will be delivered to the lowest child element in the layout hierarchy. If this element does not have an onClick behaviour it will pass the event up to its parent until the event gets handled.

Therefore you can treat the LinearLayout as one single block for your onClick behaviour. If you create another clickable element inside the layout be sure to make it big enough to reduce the chance of the user missing the correct item.

Source: Does making parent clickable make all child element clickable as well?

Normally in cases where the image to be clicked is very small in dimension the imageView is kept inside a layout which is given some padding, then the click of the layout is handled. This gives enough area on screen for the user to click on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM