Android App using Eclipse - Creating a button array - android

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

Related

Button pressed Image background set from Dreawable folder Using Array

public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1;
final ImageView image;
button1 = (Button) findViewById(R.id.button1);
image = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for (int j = 1; j < 6; j++) {
Drawable dreaw = getResources().getDrawable(getResources().getIdentifier("d002_p00"+j, "dreaw",getPackageName()));
image.setBackgroundResource("R.drawable." +dreaw);
}
}
});
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
i am new in android i want to change my image when i pressed my button image
in this line image.setBackgroundResource("R.drawable." +dreaw); it shows error how i can fix it please help me.
You can't do that :
Drawable dreaw = getResources().getDrawable(getResources().getIdentifier("d002_p00"+j, "dreaw",getPackageName()));
image.setBackgroundResource("R.drawable." +dreaw);
Try :
Drawable dreaw = getResources().getDrawable(getResources().getIdentifier("d002_p00"+j, "dreaw",getPackageName()));
image.setBackground(dreaw);
R.drawable.xxx is not a string it is a auto genarated intiger id for each resources.
image.setBackgroundResource("R.drawable." +dreaw);is wrong.
you can do onething
int res=getResources().getIdentifier("d002_p00"+j, "drawable",getPackageName()));
image.setBackgroundResource(res);
Try this
image.setBackgroundDrawable(dreaw);
This method is deprecated from api level 16 but fro backword compatibility you should use above method.
Just do:
image.setBackgroundDrawable(drew);
As your comment quotes "it worked bt it showa my first and last image."
You can only see the first and last image.Because the for loop is in a hurry burry,that means you can't see the changing of image,because the for loop is executed within ms(Milli or Micro Seconds).So you want to put this
Thread.sleep(<put_how_much_ms_you_want_to_make_the_for_loop_sleep);
to sleep the for loop time to time.If you put this
Thread.sleep(1000);//Make the thread or program blocked for 1 second.
For implementing in your For loop you can change your For loop like this.
for (int j = 1; j < 6; j++)
{
int res=getResources().getIdentifier("d002_p00"+j, "drawable",getPackageName()));
image.setBackgroundResource(res);
Thread.sleep(1000);//Make the for loop wait for 1 second.
}
By this you can see the transition of images.
May i know it helps you or not.

Creating a Dynamic List of Buttons from data contained in an array

I am working on making an application for taking basketball stats. I am currently working on allowing the person who is taking stats to setwho will be in/out at the start of the game. I also plan to reuse this code later on so that the person can sub people in and out during the game. Anyway, I am stuck on how to create the list of buttons based on the size of an array.
Currently, I have an array set up to pull the player's number, name, and whether they are in/out from the team's database. The buttons would display the player's number so that they could be subbed in and out. I would like to have it set up so that when a person clicks on one of the buttons, it would change who is considered "in" for the game and also update the values in the database. I'll put what little source code I have below. I have tried many approaches such as a gridview, looping through a button creation command and several other things but have been unable to get any of them to work the way I would like. Thanks in advance for your help.
Activity to set who is on the bench:
package com.newelementapp.basketballstatbook;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class HomeBench extends Activity {
String tname, t1, t2;
String [] players;
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home_bench);
Bundle rteam = getIntent().getExtras();
tname = rteam.getString("team");
StatbookDB get = new StatbookDB(this);
get.open();
players = get.getHomePlayers(tname);
get.close();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
DB:
public String[] getHomePlayers(String tname) {
// TODO Auto-generated method stub
String [] columns = {KEY_PNUMBER, KEY_PNAME, KEY_INOUT};
List<String> hplayers2 = new ArrayList<String>();
String teamname = tname.toLowerCase().replaceAll(" ", "_");
Cursor c = ourDatabase.query(teamname, columns, null, null, null, null, null);
int inum = c.getColumnIndex(KEY_PNUMBER);
int iname = c.getColumnIndex(KEY_PNAME);
int iout = c.getColumnIndex(KEY_INOUT);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
String s = c.getString(iname);
String i = c.getString(inum);
String t = c.getString(iout);
hplayers2.add(i);
hplayers2.add(s);
hplayers2.add(t);
}
String [] hplayers = new String[hplayers2.size()];
hplayers2.toArray(hplayers);
return hplayers;
}
Button Creation method
private void createButtons() {
// TODO Auto-generated method stub
for(int i = 0; i<players.length; i+=3){
Button btn = new Button(this);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btn.setId(i);
btn.setText(players[i]);
ll.addView(btn, params);
btn1=(Button)findViewById(i);
btn1.setOnClickListener(new OnClickListener() { ... }
Key is to have a ViewGroup such as a LinearLayout or RelativeLayout in your home_bench.xml file. This ViewGroup will become your container. Then when you loop around and dynamically create the Buttons, you keep adding those buttons to the container ViewGroup. Then you will be able to see the Buttons you are creating. Also, after you create the button, use setOnClickListener() on those buttons to specify a onClick routine where you define what to do when buttons are clicked. Use ids to differentiate between buttons. You would assign an id to a button when you are creating the button. HTH.

How to create Array of buttons in android using java

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

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

Problem with displaying Table in Android, Please help

HI,
I want to create a table in android, should contains a lot of rows. Each row has 4 columns, and if i click any view, i want to integrate onClick event for the view.
I have developed something similar to the requirement,But didn't got the click view, Here is my code :
LinearLayout lLayout1= null;
LinearLayout main_lLayout= null;
LinearLayout lLayout2= null;
TextView myText[] = new TextView[12];
LinearLayout myLayout[] = new LinearLayout[12];
#Override
public void onCreate(Bundle icici) {
super.onCreate(icici);
main_lLayout = new LinearLayout(this);
main_lLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
main_lLayout.setOrientation(LinearLayout.VERTICAL);
int k = 0;
for(int i=0;i<4;i++) {
myLayout[i] = new LinearLayout(this);
for(int j=0;j<4;j++) {
myText[j] = new TextView(this);
myText[j].setText("asdf"+i+j);
myText[j].setPadding(0, 0, 20, 10);
myText[j].setClickable(true);
myText[j].setId(k);
myText[j].setOnClickListener(this);
k++;
System.out.println(k);
myLayout[i].addView(myText[j]);
}
main_lLayout.addView(myLayout[i]);
}
setContentView(main_lLayout);
}
#Override
public void onClick(View v) {
System.out.println(myText[0].getText());
System.out.println(myText[10].getText());
}
You have some bad array management there... you're instantiating 16 TextViews but only assign them to the first 4 elements of myText. If you fix this I find the click handler is called as expected.

Categories

Resources