Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANDROID onTouchListener on button array

Tags:

arrays

android

I have put a lot of buttons (16*16) in a button array. The buttons numbers are directly related to changes they should do in another array (e.g. button[12][7] sets the value of stat[12][7] to 1)

So I thought it's possible to put on single line in the onTouch method that reacts to every button. Example (of course, not working)

public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
if(arg0 == button[int a][int b]){stat[a][b]=1};

In this pseudocode, the button would create 2 ints that describe the 2 dimensions of the array which get passed to the stat array.

If anyone had a solution for this, he would save me a few hours this night.

Thanks for your answers.

like image 255
user2875404 Avatar asked Feb 15 '23 11:02

user2875404


2 Answers

I think HasMap is a better solution

private HashMap<Integer,Button> btnMap = new HashMap<Integer, Button>();

private void init(){
    Button yourFirstBtn = (Button) findViewById(R.id.yourFirstBtn);
    btnMap.put(yourFirstBtn.getId(), yourFirstBtn);

    for(Button tempBtn: btnMap.values()){
        tempBtn.setOnClickListener(this);
    }
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
    Button clickedBtn = btnMap.get(v.getId());
}
like image 114
Ismail Sahin Avatar answered Feb 28 '23 05:02

Ismail Sahin


Are you adding the onTouchListener to the buttons' container?

Your best bet is to add an onTouchListener to each button, and then arg0 will correspond to the specific button.

Another option would be to use a GridView, which has an setOnItemClickListener you can use. http://developer.android.com/reference/android/widget/GridView.html

like image 32
Josh Li Avatar answered Feb 28 '23 05:02

Josh Li