I am working on android.And i was creating an application in which i dynamically created a group of buttons on a button click.But what happens is buttons are created every time i click the button.i want this to happen once.Can i clear the space just at the beginning of OnClickListener()? i dunno how to do it.Below is my code.
button_generate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//*-----------clearing the variables--------*
final TableLayout rel=(TableLayout)findViewById(R.id.tab1);
int k=0,i=0,j=0;
count=3;
System.out.println("count is"+count);
while(j<count)
{
TableRow tr = new TableRow(EspeakerActivity.this);
//for(int c=1; c<=3; c++) {
Button b1 = new Button (EspeakerActivity.this);
Button b2= new Button (EspeakerActivity.this);
Button b3 = new Button (EspeakerActivity.this);
b1.setText("1");
b2.setText("2");
b3.setText("3");
b1.setTextSize(10.0f);
200));
tr.addView(b1, 100,50);
tr.addView(b2, 100,50);
tr.addView(b3, 100,50);
rel.addView(tr);
}
j++;
}
}
}
);//*--------closing the button click------*
Give the buttons ID's and then use findViewByID() to see if the buttons already exist before adding them.
TableRow tr = new TableRow(EspeakerActivity.this);
tr.setId(/*some id*/)
//for(int c=1; c<=3; c++) {
Button b1 = new Button (EspeakerActivity.this);
Button b2= new Button (EspeakerActivity.this);
Button b3 = new Button (EspeakerActivity.this);
b1.setText("1");
b2.setText("2");
b3.setText("3");
b1.setTextSize(10.0f);
200));
tr.addView(b1, 100,50);
tr.addView(b2, 100,50);
tr.addView(b3, 100,50);
//check rel already has that tr.. if it has don't add anythin.. better if you do it before even creating the TAbleRow
rel.addView(tr);
Hiding linear layout on runtime in Android
you can refer the link and i am sure you will get your ans.if not solve through this link
then tell me.
You can clear your TableLayout on each button click as follows
....
onClick(View v) {
final TableLayout rel=(TableLayout)findViewById(R.id.tab1);
for(int x=0; x<rel.getChildCount(); x++)
{
View v = rel.getChildAt(x);
rel.removeView(v);
}
....
}
Related
I add some button with image and animation in my code, the following is my code.
//add diamond to relativelayout
private void addDiamond(){
Drawable img = getContext().getResources().getDrawable( R.drawable.diamond );
img.setBounds( 0, 0, diamondWidth, diamondHeight );
for (int i = 0; i < diamondRow; i++) {
LinearLayout row = new LinearLayout(getContext());
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
diamondHeight+120));
for (int j = 0; j < diamondCol; j++) {
Button btnTag = new Button(getContext());
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
btnTag.setCompoundDrawables(null, img, null, null);
btnTag.setText("0.0158" + (j + 1 + (i * diamondCol)));
btnTag.setTextColor(Color.WHITE);
btnTag.setTextSize(8);
btnTag.setBackgroundColor(Color.TRANSPARENT);
btnTag.setId(j + 1 + (i * diamondCol));
btnTag.setOnClickListener(btnClick);
row.addView(btnTag);
}
diamond_lyt.addView(row);
}
animate(diamond_lyt);
}
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button = diamond_lyt.findViewById(v.getId());
Toast.makeText(getContext(), String.valueOf(button.getId()), Toast.LENGTH_SHORT).show();
ViewGroup layout = (ViewGroup) button.getParent();
layout.removeView(button);
}
};
Now I wnat to click these button to remove it individually.
But it is very strange in the result.
When I click two column first button, it remove two column last button.
Please how can I solve this problem?
There's nothing wrong with the click, it removes the views correctly as you click on them. I guess whenever you remove a button, the remaining buttons in the row shift towards left creates an illusion which makes you think it removes the wrong button.
If you intend to have a grid-like layout, that the buttons should always stay in their positions on screen, you could try setting the visibility to View.INVISIBLE instead of removing the view, or replace it with an empty view of the same size.
This one too simple.....
Instead of this ...
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button = diamond_lyt.findViewById(v.getId());
Toast.makeText(getContext(), String.valueOf(button.getId()), Toast.LENGTH_SHORT).show();
ViewGroup layout = (ViewGroup) button.getParent();
layout.removeView(button);
}
};
Try this one ....
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button =((Button)v);
((ViewGroup) button.getParent()).removeView(button);
}
};
When Your button click onClick(View v) v give you instance of button. TypeCaste from View to Button and remove it.
My program asks a user to enter their name and click on a button called btn. Once btn is clicked, their name is dynamically added to a TableRow along with another dynamically created Button. It's these Buttons that I'm having an issue with. I need to somehow access them later on in the program. I created a number of IDs in my res/value folder to keep track of each one(changebtn1, changebtn2, etc..). They're all stored in an array called buttonIDs.
Let's say that the user enters the first name, a new row is created with a dynamically created button:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tableRow = new TableRow(getApplicationContext());
Button changeButton = new Button(getApplicationContext());
changeButton.setText("Change");
changeButton.setId(buttonIDs[i]);//From res/values
tableRow.addView(changeButton);
tableLayout.addView(tableRow);
i++;
});
Now let's say they enter a second name, another Button is created and so on and so forth. How can I now set an OnClickListener to my first Button that I created, which has the ID of R.id.changeBtn1? In other words, I have all of these dynamically created buttons and am not sure how to add OnClickLsteners() to earlier ones or access them in anyway. Thank you
Or you attach the OnClickListener directly in the creation of the button or you can store the references to the buttons like this:
ArrayList<Button> buttons = new ArrayList<Button>();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tableRow = new TableRow(getContext());
Button changeButton = new Button(getContext());
buttons.add(changeButton);
changeButton.setText("Change");
changeButton.setId(buttonIDs[i]);//From res/values
tableRow.addView(changeButton);
tableLayout.addView(tableRow);
i++;
});
for(Button button: buttons){
button.setOnClickListener(new OnClickListener()
...etc...
);
}
You won't waste a lot of memory since the buttons.add() line won't copy the button in the array but just the reference to the button. If you need a in id access to the buttons, use an HashMap, like this:
HashMap<String, Button> map = new HashMap<String, Button>();
map.put("id", new Button(getContext()));
And then access it like this:
Button button = map.get("id");
How about something like this
for(int i=0;i<buttonIDs.size();i++) {
Button currentButton = (Button) findViewById(buttonIDs[i]);
currentButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Stuff
}
});
}
I did not check the code
#filnik The first part of your answer also gave me an idea. I created an OnClickListener method outside of my OnCreate() method.
View.OnClickListener changeTeamName(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
//Do Stuff
}
};
}
I then set an OnClickListener to EACH dynamically created Button and use the method that I created.
changeButton.setText("Change");
changeButton.setTag("ButtonOne");
changeButton.setOnClickListener(changeTeamName(changeButton));
The fact that each Button now has an OnClickListener associated with it, they can now perform whatever function I add to my method.
I am adding buttons to a linear layout at runtime and need to add the functionality of removing them if the user desires. At the moment I have a button which opens a popup with a list consisting of the text for each button added. If possible, would I be able to have each onItemClick delete the corresponding button? If not, what would be the best way to remove a specific button?
Here is the code for adding buttons:
private void addButton(){
LinearLayout lL = (LinearLayout) findViewById(R.id.requirement_linear);
lL.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
p.setMargins(0,2,0,0);
Button b = new Button(this);
b.setBackgroundResource(R.drawable.blue_button);
b.setOnClickListener(openRequirement);
b.setTextColor(Color.parseColor("#FFFFFF"));
String button_text = (index + 2) + ". " + requirement_list.get(index + 1).getName();
b.setText(button_text);
requirements_text.add(button_text);// requirements_text is an arraylist<string> which stores the text so I can display them in my popup to delete them.
index ++;
lL.addView(b,p);
}
You can use removeView() on your LinearLayout and pass your button. You can identify the button on the OnClick(View view) callback, the view there is the button.
as requested, here is an example.
final LinearLayout lL = (LinearLayout) findViewById(R.id.requirement_linear);
Button b = new Button(this);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View button) {
lL.removeView(button);
}
});
lL.addView(b);
Alternatively you can use removeViewAt() to remove a child view by index. You can use the index of your 'list of text of buttons'. Assuming its a listview, you can try this.
lview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
lL.removeViewAt(position);
}
});
here is how i hide and show the buttons
Button b = new Button(this);
b.setVisibility(View.GONE); // this will hide the button and it will now show
b.setVisibility(View.VISIBLE); // this will show the button if it was hidden before
Enjoy!
Here i am creating 20 Button dynamically using for loop
exmple
for(int i =1 ;i <= 20 ;i++){
Button b = new Button(this);
b.setText(String.valueOf(i));
b.setId(String.valueOf(i));
b.setBackgroudColor(Color.Red);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
b.setBackgroundColor(Color.GREEN);
}
);
}
If i select 1st Button color will be changing to green remaining all are red. similarly if i select 2nd Button 1st and 2nd button color will be green and remaining all are red. this is the way it working fine .but my requirement is if i select the any button 2nd time all buttons and previous button which i pressed color should be red. to do that i am not getting the previous button id's. can any help for this problem
Hold a reference of the previously pressed button:
final Button prevButton;
for(int i =1 ;i <= 20 ;i++){
Button b = new Button(this);
b.setText(String.valueOf(i));
b.setId(String.valueOf(i));
b.setBackgroudColor(Color.Red);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(prevButton != null)
prevButton.setBackgroundColor(Color.RED);
b.setBackgroundColor(Color.GREEN);
prevButton = (Button)v;
}
);
}
Are you sure using 20 Buttons is a good choice?
Can you use GridView?
You can change the backGroundColor as well: forums.pragprog.com/forums/152/topics/10301
i'm using this code to create dynamic buttons within for loop..
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearLayout2);
for (int i=0 ; i<10; i++){
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.HORIZONTAL);
TextView textview = new TextView(this);
textview.setText("Text view" + i);
textview.setId(i);
l.addView(textview);
Button button = new Button(this);
button.setText("View");
button.setId(i);
button.setWidth(90);
button.setHeight(60);
l.addView(button);
linearLayout.addView(l);//if you want you can layout params linearlayout
}
now i want to add onclick event to each button based on the iterating i value.. can any one suggest me how to implement this... thanks in advance..
create an arraay of buttons...
Button[] buttons=new Button[10];
and instead of this line
Button button = new Button(this);
in your for loop..use
button[i] = new Button(this);
and in the same loop set your onclicklistener like this..and based on the question you were asking add onclick event to each button based on the iterating i value i think you have same onclicklistener for all buttons..
button[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//your onclicklistener code
}
});
Create a List of Button's then add each Button to that list after its created...
List<Button> list = new ArrayList<Button>();
for (int i=0 ; i<10; i++){
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.HORIZONTAL);
TextView textview = new TextView(this);
textview.setText("Text view" + i);
textview.setId(i);
l.addView(textview);
Button button = new Button(this);
button.setText("View");
button.setId(i);
button.setWidth(90);
button.setHeight(60);
l.addView(button);
linearLayout.addView(l);//if you want you can layout params linearlayout
list.add(button);
}
Then use advanced for loop to iterate through the list and add click listener for each Button..
for(Button btn : list){
btn.setOnClickListener(this);
}
Outside your loop create a new View.OnClickListener:
OnClickListener ocl = new OnClickListener(){
#Override
public void onClick(View v){
switch(v.getId()){
case 1:
// click action
break;
case 2:
// click action
break;
}
// ...etc
}
}
Based on the ID of your button, in this case the iteration of i, you can perform various actions. This can be anything, however, like an if...else block on the text of the button or a tag you set.
Then inside your loop, before you addView(l), assign it:
button.setOnClickListener(ocl);
add button.setOnClickListener(this); in the forloop
and add these code below oncreate():::
#Override
public void onClick(View v){
switch(v.getId()){
case 0:
// click action for first btn
break;
case 1:
// click action for 2nd btn
break;
soon upto
case 9:
// click action for 9th btn
break;
}
}
also ypur activity must implement onClickListerner.