The problem was that setMovementMethod
was being called on the TextView and I didn't notice.
Android LinearLayout, last added children stealing click for onClickListener
-
20-06-2023 - |
Question
Setup:
I have a custom LinearLayout that has a TextView and an ImageView inside it (my attempts to resolve the issue are commented out):
public class MyTextView extends LinearLayout {
private final TextView textView;
private final ImageView imageView;
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
textView = new TextView(context);
imageView = new ImageView(context);
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(layoutParams);
imageView.setImageResource(R.drawable.img);
/* imageView.setDuplicateParentStateEnabled(true);
textView.setDuplicateParentStateEnabled(true); */
/* imageView.setFocusable(false);
textView.setFocusable(false);
textView.setTextIsSelectable(false); */
addView(textView);
addView(imageView);
/* this.setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);
this.setClickable(true); */
}
}
I'm including this custom LinearLayout in a larger 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:orientation="vertical" >
<my.package.MyTextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
I'm setting an onClickListener this way:
final MyTextView textView = (MyTextView) view.findViewById(R.id.textView);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Code
}
});
My issue:
The onClickListener only fires if I tap the ImageView, and not the TextView. I'd like it to work if I tap any part of the LinearLayout instead.
I can't understand why this wouldn't work, not even with e.g. setDescendantFocusability set to FOCUS_BLOCK_DESCENDANTS, and would appreciate an explanation. Thanks a lot.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow