Starting Activity from LinearLayout onClick() Event

Starting an activity from another activity has been explained here. But how to do the same thing from a custom LinearLayout? A button from a LinearLayout will be such a fancy thing than a standard Button. Here how it is done.

Make sure that your LinearLayout has android:clickable property value set to true. Basically done it in XML:

android:clickable="true"

From your activity, get your LinearLayout from it’s id. In this example, my LinearLayout has id: menuNews and I named it as menuNews variable of LinearLayout.

LinearLayout newsMenu = (LinearLayout) this.findViewById(R.id.menuNews);

Inside your activity class, create a local private variable named activity to store your activity references.

private Activity myActivity;

and on your onCreate() method put your activity reference on myActivity variable

this.myActivity = this;

Then, set LinearLayout’s onClickListener with:

newsMenu.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    Log.i("myApp", "newsMenu clicked!");
    Intent i = new Intent(myActivity.getApplicationContext(), NewsActivity.class);
    activity.startActivity(i);
  }
});

That’s it. Your LinearLayout should now clickable and can be used as a Button replacement to start another activity.

4 Replies to “Starting Activity from LinearLayout onClick() Event”

  1. can you please send the entire code. I am trying to create a layout and call an activty from it. so i need the java class file and the xml file. thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

*

CAPTCHA Image

*