Search code examples
androidandroid-layoutonclicklistener

set onClickListener with LinearLayout, ImageView, TextView


I have a Linear Layout with ImageView (icon) and TextView ("Settings") inside. Like this :

enter image description here

I would like when the user clicks on the LinearLayout or ImageView or TextView, another Actitivy is started.

So I do this in the code:

OnClickListenerLessons mOnClickListener = new mOnClickListenerLessons(){
@Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), nextActivity.class);
                startActivity(i);
            }}

imageView.setOnClickListener(mOnClickListener);
linearLayout.setOnClickListener(mOnClickListener);
textView.setOnClickListener(mOnClickListener);

And I found that it is quite bulky and messy, is there anyway to make the code cleaner?

Many thanks!

P.S: here is my xml file

 <LinearLayout>
     ...
      <LinearLayout
            android:id="@+id/linear_layout_wrapper_lessons"
            style="@style/width_height_margin_for_items"
            android:layout_weight="25"
            android:clickable="true"
            android:gravity="center"
            android:orientation="horizontal" >
            <ImageView
                android:id="@+id/lessons_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/puzzle_piece" />

            <TextView
                android:id="@+id/home_lesson_textView"
                style="@style/text_view"
                android:clickable="true"
                android:text="@string/home_lesson_button" />
        </LinearLayout>
    ...
</LinearLayout>

here is the style.xml for text_view

<style name="text_view">
    <item name="android:background">@null</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:textSize">22sp</item>
    <item name="android:layout_margin">5dp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@color/home_buttons_select_state_color</item>
</style>

Solution

  • When you set an onClickListener to TextView or ImageView, you should also declare those as android:clickable="true" or setClickable(true).

    Also having a LinearLayout with an ImageView and a TextView might not be necesseary, why don't you just add the image with android:drawableLeft? Nesting LinearLayouts is a very bad habit.