I've developed one Android application which uses a HorizontalScrollView, and the HorizontalScrollView has one child as a LinearLayout.
Now I want to add buttons on LinearLayout at Runtime means dynamically.
I added the button successfully, But the problem is that my button click event does not work in Android.
ArrayList listClassItems = objCompany.getListClassItems();
Button[] btnCategory = new Button[listClassItems.size()];
for(int i=0;i<listClassItems.size();i++)
{
System.out.println("OTHER_CLASS LENGTH : " + listClassItems.size());
System.out.println("CLASS ID : " + listClassItems.get(i).getClassId());
System.out.println("CLASS NAME : " + listClassItems.get(i).getClassName());
btnCategory[i] = new Button(myContext);
btnCategory[i].setId(i);
btnCategory[i].setTag(listClassItems.get(i).getClassId());
btnCategory[i].setText(listClassItems.get(i).getClassName());
btnCategory[i].setClickable(true);
btnCategory[i].setPadding(10,10,10,10);
LayoutParams layParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
if(i!=0 || i!=listClassItems.size()-1)
{
layParams.leftMargin = 10;
layParams.rightMargin = 10;
}
tabRowBottom.addView(btnCategory,layParams);
btnCategory[i].setOnClickListener(null);
tabRowBottom.addView(btnCategory[i]);
btnCategory[i].setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(myContext, "=== Button CLICKED ===",Toast.LENGTH_SHORT).show();
btnCategory.setBackgroundColor(Color.BLACK);
}
});
}
Instead of an array, create a list of buttons, you can create buttons and set their id, tags and onclicklistenners like this and add them to the button list:
buttonList = new ArrayList<Button>();
for (int i=0;i<5;i++){
Button button = new Button(getApplicationContext());
button.setOnClickListener(customListenner);
button.setId(i);
button.setTag(i);
myLayout.addView(button);
buttonList.add(button);
}
and when you need to use the button again, just call with their id or tags from the list.
If you need different listenners, you can control them by using the unique tag check in if function and declare another action.
This is the method that I always use when I create dynamic views programmatically.
Related
I am new to android. I want to display the 5 numbers in the Button. And also needs to display the arithmetic buttons also like below
14 12 13 12 11 ( These number to be displayed in the button )
+ - * / ( These arithmetic button also displayed in button)
I want to display like above dynamically. And i am using this code, but it displaying like below.( not displaying +, - *, / )
/ 14
/ 12
/ 13
/ 12
/ 11
I want to display like mentioned initially and also i want listen the button clicked
Its displaying Normal buttons, how i can display as like Graphic buttons. ( so that it will give more attraction)
Please find the code below.
setContentView(R.layout.dynamically_create_view_element);
final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
// create the layout params that will be used to define how your
// button will be displayed
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int j=0;j<5;j++)
{
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
final Button btn1 = new Button(this);
// Give button an ID
btn1.setId(1);
btn1.setText("+");
btn1.setId(2);
btn1.setText("-");
btn1.setId(3);
btn1.setText("*");
btn1.setId(4);
btn1.setText("/");
// Create Button
final Button btn = new Button(this);
// Give button an ID
btn.setId(j+1);
int random1 = (int )(Math.random() * 20 + 1);
btn.setText(""+numbers[j]+"");
// set the layoutParams on the button
btn.setLayoutParams(params);
final int index = j;
// Set click listener for button
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i("TAG", "index :" + index);
Toast.makeText(getApplicationContext(),
"Clicked Button Index :" + index,
Toast.LENGTH_LONG).show();
}
});
//Create four
//Add button to LinearLayout
ll.addView(btn1);
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
}
Ok there are multiple issues with your code:
First, you're getting the below result
/ 14
/ 12
/ 13
/ 12
/ 11
because inside your for-loop you're setting the text of btn1 to / after setting the text of the Button to + then to - and then to *.
Also because you're creating a LinearLayout for each Button you're getting the numbers below each other.
I've taken the liberty to re-write the code a bit into something a bit more generic:
public class MainActivity extends Activity {
private LinearLayout lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LinearLayout) findViewById(R.id.lm);
// Create a LinearLayout for each row inside the outer LinearLayout.
LinearLayout firstRow = new LinearLayout(this);
firstRow.setOrientation(LinearLayout.HORIZONTAL);
// Create a String array of items you want to add to the inner LinearLayout.
String[] itemsToAddToFirstRow = { "14", "12", "13", "12", "11" };
createButtonsDynamically(firstRow, itemsToAddToFirstRow);
String[] itemsToAddToSecondRow = { "+", "-", "*", "/" };
LinearLayout secondRow = new LinearLayout(this);
secondRow.setOrientation(LinearLayout.HORIZONTAL);
createButtonsDynamically(secondRow, itemsToAddToSecondRow);
}
private void createButtonsDynamically(LinearLayout layoutToAddButtonsTo, String[] itemsToAdd) {
for (int i = 0; i < itemsToAdd.length; i++) {
final Button buttonToAdd = new Button(this);
buttonToAdd.setText(itemsToAdd[i]);
buttonToAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "I was clicked: " + buttonToAdd.getText(), Toast.LENGTH_SHORT).show();
}
});
layoutToAddButtonsTo.addView(buttonToAdd);
}
// In the end add all buttons inside the inner LinearLayout to the outer LinearLayout.
lm.addView(layoutToAddButtonsTo);
}
}
Add your own code to add the ids to the Buttons.
The end-result will look like this:
As far as your #2. goes:
You could a background image to your Buttons by calling setBackground(Drawable drawable) for the buttons or you completely re-style the standard Button.
Have a go at this guide from the official guidelines.
Hope this helps :-)
I want to ask how to make a list of text that we can tap in each of the text and then get the selected text to editText.
I just added the screenshot
http://i.stack.imgur.com/ddZSg.png
I have been searching it since yesterday, but I can not find exact solution. I also tried with listview, but I don't know how it's possible with horizontal, and flow list item.
I am also new in android. But I can think of the logic what you want. You can try this out if you want.
First of all, you can make your list of texts EditText by list of buttons Buttons
You can dynamically add as many Buttons with their respective text as you want to show.
set their corresponding onClickListener
In their onClickListener , create an object of the EditText you are using to add texts.
Store the value of EditText into a String Variable first.
Add the text of the clicked Button to the variable.
and now again set the text in EditText with the variable you created to store the values.
Your task will be done.
Try referring this code.
and change the code accordingly as your needs.
// Adding EditText and a button in a new linear layout and then adding
// the new linearLayout to the main layout
String[] valuesToBeAdded={"A","B","C","D"};
String selectedValues=null;
LinearLayout mainLayout=(LinearLayout) findViewById(R.id.mainLayout);
LinearLayout localLayout = new LinearLayout(context);
localLayout.setOrientation(LinearLayout.VERTICAL);
localLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
EditText editText=new EditText(context);
editText.setText(selectedValues);
editText.setId(5000);
localLayout.addView(editText);
for(int i=0;i<valuesToBeAdded.length();i++){
Button button = new Button(context);
button.setText(R.string.scanDocument);
button.setId(i);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText ed=(EditText) findViewById(5000);
selectedValues=ed.getText();
selectedValues=selectedValues +" " + this.getText();
ed.setText(selectedValues);
}
});
localLayout.addView(button);
}
mainLayout.addView(localLayout);
Thank You
Could you not make as many buttons as you need and then in the button_Click method for all buttons add:
Buttonwithtext_Click(object sender, EventArgs e)
{
editTextBox.Text = editTextBox.Text + Buttonwithtext.text + ", ":
}
i'm trying to create buttons programmatically on my android application depending on how many items I have on my sqlite database. The buttons are there, but my problem is to set onClick on every button because I want to show different content when user's click the buttons. I'm using this code for now :
for(cursorCol.move(0); cursorCol.moveToNext(); cursorCol.isAfterLast()){
Id = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("id")));
Log.i("Id","Id : "+Id);
titleButton = cursorCol.getString(cursorCol.getColumnIndex("title"));
Log.i("titleButton","titleButton : " + titleButton);
elemOrder1 = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("elemOrder")));
Log.i("elemOrder1 ","elemOrder1 : " + elemOrder1 );
btn = new Button(this);
btn.setText(" " + titleButton + " ");
btn.setId(Id);
btn.setTextColor(Color.parseColor("#000000"));
btn.setTextSize(12);
btn.setPadding(10, 10, 10, 10);
btn.setBackgroundResource(R.drawable.gray_button);
btnlayout.addView(btn,params);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
infoCard.removeAllViews();
for(int i=0;i<=cursorCol.getCount();i++){
Log.i("","titleButton : "+titleButton);
}
}
}
But the problem is that when I click the button it's showing only the last titleButton. Actually I don't need to show titleButton, I just did it for testing purposes. Any ideas how can I create different onClick methods for every single button?
I think the problem lies with this line of code:
btn = new Button(this);
You are editing the same button over and over again in your loop and not acutally creating a new one. To create a new one you will need to do this:
Button new_btn = new Button(this);
This will create a brand new one every time you iterate through your for loop.
I am trying to do this:
Programatically create 4 buttons on a layout. Then, create an onclick listener for each of the button. Then, based on which button is pressed, will do some logic.
I have created a LinearLayout in my XML file and called it "layout".
So, my codes go something like this:
layout = (LinearLayout)findViewById(R.id.layout);
//Create the array of buttons
Button [] subjectButtons_BT = new Button[4];
for(int i=0; i<4; i++){
subjectButtons_BT[i] = new Button(this);
// Add the button to the layout
layout.addView(subjectButtons_BT[i]);
subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// if it is the first button, do LOGIC1
// if it is the second button, do LOGIC2 etc
}
});
}
So far, I have managed to create the 4 buttons and I can click on the buttons.
However, I do not know how to the logic in the setOnClickListener part.
I wanted to know which button is pressed. So, I tried using v.getId() but it always returns a -1.
Can someone advise if this is the right way to go? And if so, how to do the logic?
Thanks.
You have two options for identify which dynamic button is clicked.
1) Set ID to the button and compare ID
2) Set Tag to the button if you have come more information about button
and want to access it
1) You can set id to the button and in onClick() method you can get id by button.getId() method and you can compare ids and perform action according to click.
2) If you set tag then you have to get tag by calling button.getTag() method and by this way you can pass object with the button
You can set the id of the buttons after you create them, and then check for that id within the OnClickListener
layout = (LinearLayout)findViewById(R.id.layout);
//Create the array of buttons
Button [] subjectButtons_BT = new Button[4];
for(int i=0; i<4; i++){
subjectButtons_BT[i] = new Button(this);
subjectButtons_BT[i].setId(i);
// Add the button to the layout
layout.addView(subjectButtons_BT[i]);
subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
int id = v.getId();
if (id == 0) {
} else if (id == 1) {
}
//etc.
}
});
}
I am creating a dynamic list in which has 2 buttons (Accept and Reject) and one TextView (Email ID which is unique).
I have to accept/reject the email Id on button click event. My problem is I am not able to get the Id or any other reference to point which accept button i had clicked.
Assign an ID to each button in your view.
Then create a separate OnClickListener for each button, each calling their own method?
If each item in your list has 2 buttons, search for the ID withing the parent container, then add the OnClickListener to the found button.
Create dynamic controll.You have to set some id for your controll
` ////////////Create weekdays button//////////////
Button week_btn = new Button(this);
week_btn.setWidth(55);
week_btn.setHeight(45);
week_btn.setText("days");
week_btn.setGravity(Gravity.TOP);
week_btn.setId(NEW_BTN_SELECT_DAYWEEK_id + i);
cur_lin_layout.addView(week_btn, p);
week_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
current_period_id = v.getId() + 500;
lDayFlags = 0;
showDialog(0);
}
});`
just create your own constant id and increase it after creating new controll(button). You set your controll and you can give it from click listner or finviewbyid