Is there a way to have 1 onClick Lister for many buttons where I can toss a case statement to do things based on what buttons were clicked.
I know I can make 100 different listeners for 100 buttons but I have to think I can create some nifty variables to do it in less lines of code.
Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};
If you are using 1.6+ version of the SDK you can use android:onClick to set the onClick handler of a view. In your activity you must have a method with the following signature. The view is the view that was clicked.
void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
//do something fantastic;
break;
}
}
public class MainActivity extends Activity implements View.OnClickListener{
btnXXX.setOnClickListener(this);
public void onClick(View v) {
if (v.getId()==R.id.btnXXX){
dialog.show();
} else {
handleOtherViews(v);
}
}
Alternatively, you can specify the method to call in xml:
<Button android:id="#id/button" android:text="#string/button" android:onClick="someMethod" />
Related
I have a layout which contains some views. I want to set some actions when a user clicks anywhere on the layout, so I have set an OnClickListener for the layout which works as it should. But how can I know which view was clicked?
I want to assign different actions depending on the view which was clicked; or maybe no view was clicked and it was only the layout itself.
So the problem is if I set OnClickListener for one of the views, both OnCLickListeners related to the layout and the view will get activated, but I want only the view action. Thanks in advance.
Other answers are quite abstract and some are incorrect. You can't Override onClick method for an Activity as it doesn't have one (unless of course you implement an OnClickListener).
Furthermore, if you set the listener for the layout the View argument received by the onClick method will always be the layout.
You can either create your own custom layout that intercepts the clicks and check if you clicked on a view, or you can set listeners for all the views.
A somewhat cleaner solution is using a single listener and checking if it's a view that was clicked.
private final String TAG = "MainActivity";
List<View> views = new ArrayList<View>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
TextView tv1 = (TextView) findViewById(R.id.tv1);
TextView tv2 = (TextView) findViewById(R.id.tv2);
TextView tv3 = (TextView) findViewById(R.id.tv3);
views.add(tv1);
views.add(tv2);
views.add(tv3);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isView = false;
for (View view : views) {
if (v.equals(view)) {
isView = true;
break;
}
}
if (isView) {
Log.e(TAG, "Click on view");
} else {
Log.e(TAG, "Click on layout");
}
}
};
tv1.setOnClickListener(clickListener);
tv2.setOnClickListener(clickListener);
tv3.setOnClickListener(clickListener);
rLayout.setOnClickListener(clickListener);
}
If you want different actions for different views, just create a listener for each of them.
For example Layout has two views View1 and View2. I assume that you have already inflated them. So you have to set OnClickListiner for each of them
Layout.setOnClickListener(this);
View1.setOnClickListener(this);
View2.setOnClickListener(this);
Then you have to override method:
public void onClick(View v)
{
switch(v.getId())
{
case R.id.id_for_layout:
// do what you want when user click layout
break;
case R.id.id_for_first_view:
// do what you want when user click first view
break;
case R.id.id_for_second_view:
// do what you want when user click second view
break;
}
}
Remember that the method OnClick have one parameter that indicates which View is clicked!
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn1:
// first button
break;
case R.id.btn2:
// second button
break;
}
}
Assign the id to each of your views by android:id="#+id/v1"
then in
onClick(View v)
check for the view like
if(v == findViewById(R.id.v1))
{
// v1 specific action
}
else if(v == findViewById(R.id.v2))
{
// v2 specific action
}
Ok, it's easy.
You have to add an OnClickListener to each view (button, textView and so on), and to the whole layout as well.
In this case, the onClickListeners that will be launched if you click are the view's onClickListener and the layout's onClickListener. So no need for a whole bunch of classes. One will be enough if you try this (do actions depending on the id and don't forget the layout ;) ):
public void onClick(View v) {
switch(v.getId()) {
case R.id.layout:
layout actions here
break;
case R.id.textview:
textview actions here
break;
this onClickListener is for all of your views ;)
There is View v parameter in onClickListner(View v) method :
#Override
protected void onCreate(Bundle savedInstanceState) {
LinearLayout layout=(LinearLayout)findViewById(R.id.linearLayout);
layout.setOnclickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.linearLayout){
//your logic
}
}
for anyone interested you can also log the currently clicked view:
getActivity()
.getWindow()
.getDecorView()
.findViewById(android.R.id.content)
.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.v("[onClick]", v.getClass().getCanonicalName());
}
return false;
});
I have a serie of ImageViews on my Activity. And I wanna execute a method when one of these is touched. I have the next:
public void onClick(View v) {
switch(v.getId()){
case R.id.image1:
mymethod(1,1,movimientos,(ImageView)v);
break;
case R.id.image2:
ponerficha(1,2,movimientos,(ImageView)v);
break;
case R.id.image3:
...
But the method isn't executed, The problem not is the method, because any code in the cases not work. Any idea?
First thing what you need to check if you already register onClickListener for your Images
image.setOnClickListener(this);
(This you have to use if your class implements OnClickListener interface)
Then how you declare and initialize your ImageViews, whether have own ids.
image = (ImageView) findViewById(R.id.someId)
anotherImage = (ImageView) findViewById(R.id.anotherId)
...
You can work with onClickListeners like with anonyme classes like
image.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// some actions
}
});
but more complex and better in the case you have many widgets to set implement OnClickListener.
public class ClassName extends Activity implements View.OnClickListener {}
First, your activity has to implement View.OnClickListener like so
public class myActivity implements View.OnClickListener {
Then you need to set your on click listener for your ImageViews. If all your ImageViews are in a linearlayout then the code would look like this
LinearLayout llImageViewHolder = (LinearLayout) findViewById(R.id.llImageViewHolder);
for (int i = 0; i < llImageViewHolder.getChildCount(); i++ {
ImageView iv = (ImageView) llImageViewHolder.getChildAt(i);
iv.setOnClickListener(this);
}
Cheers.
You need to add an onClick handler to each view you are interested in processing clicks for.
How you do it depends on how you want to process the click events. You can either use hawaii.five-0's approach and have one event handler for everything, or you can have one event handler per view item which you could add in the onCreate method of your activity:
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// Do something
}
}
I create a whole layout setup in XML then attempt to attach listeners to the buttons using findViewById(). The problem I am having now is that the View parameter I receive in the method does not contain the ID of the view I clicked: 830009633920 vs 2131099657.
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnNext) {
...
}
}
How about this:
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.btnNext:
...
break;
case R.id.foo:
...
break;
}
}
That should be working, so my only guess without seeing the rest of the code or layout is that you have set click handlers on two items that overlap.
If you plan on making an Android Library project switch like this will not work due to a recent change in the tool chain.
http://tools.android.com/tips/non-constant-fields
In general I find it is much simpler to use an anonymous class the handle clicks rather than a large single handler.
btnNext.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
...
}
});
You might try this approach just to debug that the item you expect to get the click is what you are pressing, to make sure you don't have layout issues.
Try skipping the IDs, and just compare the actually view object. so something like this:
#Override
public void onClick(View view) {
if (view.equals(btnNext)) {
...
}
}
I want to implement a click listener for a button on my main view. My code is something like below
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.btnFinish);
// Register the onClick listener with the implementation above
button.setOnClickListener(mFinishListener);
...
}
private OnClickListener mFinishListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
But shows me error as follows
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (DialogInterface.OnClickListener) MobileTrackerActivity.java /MobileTracker/src/com/example/mobiletracker line 37 Java Problem
I have no idea what to do. Please help.
You are not using the correct interface to instantiate the mFinishLinstener variable...
It is possible you have an import specifying DialogInterface and that is confusing the view.
Try specifying View.OnClickListener explicitly.
private View.OnClickListener mFinishListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
As per my opinion Best way to implement On click event for the Button.
Instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute. For example:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/self_destruct"
android:onClick="selfDestruct" />
Now, when a user clicks the button, the Android system calls the activity's selfDestruct(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example:
public void selfDestruct(View view) {
// Kabloey
}
Note: The above code is given in Android SDK - Button.
try this code :::
final Button button = (Button) findViewById(R.id.btnFinish);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
Simply try this one as:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// do something when the button is clicked
}
};
you can also use like below code..
Button button = (Button)findViewById(R.id.btnFinish);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
//Write Your code here
}
});
You can also declare the onclick in the xml.
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onclick="buttonClick" />
And in your code you would define the function as:
public void buttonClick(View view)
{
// handle click
}
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.
#Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..
Update: code could be soemthing along these lines:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
as a method in the activity and then use it in the loop like this
button.setOnClickListener(getOnClickDoSomething(button));
I got one solution for this..
use this code in onCreate
linear = (LinearLayout) findViewById(R.id.linear);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
btn[i] = new Button(getApplicationContext());
btn[i].setText(num_array_name[i].toString());
btn[i].setTextColor(Color.parseColor("#000000"));
btn[i].setTextSize(20);
btn[i].setHeight(100);
btn[i].setLayoutParams(param);
btn[i].setPadding(15, 5, 15, 5);
linear.addView(btn[i]);
btn[i].setOnClickListener(handleOnClick(btn[i]));
}
after onCreate create one method of return type View.OnClickListener like this..
View.OnClickListener handleOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
}
};
}
Button.OnClickListener btnclick = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button)v;
Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();
}
};
call this listener by btn.setOnClickListener(btnclick);
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.
Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().
instead use setTag() function to distinct easily.
for(int i=0;i<4;i++) {
Button btn = new Button(this);
btn.setTag(i);
btn.setOnClickListener(new View.OnclickListener() {
#Override
public void onClick(View v) {
int i=v.getTag();
switch(i) {
case 1: btn.setText(i);
break;
case 2: btn.setText(i);
break;
case 3: btn.setText(i);
break;
case 4: btn.setText(i);
break;
default: btn.setText("Others");
}
}
}
"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.
I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.
Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout
This answer may you help:
https://stackoverflow.com/a/5291891/2804001
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}