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 :)
Related
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 one activity and here i have 100 buttons, i want that when i press Button 1 then press another Button the Button 1 should get unpressed.
i know i can make this with
if(Button1.isPressed()) {
Button2.setPressed(false);
Button3.setPressed(false);
Button4.setPressed(false);
Button5.setPressed(false);
Button6.setPressed(false);
Button7.setPressed(false);
Button8.setPressed(false);
......................... }
else { do nothing }
.... BUT!
it's too much code
Coders will kill me or will just laugh on me.
any ideas?
maybe there is a way to unpress the all buttons from the activity?
Not the prettiest solution ever, but you could make an OnClickListener like this:
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
ViewGroup parent = (ViewGroup) v.getParent();
for (int i = 0; i < parent.getChildCount(); i++) {
View current = parent.getChildAt(i);
if (current != v && current instanceof Button) {
((Button) current).setPressed(false);
}
}
((Button) v).setPressed(true);
}
}
and attach it to all of your buttons.
Then, whenever a button is clicked, it will iterate over all views that are in the same layout (or actually, view group) as the clicked button, and, for any of those views that are buttons except for the clicked button, it will call setPressed(false).
Note that this only works out of the box if all the buttons are in the same layout. If they are in nested layouts, you will have to adapt it a little.
Off topic: What do you need 100 buttons for? That's a lot of buttons. You may want to redesign your user interface
Ok so instead of looping through all the buttons on over and over again when one button is pressed, you can just store a variable which stores the button number of the button that was last pressed. Now, when the second button is pressed, disable the button that was pressed earlier, you get its index from the saved variable, enable the button that was pressed and store its index in the variable.
Heres an example pseudo code to give you and idea:
int buttonLastPressed = 0;
void onButtonClick(Button buttonPressed){
if(buttonLastPressed != 0){
disableButton(buttonLastPressed);
enableButton(buttonPressed);
buttonLastPressed = buttonPressed.getIndex()
}
}
Saves you from looping through each and every button to disable it.
Define id of button 1 to 100
When press button occurs save it's id in some member variable like previous_pressed
Before updating a previous_pressed value find and unpress previous pressed button like this
Button previous_pressed_button = (Button) findViewById(previous_pressed);
Now you have the previous pressed button, So upress it or whatever.
I have a Activity in android that has 4 buttons.
The first 3 buttons fetches a json data from a weather API for 1 day, next 5 days and next 10 days respectively.
I have a 4th button placed at the bottom of the screen, which takes user to second activity.
I want to restrict the entry of user to second Activity if no button from top 3 is clicked.
If the data is fetched, I mean any one of the top 3 buttons have been clicked, allow him to go to second activity on 4th button click else show a message.
How can i check on click of 4th button if any of the top 3 buttons have been clicked before?
Thanks
Put a boolean field in your activity, name it clicked and set it to false on the onCreate method of your first activity, then in the onClick method of your 3 buttons, set it to true,
and in the onClick method of your 4th button check it, if it's true go startActivity, else launch a Toast
You can make the 4th button look disable in "OnCreate" with the function "setEnabled"(may be wrong),
and then just set "setOnClickListener" for the 4th button when you click any of the others.
ps.
Can provide code example if needed.
Why don't you use if statement? You can keep the clicked count data under the first three buttons. Like this;
import java.util.stream.*;
int[] btnMemory = new int[4];
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnMemory[0] = 1;
// your code
}
});
after, you can check it with if statement under 4th button;
button4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int sum = IntStream.of(btnMemory).sum();
if(sum >= 3)
// your code
}
});
Currently i am having some problem with implementing onclicklistener to a dynamically creating textview. I will explain the problem more detailed. What i need to do is, i need to create textviews when i click a button in an activity and when i click on that textview it should get removed. but i am not able to set onclicklistener to each textview. Since, set onclicklistener of textviews are written inside the onclick function of the above said button(button used for creating the textview), its scope get over when it exits from onclick function of the button(i think this is the problem). So i tried using visible and invisible feature, which will create the textviews before hand and make them invisible and they are made visible only when the button(button used for creating the textview)is clicked. But here even though it is invisible the space will be allocated(ie, blank space will be availabe).
Here is my code
This button addphone will dynamically create textview by inserting the value present in the edittext phoneno
addphone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(phoneno.getText().toString().length() > 0 && counter < MAX)
{
addphoneno[counter] = phoneno.getText().toString();
phoneno.setText("");
final TextView mybox = new TextView(getApplicationContext());
mybox.setText(addphoneno[counter]);
mybox.setPadding(5, 5, 5, 5);
mybox.setBackgroundColor(Color.rgb(99, 99, 99));
contactbox[counter] = mybox;
contactbox[counter].setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
contactbox[counter].setId(100+counter);
contactbox[counter].setText(addphoneno[counter]+" "+"X");
contactbox[counter].setClickable(true);
contactbox[counter].setOnClickListener(this); //This doesn't work!!!!!
counter = counter+1;
}
}
});
But the setOnClickListener in the above line is not working
So can anyone pls help me with this problem. I hope you are clear with my question.
Thank You!
You can try this:
private OnClickListener phoneViewClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// your code
}
};
and use that listener in your TextViews:
contactbox[counter].setOnClickListener(phoneViewClickListener);
You will have to actually define a onClickListener instead of simply setting it as a boolean value.
contactbox[counter].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//this is where you would handle your click event
}
});
Good luck!
If your button was defined on the xml layout you can do that.
In your xml layout you can define which method will be called when a user click on your button:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/add_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="addTextView" /> // This is most imporant line
Your activity must have a method with the same name with a View parameter, like that:
/** Called when the user touches the button */
public void addTextView(View view) {
// Do something in response to button click
if(phoneno.getText().toString().length() > 0 && counter < MAX)
{
addphoneno[counter] = phoneno.getText().toString();
phoneno.setText("");
final TextView mybox = new TextView(getApplicationContext());
mybox.setText(addphoneno[counter]);
mybox.setPadding(5, 5, 5, 5);
mybox.setBackgroundColor(Color.rgb(99, 99, 99));
contactbox[counter] = mybox;
contactbox[counter].setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
contactbox[counter].setId(100+counter);
contactbox[counter].setText(addphoneno[counter]+" "+"X");
contactbox[counter].setClickable(true);
contactbox[counter].setOnClickListener(this); //This will work \o/
counter = counter+1;
}
}
}
On this method you should put your code to addViews.
As the behavior of all added textview must to be the same( i understood in that way), be removed when a user clicked on it, you can make your activity implements onClickListener and with that you just need to implement correctly the onClick method of your activity.
In my app, i am loading a layout dynamically with text views ,on a button's onclick event. when i click the button for the first time , i got my layout with text views. when i click it again ,it should display the layout again. but its showing error. my code is
private OnClickListener some_name = new OnClickListener(){
public void onClick(View v) {
LinearLayout my_list_layout = (LinearLayout)findViewById(R.id.my_list_layout);
my_list_layout.setOrientation(1);
my_list_layout.setId(50);
my_textview = new TextView[length];
for(int i=0; i<length ; i++)
{
my_textview[i]= new TextView(getApplicationContext());
my_textview[i].setText("sample text");
my_textview[i].setId(i);
if(i==0)
{
RelativeLayout.LayoutParams my_textviewparams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
my_textviewparams.addRule(RelativeLayout.ALIGN_PARENT_TOP,my_list_layout.getId());
my_list_layout.addView(my_textview[i],my_textviewparams);
}
else
{
RelativeLayout.LayoutParams my_textviewparams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
my_textviewparams.addRule(RelativeLayout.BELOW,my_textview[i-1].getId());
my_list_layout.addView(my_textview[i],my_textviewparams);
}
}
}
and my error log is
quick response is needed. anyone tell me, what is my wrong in coding, or what changes i have to do for my requirement?
You should remove this line:
my_list_layout.setId(50);
because once you set the id to 50, and again when you click the Button, the LinearLayout is null because you call findViewById(R.id. my_list_layout); its id has been changed to 50.
Cheers!
I got the answer.Here while i was doing first time the btn click, the child view will added to my parent view dynamically.
During the second click the i removed previously added child from my parent view and added the new child. So this will updates my content and displays clearly every time when I click the btn.
I got error in removing the views from my child, now I clear the error by assigning some variables for identifying btn click, whether user clicks it for first time or not. thank you all for your time here and for your answers.