1

I want to use the same xml file for displaying depending upon which button was clicked in the previous page. There is an xml template and depending upon the user's input the output will be shown.

Let's say there are 5 buttons and the layout of the output will be same for all but there will be difference in output data.

  1. How can I get the id of the clicked button in the java file?
  2. Can I use ImageView instead of buttons for the same purpose?

Thanks in advance!

2rs2ts
  • 10,662
  • 10
  • 51
  • 95
user3379410
  • 176
  • 1
  • 11
  • yes, add the click event to your ImageView, then you test it with yourView.getId(); because Button and ImageView inherits from View – Athanor Mar 04 '14 at 14:26

1 Answers1

1

1: You can create an onClickListener in your java class:

Button myButton = (Button) findViewById(R.id.mybutton);    

myButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } });

Or you can use set the click event in your layout-xml and ask the Id of the clicked view, see: How exactly does the android:onClick XML attribute differ from setOnClickListener?

2: You can use an ImageButton instead of a Button/Imageview http://developer.android.com/reference/android/widget/ImageButton.html

Extra: sending info to next Activity

Bundle bundle = new Bundle();
bundle.putString("clickedTag", v.getTag());
intent.putExtras(bundle);

Tip: don't use the Id, but set the android:tag="ABC" to all your buttons, that's better to read than an integer Id. To read the clickedTag use this inside your next Activity:

String tag = getIntent().getExtras().getString("clickedTag");
Community
  • 1
  • 1
Francesco verheye
  • 1,574
  • 2
  • 14
  • 32
  • Thank you very much for your help! But I have too many buttons. Is there any way so that we write only one setOnClickListener function for all the functions (invoking through the clicked button)? – user3379410 Mar 04 '14 at 16:17
  • Yes, you can implement the onClickListener on your Activity (or Fragment) see this: http://anujarosha.wordpress.com/2011/11/13/how-to-implements-onclicklistener-for-a-view-item-in-android/ – Francesco verheye Mar 04 '14 at 16:19
  • It was of great help. Thank you! One last thing I wanted to know, I am using intent to go to the next page. How do I pass my id to the next java file? Since the xml file I will be using is same for all therefore depending on the id of the clicked button I would be displaying the data. – user3379410 Mar 04 '14 at 16:51
  • I updated my solution: don't use the Id but have a look at Tag. Hope you understand it. – Francesco verheye Mar 04 '14 at 16:59