How to get the text from the Button when clicked? [duplicate] - android

This question already has answers here:
Get text from pressed button
(8 answers)
Closed 9 years ago.
for( i=0; i<26; i++) {
btnAlpha[i] = new Button(this);
btnAlpha[i].setBackgroundColor(Color.TRANSPARENT);
btnAlpha[i].setTextColor(Color.GREEN);
btnAlpha[i].setText(Character.toString ((char)(j+i)));
btnAlpha[i].setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//Want to get the text from the current button.
btnAlpha[i].getText();
//But it gives error that "i" cannot be accessed.
}});
I get the error "cannot refer to a non-final variable inside an inner class defined in a different method". But I need to get the text at that right time. How to do it? Is there any other way to do it?

Button is a subclass of View, so the argument to onClick, v, is the Button being clicked. Try
public void onClick(View v) {
((Button) v).getText();
}

create a new variable final int x = i; in the for loop and use x in place of i in the onClick method
edit: actually im not sure this will work correctly. oops. Kype P's answer looks pretty good.

Related

Changing the background image of Text View whenever the button is pressed

Whenever the user presses the button, the text of the TextView, as well as the background image of TextView, is changed. I have created an int[] array to store the id of drawable to use in TextView.setBackgroundResource(array[index]) . But on incrementing the index the background is not changed. I even tried hardcoded index for array[] but it still sets first element image.
//j and drawable array are global variable.
int j=1;
int[] drawablearray=new int[]{R.drawable.girl,R.drawable.beach,R.drawable.flower};
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(j<drawablearray.length-1){
j++;
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
}else{
j=0;
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
}
});
It seems everthing OK in your code.
Did you initialised nextButton properly?
Probably your click is not working.
UPDATE
I have updated your code:
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(j<drawablearray.length){
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
j++;
}else{
quoteTextView.setBackgroundResource(R.drawable.girl);
quoteTextView.getBackground().setAlpha(150);
}
}
});
For the first 3 clicks it will show three different images then sets to default image
Your j variable must be 'global'. It means that it must a member of your Activity or Fragment but not a variable inside your method
Instead of the "if" condition I suggest you to use:
j = (j+1) % drawablearray.length;
Then the variable j must be a field of your java class (declare it outside every method)

How can I change Text of Textview from other funcion?

this is my first question so I hope to make it clear.
I have one textView with some numerical text and next to it one button with one click listener and what I want is that when you click on the button the numerical value (>=0) of the TextView decrements in one.
Here is part of my code:
TextView Counter = new TextView(this);
if (intSeries != 0)
Counter.setText(Integer.toString(intSeries));
else
Counter.setText("0");
Counter.setId(4);
tablaContador.addView(Counter,Tr);
Button Done = new Button(this);
Done.setText("-1");
if (intSeries != 0)
Done.setVisibility(View.VISIBLE);
else
Done.setVisibility(View.GONE);
Done.setId(6);
Done.setOnClickListener(this);
And this is the onClick funcion (part of it):
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case 6:{
TextView text = (TextView)findViewById(4);
int series = Integer.parseInt(text.getText().toString());
series--;
text.setText(series);
if (series==0){
Button boton = (Button)findViewById(6);
boton.setVisibility(View.GONE);
}
}
}
}
The error is when I try to make the setText inside the onClick function, I hope it can be fixed or maybe recieve other idea to do it.
Thank you so much.
I would avoid all this hardcoding of Ids, use resources instead.
Your call to
text.setText(series)
is passing an int. The only valid setText(int resId) overload expects a resource associated with the int value, i.e. a string resource.
Convert your series value to a string.
Something like:
text.setText(Integer.toString(series));
You should setup series as an integer. And increase/descrease it as you wish. When you want to change the button's text convert the int to String.
Instead of:
text.setText(series);
use:
text.setText(String.valueOf(series));
Variablenames in java can't start with a capital letter. That is reserved for classnames.
Counter -> counter
Done -> done
I tried this and it worked:
//Create onClickListener
OnClickListener pickChoice = new OnClickListener()
{
public void onClick(View v)
{
TextView txt = (TextView) findViewById(4);
int number = Integer.valueOf(txt.getText().toString());
txt.setText(String.valueOf(number -1));
}
};
//Create layout
LinearLayout lnLayout = new LinearLayout(this);
lnLayout.setOrientation(LinearLayout.VERTICAL);
TextView txt = new TextView(this);
txt.setId(4);
txt.setText("0");
lnLayout.addView(txt);
Button Done = new Button(this);
Done.setText("-1");
Done.setId(6);
Done.setOnClickListener(pickChoice);
lnLayout.addView(Done);
setContentView(lnLayout);
Where are you creating your button inside? an activity? the part where you pass the onClickListener to the button doesn't make sense, maybe the button is getting a wrong listener and gets you an error every time you press the button ?
The code should be easy to understand, if there is anything you need me to explain please ask :)

How to manage setOnClickListener on a array of buttons

I have a dynamic array of buttons and I would like to know how to handle the onclick on every button?
Thanks
I don't see a need to create a new OnClickListener for each button -- all the buttons could share a single listener.
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
Object tag = v.getTag();
// Do something depending on the value of the tag
}
};
...
for (int i=0; i < btns.length; ++i) {
btns[i].setOnClickListener(myListener);
btns[i].setTag(some_identifying_information);
}
Of course, you could create a unique OnClickListener for each button, and take advantage this way:
for (int i=0; i < btns.length; ++i) {
final Button btn = btns[i];
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something depending on the value of btn, which you're allowed
// to reference here because it was declared final above.
}
});
}
The same way you would on a single button...
Set an on click listener, if you have an Array it would look something like this:
btns[0].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
btns[1].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
//etc.
If you want all of them to do the same thing you could use a for loop to loop over the array like this:
for(int i = 0; i< btns.length; i++){
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
}
I don't know exactly what you are doing but if you have an Array of Buttons it is likely that you should probably be using an Adapter with a ListView or something instead of how every you are doing it now.
Without seeing some code or more of an explanation, it's hard to really answer your question, but here are some tips:
Before we get to the listeners, we have to make sure that each of the dynamically created buttons knows how to respond to a click event. You can use the setTag method on a button to attach an arbitrary Object to it. This Object will represent how the Button acts when clicked. You can just use Integers as this Object (perhaps some constant values) or if each button needs some unique data, create a class that maintains both how the button needs to act when clicked AND the data you need (or at least a reference to it).
Then, you can initialize one single listener that handles all of your button clicks. In the onClick method of this listener place a conditional that branches to handle all of your click cases. Set this listener on all of your dynamic buttons as you create them. At the start of your onClick, get the Tag from the View parameter of the onClick method (this view will be the button that was clicked), and use that to decide which branch of the conditional to take.
Hope this helps. If you make your question more specific, we'll be able to offer some more detailed assistance.

Updating arrayIndex onClick of button is causing problem

I am implementing a quiz and here am having a method for my button as
public void playquiz(final int arrayIndex) {
setContentView(R.layout.quiz);
next = (Button) findViewById(R.id.nextBtn);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (arrayIndex == TourDescription.currentTour.getTriviaArray().size()) {
int totalpoints = correctAnswerCount*10;
Intent scoreintent = new Intent(TriviaQuiz.this,ScoreBoard.class);
startActivity(scoreintent);
}
else
{
playquiz(arrayIndex+1);
}
}
What I am trying to do is, inside the method I am loading another layout and assigning an onclick for the button in that layout.
Now my problem is, the arrayIndex which I get initially, I have to update this on click of the next button and based on this I have some other conditions to check.
But if I do like playquiz(arrayIndex+1);, it asks me to declare the arrayIndex as final, why is this?
And even then it is not behaving in the exact way as it supposed to be.
The if (arrayIndex == TourDescription.currentTour.getTriviaArray().size()) inside onClick is not happening
Any suggestion?
But if I do like playquiz(arrayIndex+1);, it asks me to declare the arrayIndex as final, why is this?
This is because you are using it inside another class - OnClickListener() and arrayIndex is probably a local variable. There are two ways to getting around this.
declare it in the global declaration area.
your class should implement OnClickListener and override OnClick method within which you must include your codes.
The if (arrayIndex == TourDescription.currentTour.getTriviaArray().size()) inside onClick is not happening
I am not sure if you have provided enough code here but by just looking at it i cannot see arrayIndex being incremented and hence it will never get to TourDescription.currentTour.getTriviaArray().size(). You need to increment arrayIndex
it in the else clause.

How can I find out which view currently has focus? [duplicate]

This question already has answers here:
How to find out which view is focused?
(6 answers)
Closed 6 years ago.
My app uses keyboard control and when moving around I've noticed that occasionally you get what I'll refer to as a "Mystery View" - I say that because nothing visible seems to be selected, yet nothing visible is focussed either
Is there any way to find out what I'm focussed on at any given time? eg. a listener that fires on a view selection, etc.
Thanks
** edit - some code for ntc **
LinearLayout col1 = (LinearLayout)findViewById(R.id.col1);
Button btn = new Button(this);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LinearLayout col1 = (LinearLayout)findViewById(R.id.col1);
if(col1.getFocusedChild() != null) {
Log.d(TAG, col1.getFocusedChild().toString());
}
}
});
col1.addChild(btn);
getWindow().getCurrentFocus();
You can probably use this method for every view. Maybe this may gets bigger and hectic but is sure to work:
if(yourChildView.isFocused()) {
yourChildView.setFocusable(false);
}

Categories

Resources