I want to create an array of buttons in my app. So how that can be done. Secondly, is it possible to interact with each button in an array of buttons? If so, how? Please suggest to me.
Regards
Anshuman
Inside you Activity do something like this:
LinearLayout linear = new LinearLayout(this);
linear.setOrientation(LinearLayout.VERTICAL);
ArrayList<Button> ab = new ArrayList<Button>();
for (Button b : ab) {
linear.addView(b);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
};
setContentView(linear);
Related
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'm writing an app that needs 86 small, square buttons in one layout - 6 columns preferably. I want to reference the buttons to show a different image depending on the button pressed. I coded it the hard way using a relative layout> scrollview (in XML), then 86 individual buttons, but it seemed like an amateur solution.
Can someone show me how to code an array of identical buttons with different id's directly within the Java class the right way? (By the way, i have tried hard to find this answer with Google, but when i search variations of this question i always get tutorials about JButtons, which i believe can't be used in an android app).
Thanks in advance.
This may help
public class Test extends Activity{
List<Button> buttonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
Button doneButton=(Button)findViewById(R.id.your_final_button);
ScrollView view=(ScrollView)findViewById(R.id.your_scroll_view);
view.addView(tableLayout(20));//20 rows
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(Button b : buttonList){
b.getText();//whatever you wanna do
}
}
});
}
private TableLayout tableLayout(int count) {
TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
tableLayout.setBackgroundColor(Color.WHITE);
int noOfRows = count ;
for (int i = 0; i < (noOfRows+1); i++) {
int rowId = 3 * i;
tableLayout.addView(createOneFullRow(rowId));
}
return tableLayout;
}
private TableRow createOneFullRow(int rowId) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
//6 columns
tableRow.addView(createButton("text1"));
tableRow.addView(createButton("text2"));
tableRow.addView(createButton("text3"));
tableRow.addView(createButton("text4"));
tableRow.addView(createButton("text5"));
tableRow.addView(createButton("text6"));
return tableRow;
}
private View createButton(String string) {
// TODO Auto-generated method stub
Button button = new Button(this);
button.setText(string);
buttonList.add(button);
return button;
}
}
I have an activity and a class that implements a popup window. Using this tutorial I implemented the popup. I call the methods init() and popupInit() from the activity and everything else is in the class. My problem is that the popup does not show.
Here is the popup class:
public class PopupAudio implements OnClickListener {
LinearLayout layoutOfPopup;
PopupWindow popupMessage;
Button popRecord, popStopRecord, popPlay, popStopPlaying;
TextView popupText;
public void popupInit() {
popRecord.setOnClickListener(this);
popStopRecord.setOnClickListener(this);
popPlay.setOnClickListener(this);
popStopPlaying.setOnClickListener(this);
popupMessage = new PopupWindow(layoutOfPopup, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popupMessage.setContentView(layoutOfPopup);
}
public void init(Context context) {
popRecord = new Button(context);
popRecord.setId(112);
popStopRecord = new Button(context);
popPlay = new Button(context);
popStopPlaying = new Button(context);
layoutOfPopup = new LinearLayout(context);
popRecord.setText("REC");
layoutOfPopup.setOrientation(1);
layoutOfPopup.addView(popRecord);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case 112:
break;
}
}
}
It is a school project so it is very important. Please help me, I'll be grateful :)
You need to call a method to actually show the popup on some event action or whenever you need it. Here are the different methods from the docs
Here is one example of using showAtLocation().
showAsDropDown(View anchor) may be the simplest depending on your needs. Just pass it the view you want it to attach to. Though, the other two give you more flexibility on where it shows.
I need create a button in java class and replace it in xml in a specific position like i want to put them in horizontal scrollView that i created in xml please any help + i need a function the allow me to generate button automatically according to my array size thanks. .
Try This code
LinearLayout layout=(LinearLayout)findViewById(R.id.linearLayout);
LayoutParams layoutParam_text=new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); layoutParam_text.gravity=Gravity.LEFT;
Button btnTest[]=new Button[array.size];
for(int i=0;i<array.size();i++)
{
btnTest[i] =new Button(this);
btnTest[i].setLayoutParams(layoutParam_text);
btnTest[i].setTag(""+i);
btnTest[i].setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
layout.addView(btnTest[i]);
}
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");
}
}