I have a Fragment that uses the following XML layout:
<?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>
As you can see, I have an onClick parameter set on LinearLayout. Now on the TextView this one is triggered correctly, and on all empty area. Just on the Button it doesn't invoke the onClick method that I set.
Is this normal? What do I have to do so that the onClick method is invoked everywhere on the LinearLayout?
How to add a TextView to a LinearLayout dynamically in Android? This example demonstrates about How to add a TextView to a LinearLayout dynamically in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
how to set onClick Listener for layouts [android]. LinearLayout mLinearLayout = findViewById(R.id.your_linear_layout_name); mLinearLayout.setonClickListener(new View.onClickListener(){ @Overide public void onClick(View v){ //do want to do here } });
For the listview just use setOnItemCLickListener (). Back to what you want, I think you need to make the linearlayout focusable/touchable in order to "receive" clicks. Great catch by @duggu. Apart from the answer, using ImageView and TextView inside a LinearLayout, nesting LinearLayout is a bad idea.
You have two methods to respond button click event as below. Create a View.OnClickListener object and assign the object to the button instance use the setOnClickListener () method. ...... button3.setOnClickListener (new View.OnClickListener () { @Override public void onClick (View view) { ...... } });
This is what you need in your LinearLayout :
android:onClick="editActions"
android:clickable="true"
and also in your class which call that xml some method:
public void editActions(View view){
//something TODO
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With