GHousy8909 GHousy8909 -4 years ago 99
Java Question

Avoid clicking of full layout

I only want my textview with id

clickable_txtView
to be clickable in relative layout. Here is the code -

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@android:id/empty"
android:clickable="false">

<ImageView
android:layout_width="120sp"
android:layout_height="130sp"
android:layout_centerHorizontal="true"
android:src="@drawable/flower"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="120sp"
android:text="Dont click me />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/clickable_txtView"
android:gravity="center"
android:paddingTop="140sp"
android:clickable="true"
android:text="Click me" />
</RelativeLayout>

@OnClick(R.id.clickable_txtView)
public void txtViewClick() {
//Some event
}


Thr problem is I am able to click whole relative layout and some event happens after onclicking relative layout.
How do I avoid this and make it limited to text view only.

Answer Source

Your textview has an attribute android:paddingTop="140sp" which basically wraps over the entire relative layout, because of which you are having the problem with onClick behaviour.

enter image description here

Use this RelativeLayout structure (provide ID to the "don't click me" textview, and place the "clickable textview" below it.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/empty"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:layout_width="120sp"
        android:layout_height="130sp"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher"
        android:layout_alignParentTop="true"
        />

    <TextView
        android:id="@+id/do_not_click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingTop="120sp"
        android:enabled="false"
        android:text="Dont click me" />

    <TextView
        android:id="@+id/clickable_txtView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:gravity="center"
        android:layout_below="@id/do_not_click"
        android:text="Click me" />

</RelativeLayout>

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download