Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android view comparing two views for equality

I have 4 buttons on a layout, and for each of the buttons, they have the attribute:

android:onClick="numberChosen"

now, what I had planned on doing was that in my activity (which uses a layout that has the 4 buttons), I have something like:

public class Blah extends Activity{
    String fileName;
    Button one;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number_players_selection_screen);
        one = (Button) findViewById(R.id.number_players_one);
    }


    public void numberChosen(View v){
        if(v == one){                              // <-------- first way
            System.out.println("first way");      
        }
        if(v.getId()==R.id.number_players_one){    // <--------  second way
            System.out.println("second way");
        }
    }
}

if you take note of what happens in the method numberChosen, between these two ways, which one is better? or are they both exactly doing the same thing?

on a side note, is doing android:onClick="numberChosen" any better or worse than just setting the View.onClickListener instead?

like image 691
David T. Avatar asked Mar 25 '13 10:03

David T.


1 Answers

From my point of view, both ways are correct, they get the job done. From performance point view, the second way might be better.

In addition, like some suggested, using the switch case might not be possible if you are using ADT 14 or higher, in a library project, because the IDs are not final (constants), so you have to use if statements in that case only.

like image 118
Leeeeeeelo Avatar answered Nov 09 '22 08:11

Leeeeeeelo