xml button link to for loop - android

I am trying to get a button in an XML doc to add new textfields and checkboxes, I have the for loop that does what I want, but I don't understand how I am suposed to link my button to access a specific part of a java file.
How do i implement?
edit.
Here is my forloop that I want my button to access when pressed (generate textfields)
And Generally I want to know if it is possible to link a xml button to a loop in java and
If not, what can I do in order to get my button to generate textfields?
for(int i = 0; i <5; i++){
CheckBox cb = new CheckBox(this);
cb.setText("I'm an egg!");
EditText et1 = new EditText(this);
et1.setText("Listitemz!");
ll.addView(et1);
ll.addView(cb);

in XML:
<Button android:id="#+id/button" ..... />
in java file:
Button button = (Button)findViewById(R.id.button)
Now you can use button object from Button class.
Is it what you mean by linking?

If I'm understanding you correctly you want the button to access and run the for loop?
Step 1:
First create the button in xml.
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Step 2:
Create the link in your activity.
Button button = (Button) findViewById(R.id.button);
Step 3:
Assign an onClickListener to your button and put the for-loop inside.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i = 0; i <5; i++){
CheckBox cb = new CheckBox(this);
cb.setText("I'm an egg!");
EditText et1 = new EditText(this);
et1.setText("Listitemz!");
ll.addView(et1);
ll.addView(cb);
}
}
});
Now whenever the button is pressed your for-loop will run, if you have any questions please let me know.
NOTE: You may need the following imports -
import android.view.View;
import android.widget.Button;

Related

Using Mutliple Dynamically Created Buttons in Android

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 need to get the id of the dynamically generating button

From this code it creates dynamic buttons accodring to a given value from another layout. I need to get the id of that and add another button (if dynamic button clicks then I need to add another button dynamically).
for (int i = 0; i < value1; i++) {
LinearLayout.LayoutParams paramsIButton = new LinearLayout.LayoutParams
((int) ViewGroup.LayoutParams.WRAP_CONTENT, (int) ViewGroup.LayoutParams.WRAP_CONTENT);
ibutton = new ImageButton(HomePage.this);
ibutton.setImageResource(R.drawable.add);
ibutton.setLayoutParams(paramsIButton);
paramsIButton.topMargin = -70;
paramsIButton.leftMargin = 370;
paramsIButton.bottomMargin = 30;
ibutton.setId(i);
ibutton.getPaddingBottom();
ibutton.setBackgroundColor(Color.WHITE);
ibutton.setAdjustViewBounds(true);
rR.addView(ibutton);
}
If I understood correctly from the additional information you provided on your comment, you need to know when a user clicked on a button. You could set an OnClickListener to your button.
// Somewhere in your activity . . .
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// The button is clicked! Do whatever you want.
}
});
}
// ...
// Rest of the code
// ...
Of course, you should replace R.id.button1 with your button's id.
Seems to me like you need to add an onClickListener for the dynamically added button.
Make your class implement OnClickListener and then add a listener for the dynamic button:
ibutton.setOnClickListener(this);
and add an onClick Listener within your class:
#Override
public void onClick(View v)
{
// do something with this ID
v.getId()
}
I don't know how you keep track of the bulbs and fans, I'd hope you don't do it via the UI elements alone. I'd probably do it a bit differently, creating a data structure to track the bulbs and fans and attach the specific bulb or fan object to the UI element as a tag.

How to identify the button clicked from a dynamically generated table

I am populating a table dynamically from a string array.Each row of the table also has a plus and minus button to increment/decrement the value of one column. These buttons are also dynamically created like in the code below. Here how can I detect the exact button upon clicking. i.e; if I click on the '+' button of the 2nd row, how can I get the id of the button clicked for further processing.
plusButton= new Button(this);
minusButton= new Button(this);
createView(tr, tv1, names[i]);
createView(tr, tv2, (String)(names[i+1]));
minusButton.setId(i);
minusButton.setText("-");
minusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
plusButton.setId(i);
plusButton.setText("+");
plusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));`
You can set an onClickListener listener for each button. Use the id of the button from view.getId() method on your onClick() method to identify the button click.
You can add separate listeners for each button like here (assuming that the id you are setting for each button corresponds to a row)
minusButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
// Do some operation for minus after getting v.getId() to get the current row
}
}
);
Edit:
I am assuming your code is like this. Correct me if there is a deviation.
Button minusButton = null;
for(int i = 0; i < rowCount; i++)
{
minusButton = new Button(this);
minusButton.setId(i);
// set other stuff and add to layout
minusButton.setOnClickListener(this);
}
Let your class implement the interface View.OnClickListener and implement the onClick() method.
public void onClick(View v){
// the text could tell you if its a plus button or minus button
// Button btn = (Button) v;
// if(btn){ btn.getText();}
// getId() should tell you the row number
// v.getId()
}
You could do with tags: minusButton.setTag("-") and plusButton.setTag("+").
In your clickListener just get it from your button with view.getTag().
Then switch between your actions comparing the string tag.
Edit:
ID's "should" be unique. The setTag() method may help you if setId() doesn't work for you.

changing string value displayed in scrollView

first I would like to say thank you to every one out here as i am a nOOb and have learned a lot just by reading questions and answers that you post. I am trying to pass a great deal of text to the end users and while being able to do this with new classes and .xml files this is becoming cumbersome. i thought of stream lining the app by just having a single xml layout for a particular set of text strings and just change the #string/????? via button onclick and setText but have learned that I can not change the initial value of #string in an xml file. question is that TRUE? and is there a more efficient way to do this ie (setting android:text to a var and setting var in java to a particular string) or do i need a new xml layout for each string? (that's a lots of waste if you ask me) and a little insight, there are at this time approx 250 different strings with min 5 paragraphs and growing.
here is my code thus far.
snippet of first java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Monlt extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.monolt);
final MediaPlayer buttonsound = MediaPlayer.create(Monlt.this, (R.raw.buttonclick));
Button button1 = (Button) findViewById(id.button1);
Button button2 = (Button) findViewById(id.button2);
Button button3 = (Button) findViewById(id.button3);
Button button4 = (Button) findViewById(id.button4);
Button button5 = (Button) findViewById(id.button5);
Button button6 = (Button) findViewById(id.button6);
Button button7 = (Button) findViewById(id.button7);
Button button8 = (Button) findViewById(id.button8);
Button button9 = (Button) findViewById(id.button9);
Button button11 = (Button) findViewById(id.button11);
Button button12 = (Button) findViewById(id.button12);
Button button13 = (Button) findViewById(id.button13);
Button button14 = (Button) findViewById(id.button14);
Button button15 = (Button) findViewById(id.button15);
Button button16 = (Button) findViewById(id.button16);
Button button17 = (Button) findViewById(id.button17);
Button button18 = (Button) findViewById(id.button18);
Button button19 = (Button) findViewById(id.button19);
Button button21 = (Button) findViewById(id.button21);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
buttonsound.start();
final TextView mview = (TextView) findViewById(R.id.solayout2);
mview.setText("mono1"); //this was my first string to pass
startActivity(new Intent("com.nvar.Sorders.Mono.ASO1"));
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
buttonsound.start();
startActivity(new Intent("com.nvar.Sorders.ASO1"));
final TextView mview = (TextView) findViewById(R.id.solayout2);
mview.setText("#string/mono2");/this is the second string to pass
}
});
`
now this code works when i remove the 2 text view lines in the onclick
so then it call another class Aso1 that I would like to keep in place for later use.
Aso1 java code
`
package com.nvar.Sorders.Mono;
import com.nvar.Sorders.R;
import android.app.Activity;
import android.os.Bundle;
public class Aso1 extends Activity {
// Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.solayout2);
}
}
`
and then the first xml
`
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/solayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="mview"/>
<!-- android:text="#string/monoaso1"/>
-->
<!-- this is were i was playing with the strings />
-->
</LinearLayout>
</ScrollView>
`
any help in this matter would be greatly appreciated, and remember "noob" to java / android! so if there is a sample of what i could or should be looking at, don't hesitate to smack me in the head and point me in the right direction. i don't mind reading :)
thanks again.
When displaying the Strings, What you could use is a TextView and have multiple lines and then just update the text value of it in code. It doesn't even need default text
<ScrollView
...some params...>
<TextView
android:id="#+id/my_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="10"/>
</ScrollView>
This will give you a TextView 10 lines long. Then in code you can do something like this to update the value:
String longText = getVeryLongText();
((TextView)findViewById(R.id.my_text)).setText(longText);
Then you'll have something that looks like a scrollable paragraph of text
*#string/string_name* in xml are not designed to change the value. They are there to help you with localization. Currently that xml is located here http://developer.android.com/guide/topics/resources/localization.html
res/values/string.xml
you can have another string xml with different language like in the following location, for example france
res/values-fr/strings.xml
you can read more about that over here.
Now, let's move on to how to reference that string_name from java
Resources res = Monlt.this.getResources();
mview.setText(res.getString(R.string.string_name));
//do something
mview.setText(res.getString(R.string.mono2));

Android Multiple Buttons with different Actions

I create buttons dynamically based on the size of an array list that i get from another object. For each entry of the arraylist i need to create three buttons each one with different action.
Like this i need to create 3 times the sizes of arraylist number of buttons. If i had only one set of buttons I can write onClick()-method which takes the id of the button but here i have 3 buttons for each entry and need to write 3 different actions for those three buttons.
How could this be done?
Similar thing I have done when i needed a textview for each of my array item.it was like-
String[] arrayName={"abc","def","ghi"};
for(int i=0;i<arrayName.length;i++)
{
TextView tv=new TextView(context);
tv.setPadding(20, 5, 40, 5);
tv.setText(arrayName[i]);
tv.setTextSize(1, 12);
tv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setTextColor(Color.parseColor("#2554C7"));
tv.setClickable(true);
tv.setId(i);
layout.addView(tv);
}
In same way,you can add button in similar way. and in click event of each of them,you can code for their actions separately.(I have not tried this).So in each iteration,you will have 3 buttons for each of the array item.
Edit - 1:
You can differentiate ids like:
mButton1.setId(Integer.parseInt(i+"1"));
mButton2.setId(Integer.parseInt(i+"2"));
mButton3.setId(Integer.parseInt(i+"3"));
Then you can set click listener on each of the button like mButton1.setOnClickListener... and so on.
Declare a list of buttons:
private List<Button> buttons = new ArrayList<Button>();
Then add each button to this list:
buttons.add(0, (Button) findViewById(id in ur layout));
Inside a for loop give click listener:
Button element = buttons.get(i);
element.setOnClickListener(dc);
where dc is ur object name for your inner class that implements OnClickListener.
To access each button you can give:
Button myBtn;
#Override
public void onClick(View v) {
myBtn = (Button) v;
// do operations related to the button
}
Create the Common Listener class for your button action event and set the used into the setOnClickListener() method
Now set the unique id for the buttons.
Now suppose your class look like this :
class MyAction implements onClickListener{
public void onClick(View view){
// get the id from this view and set into the if...else or in switch
int id = view.getId();
switch(id){
case 1:
case 2:
/// and so on...
}
//// do operation here ...
}
}
set this listener in button like this way.
Button b1 = new Button(context);
b1.setId(1);
b1.setOnClickListenr(new MyAction());
Button b2 = new Button(context);
b2.setId(2);
b2.setOnClickListener(new MyAction());

Categories

Resources