ProBul ProBul - 4 months ago 9
Android Question

How can I pass View parameter (TextView) from OnClickListener to public methode

I`m trying to use same methode for different Views. Each time i want to pass different TextView to work with, as follows:

ibIncreaseA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//increase the counter in textView
increase(view);
}
});

ibIncreaseB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//increase the counter in textView
increase(view);
}
});


and this is the desired methode:

public void increase (View textView ){
int calculatedValue;
try {
String counter = textView.getText().toString();
calculatedValue = Integer.parseInt(counter) + 1;
tvNumOfTickets.setText(String.valueOf(calculatedValue));
}catch (Exception e){
e.printStackTrace();
}
}


my problem is that the textView in the methode does not allow me to use .setText().
How can I make it work?

Answer

try below code

try {
    String counter = ((TextView)textView ).getText().toString();
    calculatedValue = Integer.parseInt(counter) + 1;
    ((TextView)textView ).setText(String.valueOf(calculatedValue));
}catch (Exception e){
    e.printStackTrace();
}
Comments