dynamic button onclick event inside for loop - android

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.

Related

How to remove dynamic button on android studio

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.

OnClickListener() for dynamic amount of buttons

Background
I am creating buttons dynamically in a for loop by following Pragnesh Ghota's solution of one onClick listener for every button in the format of dymmeh's individual initialization solution:
LinearLayout someLayout = (LinearLayout) findViewById(R.id.theRoom);
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setOnClickListener(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
}
In addition, I am making one onClick listener by implementing View.OnClickListener in the actvity class. My class is defined as such:
public class RecallActivity extends AppCompatActivity implements View.OnClickListener{
...
}
I have followed the other steps of Pragnesh Ghota's solution with success. However...
Problem
The fourth step of Pragnesh Ghota's solution mentions the use of a case statement to check if any of the buttons have been clicked. This works when the amount of buttons is known. However, since I am following the format laid out in dymmeh's solution, I do not know how many buttons I am checking until execution time.
Question
How do I do a control flow statement within an overrided onClickMethod for a dynamic amount of buttons?
Just create a new OnClickListener for each button when you're creating them.
LinearLayout someLayout = (LinearLayout) findViewById(R.id.theRoom);
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// add your click listener code here
}
})
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
}
you can set a id for button .just like this:
LinearLayout someLayout = (LinearLayout) findViewById(R.id.theRoom);
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setId(i);
neededButtons[i].setOnClickListener(this);
...
);
}
then find view by id in OnClickListener. for example:
public class RecallActivity extends AppCompatActivity implements View.OnClickListener{
#overide
public void onClick(View view){
if(view.getId == 0){
.....
}
}
}
The simplest solution is using setTag and getTag for your buttons. You can use an object with setTag and getTag. Whenever you're creating a button, set the tag for it:
for (int i = 0; i < neededButtons.length; i++){
neededButtons[i] = new Button(this);
neededButtons[i].setText(names[i]);
neededButtons[i].setTag(names[i]);
// or you can use the index as the tag with:
// neededButtons[i].setTag(i);
neededButtons[i].setOnClickListener(this);
}
Then you do something for each button by checking the tag:
#Override
public void onClick(View v) {
doSomething(v.getTag());
}
private void doSomething(Object tag) {
// in case your tag is the index, than you can convert it to
// integer and use switch case
int index = (int) tag;
switch(index) {
case 1:
...
break;
case 2:
...
break;
...
}
}

How to remove dynamically created views on button click

public void Add_text() {
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView product = new TextView(getActivity());
product.setText(" Product" + 5 + " ");
ll.addView(product);
EditText qty = new EditText(getActivity());
qty.setText(i + "");
qty.setId(i);
qty.setWidth(120);
ll.addView(qty);
Button btn = new Button(getActivity());
ll.addView(btn);
btn.setLayoutParams(params);
btn.setOnClickListener(o);
ly.addView(ll);
i++;
}
I wrote the above code to create the textfields and buttons dynamically; But now I need to remove 2 textfields and a button when the button is clicked. How do I do that?
Try following code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LinearLayout linearParent = (LinearLayout) v.getParent().getParent();
LinearLayout linearChild = (LinearLayout) v.getParent();
linearParent.removeView(linearChild);
}
});
Explanation
Here first take "GrandParent" of any view.
Then take its "Parent" view
With reference to "GrandParent" remove that "Parent" view.
this will remove all views which that "Parent" holds. As per your code, your "ll" will be "linearChild" here. And "ly" will be "linearParent" here. So whole "ll" will be removed from "ly" which you have added dynamically.
If you want to permanently remove the views you created.
OnClick(View view){
ly.removeAllViews()
}
If you do not want to permanently remove the views you created.
OnClick(View view){
ly.setVisibility(View.GONE); //This will hide the all views
qty.setVisibility(View.GONE);//This will hide the EditText qty
product .setVisibility(View.GONE);//This will hide the TextView product
}
So use appropriate code line which you want.
EDIT:
Use this code for your situation:
public void Add_text() {
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView product = new TextView(getActivity());
product.setText(" Product" + 5 + " ");
ll.addView(product);
EditText qty = new EditText(getActivity());
qty.setText(i + "");
qty.setId(i);
qty.setWidth(120);
ll.addView(qty);
Button btn = new Button(this);
ll.addView(btn);
btn.setLayoutParams(params);
ly.addView(ll);
i++;
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View button) {
qty.setVisibility(View.GONE);//This will hide the EditText qty
product .setVisibility(View.GONE);//This will hide the TextView product
}
});
}
i think you got to use this method on your LinearLayout :
public void removeView (View view)
first you call :
EditText et = (EditText)linearLayout.findViewById(yourEditText.getId());
then call the remove view method :
linearLayout.removeView (et) ;
and to remove all of the Views that are in the LinearLayout do the following :
public void removeAllViews ()
like the following :
linearLayout.removeAllViews()
and give me some feedback
Hope that Helps .
you can simply use qty.setVisibility(View.GONE) on the onClickListener() of the Button of your choice. like this.
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
qty.setVisibility(View.GONE); //for temporary purpose
//or u can also do this
layout.removeView(qty); //removes permanently
}
});
The benefit of using View.GONE is that you can get the View back if you want but layout.removeView(qty) will remove the view permanently and you have to re add the view again.
[EDIT] 1. changed to View.GONE instead of View.INVISIBLE because of reasons explained here
Hope I answered your question. :)
just use index for which you want to remove your view from linear layout
Linearlayout.removeViewAt();
if you want again that view then you can call addViewAt()in same way.
I hope it will help you.
Add this line
mLayout.removeViewAt(mLayout.getChildCount()-1);

Removing Layout on a button clilck

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);
}
....
}

Dynamically creating Buttons and setting onClickListener

I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.
#Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..
Update: code could be soemthing along these lines:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
as a method in the activity and then use it in the loop like this
button.setOnClickListener(getOnClickDoSomething(button));
I got one solution for this..
use this code in onCreate
linear = (LinearLayout) findViewById(R.id.linear);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
btn[i] = new Button(getApplicationContext());
btn[i].setText(num_array_name[i].toString());
btn[i].setTextColor(Color.parseColor("#000000"));
btn[i].setTextSize(20);
btn[i].setHeight(100);
btn[i].setLayoutParams(param);
btn[i].setPadding(15, 5, 15, 5);
linear.addView(btn[i]);
btn[i].setOnClickListener(handleOnClick(btn[i]));
}
after onCreate create one method of return type View.OnClickListener like this..
View.OnClickListener handleOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
}
};
}
Button.OnClickListener btnclick = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button)v;
Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();
}
};
call this listener by btn.setOnClickListener(btnclick);
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.
Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().
instead use setTag() function to distinct easily.
for(int i=0;i<4;i++) {
Button btn = new Button(this);
btn.setTag(i);
btn.setOnClickListener(new View.OnclickListener() {
#Override
public void onClick(View v) {
int i=v.getTag();
switch(i) {
case 1: btn.setText(i);
break;
case 2: btn.setText(i);
break;
case 3: btn.setText(i);
break;
case 4: btn.setText(i);
break;
default: btn.setText("Others");
}
}
}
"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.
I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.
Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout
This answer may you help:
https://stackoverflow.com/a/5291891/2804001
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}

Categories

Resources