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)
Related
This code was working until last night, but now now. I'm wanting a value to be record that is linked to the buttons, I have used set and get tag but is only returning last value.
//create a layout
LinearLayout layout = (LinearLayout)findViewById(R.id.linearlayout);
// create a list of buttons
for(x=0; x<3; x++)
{
newBut = new Button(this);
newBut.setText("("TEXT");
newBut.setTextColor(Color.parseColor("#FFFFFF"));
newBut.setTag(x); //hide job id within the button.
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(newBut.getTag().toString());
System.out.println(newValue); //this just a test to display the value
}
});
layout.addView(newBut);
}
Is the error obvious - not to me.
It is returning the last value, because in all the created listeners you always reference the same button (last value of newBut variable), ignoring the actual click source view you have as the argument. Is should be:
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(v.getTag().toString());
System.out.println(newValue);
}
});
I am duplicating my linear layout dynamically and I have to set onClickListeners for buttons inside the linear layout.
for(int i = 0; i <10 ; i++){
// other code here
Button approve_btn = (Button) findViewById(R.id.rent_number_up_btn);
approve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
approve_btn.setText(String.valueOf(i));
}
});
}
Everything works fine except that my button's text is always set to 9. I think that's because when the listener is called the value of i is 9 at that time. What I want the value of i at the time the button's listener is set and I am not sure how to do that.
How can I solve this problem? Any help is appreciated.
The issue is that you are setting click listener to the same button (by calling findViewById()) 10 times in a row. You get the value 9 because thats the last click listener which you added to the button.
for(int i = 0; i <10 ; i++){
// other code here
Button button = new Button(<Activity Instance>);
button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
approve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
approve_btn.setText(String.valueOf(i));
}
});
}
In above code you need to add those buttons in your linearlayout.
Hope this will help you,
Thanks
I am not sure what you want to do but:
Like #Shaishav said your are using same button (R.id.rent_number_up_btn) and your are replacing the click listeners on top of each other. The last value (of the your counter "i") before your loop finish is 9 , that's why it show 9 all the time. If you want to add 10 buttons inside your Linear layout just create new Button(context) every time when your loop starts and add this button to your layout via
yourLinearlayout.addView(yourNewButton);
Then if you set click listener to your new button maybe it will show different values :)
I dynamically create Buttons by entering a word. If I write "met", it appears on the screen - one Button per letter. The same thing happens for the next word I enter, and it appears below the previous word --- as shown in the image above.
When I click on a Button it turns green. My question is, what is the best way to disable the clicking of a row of Buttons. Meaning, if the user clicks on the 'm' in "met" I want the user to only be able to click on the Buttons in "met" and to not be able to click on any of the Buttons in "had", "goes", or "ran"
Here is my code:
EDIT
int size = enter_txt.getText().toString().length();
for (int i=0; i<size; i++){
final Button dynamicButtons = new Button(view.getContext());
dynamicButtons.setLayoutParams(rlp);
dynamicButtons.getLayoutParams().width = 130;
dynamicButtons.getLayoutParams().height = 130;
dynamicButtons.setTag("0");
dynamicButtons.setId(1);
dynamicButtons.setText(edit_text_array[i]);
dynamicButtons.setBackgroundResource(R.drawable.button);
button_list.add(dynamicButtons);
linearLayout2.addView(dynamicButtons, rlp);
dynamicButtons.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
int i=0;
LinearLayout ll = (LinearLayout) dynamicButtons.getParent();
for(i=0; i<list_of_ll.size();i++){
if (ll == list_of_ll.get(i)){
list_of_ll.get(i).setId(i);
break;
}
}
if(list_of_ll.get(i).getId()==i)
ButtonOnClick(view);
}
});
}
linearLayout2.setId(0);
linearLayout2.setTag("0");
list_of_ll.add(linearLayout2);
EDIT
I created a List of the LinearLayouts for each row of Buttons. The Buttons turn green if the id of the LinearLayout is set to 1. When I click on a Button I want that LinearLayout to stay at 1 and have all other rows/LinearLayouts set to 0 so they become unclickable.
Currently, every Button I click turns green even if it's in a different row. Can someone please help me solve this issue?
Why you don't set Id in the for loop so that you are able to refer and set the onlicklistener to null like jpcrow already mentioned.
Set Id like:
YourCreatedBtn.setId(i+1);
//Id's setted programmatically don't.
have to be unique... But they should be
a positive number (referring to the
android documentation)
And in your on click method simply set onclicklistener for specified Id's to null. Just a hint, hope it helps
Update regarding Thread-openers Comment
I found two simple ways but i would prefer the one which is not commented out in the buttonIsClicked:
LinearLayout llrow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llrow = (LinearLayout) findViewById(R.id.test_layout);
//Adding 5 Buttons
for(int i = 0; i<5; i++) {
Button mybtn = new Button(this);
//set LayoutParams here
mybtn.setId(5);
mybtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonIsClicked(v);
}
});
llrow.addView(mybtn);
}
}
private void buttonIsClicked(View v) {
/*ArrayList<View> myButtons = llrow.getTouchables();
for(int i = 0; i < llrow.getChildCount(); i++){
myButtons.get(i).setOnClickListener(null);
}*/
for(int i = 0; i<llrow.getChildCount(); i++){
llrow.getChildAt(i).setOnClickListener(null);
}
}
It's just a simplified Version of your code, but i'm sure you will get the Content..
What if found out is, that you don't have to set the ID in both cases.. You can easily get all the child over
YourRowLinearLayout.getChildAt(starting from 0 to n-1-Views you added)...
I didn't found a way around the for-loop... But this small-little loop will not break your neck regarding to Performance..
The outcommented-code is the second Approach, finding all the Child over getTouchables which logically leads to an ArrayList and that's exactly the reason why i don't like it. You have to initialize an arraylist...... However, this also won't break your neck regarding to Performance but a penny saved is a penny got! ;) Hope it helps and everything is clear. Both of them work! Please mark as accepted answere if it fits your Needs...
You have to distinguish between the two rows, either add them to different ViewGroups or you can use View.setTag(int key, Object tag)
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.
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.