I have this code which generates a GUI programmatically
TableLayout table;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
table = new TableLayout(this);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
table.setLayoutParams(lp);
table.setStretchAllColumns(true);
TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
TableRow.LayoutParams cellLp = new TableRow.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
int count = 0;
for (int r = 0; r < 3; ++r) {
TableRow row = new TableRow(this);
for (int c = 0; c < 3; ++c) {
count++;
final Button btn = new Button(this);
btn.setText("");
btn.setId(count);
btn.setOnClickListener(this);
row.addView(btn, cellLp);
}
table.addView(row, rowLp);
}
TableRow erow = new TableRow(this);
Button btn = new Button(this);
btn.setText("Reset");
btn.setId(10);
btn.setOnClickListener(this);
erow.addView(btn, cellLp);
table.addView(erow, rowLp);
setContentView(table);
}
In the listener, I can change the text of the button I click this way
#Override
public void onClick(View v) {
Button btn = (Button)v;
btn.setText("text");
}
But, how, can I interact with other buttons? I have tried with something like btn = (Button)findViewById(7); but it doesn't work.
I also tried with an array of buttons but still doesn't work. Any tips?
findViewById() is mainly for views created by inflating XML layout files.
Though you can call setId() for views, in this case you should keep simply references to the programmatically created views, i.e.
private Button button1;
and then just use those fields.
Try to use Tag instead id for your buttons:
for (...) {
count++;
final Button btn = new Button(this);
...
btn.setTag(count);
btn.setOnClickListener(this);
...
}
And in listener call (Integer)v.getTag()
Related
This question already has answers here:
How to Programmatically Add Views to Views
(7 answers)
Closed 3 years ago.
I have made some buttons and stored them into an ArrayList. I need to add these buttons to my main activity layout.
I have tried to create a linearlayout and make that my main layout, however the buttons do not show.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// createButtons();setContentView(new CircleView(this));
}
public void createButtons() {
ArrayList<Button> buttons = new ArrayList<>();
int n = 0; // the number of buttons circumferencing the semicircle
for(int i = 0; i < 6; i ++) {
n = 7;
Button button = new Button(this);
double Xval = 500* Math.cos(i * Math.PI / n);
double Yval = 500* Math.sin(i * Math.PI / n);
button.setX((float)(Xval));
button.setY((float)(Yval));
buttons.add(button);
}
}
}
I expect to have my buttons appear in my main activity layout.
I Found some solutions for your case, but not the right solution, you must change it to your own implementation.
One way to do this, is create a layout and get the layout in code by id and in that you insert your buttons. This is one way to do this:
Button myButton = new Button(this);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
Inserting mutiple buttons with an event, even if I do prefer to implement OnClickListener on the class:
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
You can find many samples of android native in the link Android Samples
Source
I don't know what is the problem. I am creating the simple phone-book, so i have name of abonent, image and call button under the name. And when i try to set width with the layoutParams parameter for button, it doesn't change anything, btn.setWidth(); doesn't work either.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout linear = (LinearLayout)findViewById(R.id.linear);
LinearLayout.LayoutParams sublparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams childparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams imageparams = new LinearLayout.LayoutParams(200, 200);
linear.setOrientation(LinearLayout.VERTICAL);
for(int i = 0; i < 10 ; i++){
LinearLayout sublinear = new LinearLayout(this);
Button btn = new Button(this);
ImageView img = new ImageView(this);
TextView txt = new TextView(this);
img.setImageResource(R.drawable.img);
txt.setText("Abonent " + (i+1));
btn.setBackgroundColor(getColor(R.color.mygreen));
btn.setText("+3800000");
txt.setLayoutParams(childparams);
btn.setLayoutParams(imageparams);
img.setLayoutParams(imageparams);
linear.addView(txt);
sublinear.addView(img);
sublinear.addView(btn);
linear.addView(sublinear, sublparams);
}
}
}
result of programm, green vertical lines are buttons, that i cannot to make wider
your button is using LayoutParams to set width and heigth so you need to change this properties here (LinearLayout.LayoutParams(widht, height)):
LinearLayout.LayoutParams imageparams = new LinearLayout.LayoutParams(500, 300);
and the size of your button must change, because you are setting this values.
btn.setLayoutParams(imageparams);
I have a tableLayout in Android and each row in the table has an ImageButton, a TextView and another ImageButton. The no. of rows is variable and I am generating the table programmatically at runtime.
I am setting id of the buttons to be same as row number by using ImageButton.setId(i).
When the user clicks on any ImageButton, I want to be able to access its id in the onClickListener. Is there a way to do it? All answers on stackoverflow which I have seen regarding this involve a fixed no. of buttons and use a switch statement to find out the id. But since the no. of buttons is dynamic for me, this won't work for me.
Here's the code:
TableLayout tbl_layout = (TableLayout) findViewById(R.id.tbl_layout);
for (int i=0; i<num_rows; i++) {
TableRow tbl_row= new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
tbl_row.setLayoutParams(lp);
tbl_row.setPadding(0, 5, 0, 5);
//tbl_row.setBackground(R.drawable.border);
if(i == 3)
tbl_row.setBackgroundColor(Color.GREEN);
else
tbl_row.setBackgroundColor(Color.parseColor("#ffffd1"));
tbl_row.setGravity(Gravity.CENTER);
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Some text goes here\New line.");
ImageButton infoBtn = new ImageButton(this);
infoBtn.setImageResource(R.drawable.ic_menu_info);
infoBtn.setAdjustViewBounds(true);
infoBtn.setScaleType(ImageView.ScaleType.FIT_XY);
infoBtn.setMaxHeight(120);
infoBtn.setMaxWidth(120);
infoBtn.setId(i);
//infoBtn.setBackgroundColor(Color.BLUE);
ImageButton cameraBtn = new ImageButton(this);
cameraBtn.setImageResource(R.drawable.ic_menu_camera);
cameraBtn.setAdjustViewBounds(true);
cameraBtn.setScaleType(ImageView.ScaleType.FIT_XY);
cameraBtn.setMaxHeight(120);
cameraBtn.setMaxWidth(120);
cameraBtn.setId(i);
tbl_row.addView(infoBtn);
tbl_row.addView(tv);
tbl_row.addView(cameraBtn);
tbl_layout.addView(tbl_row, i);
}`
for (int i=0; i<num_rows; i++) {
TableRow tbl_row= new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
tbl_row.setLayoutParams(lp);
tbl_row.setPadding(0, 5, 0, 5);
//tbl_row.setBackground(R.drawable.border);
if(i == 3)
tbl_row.setBackgroundColor(Color.GREEN);
else
tbl_row.setBackgroundColor(Color.parseColor("#ffffd1"));
tbl_row.setGravity(Gravity.CENTER);
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Some text goes here\New line.");
ImageButton infoBtn = new ImageButton(this);
infoBtn.setImageResource(R.drawable.ic_menu_info);
infoBtn.setAdjustViewBounds(true);
infoBtn.setScaleType(ImageView.ScaleType.FIT_XY);
infoBtn.setMaxHeight(120);
infoBtn.setMaxWidth(120);
//infoBtn.setId(i);
//infoBtn.setBackgroundColor(Color.BLUE);
infoBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
ImageButton cameraBtn = new ImageButton(this);
cameraBtn.setImageResource(R.drawable.ic_menu_camera);
cameraBtn.setAdjustViewBounds(true);
cameraBtn.setScaleType(ImageView.ScaleType.FIT_XY);
cameraBtn.setMaxHeight(120);
cameraBtn.setMaxWidth(120);
//cameraBtn.setId(i);
cameraBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
tbl_row.addView(infoBtn);
tbl_row.addView(tv);
tbl_row.addView(cameraBtn);
tbl_layout.addView(tbl_row, i);
}`
I have a method that creates layouts vertically each with 3 buttons aligned horizontally with onClick creating one at a time with each click to a max of 5 layouts. How do I remove those layouts with a button that was created.
public void addTroop(Editable name){
LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);
if (count <= 5)
{
//CREATE NEW LINEAR LAYOUT
LinearLayout addTroopLayout = new LinearLayout(this);
//CREATE LAYOUT PARAMS FOR LAYOUT
LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLayout.bottomMargin = 10;
//STYLE NEW LINEAR LAYOUT
addTroopLayout.setTag("addTroopLayout" + count);
addTroopLayout.setLayoutParams(newLayout);
addTroopLayout.setOrientation(LinearLayout.HORIZONTAL);
//CREATE NEW BUTTONS
Button newTroop = new Button(this);
Button remove = new Button(this);
Button change = new Button(this);
//CREATE LAYOUT PARAMS FOR BUTTONS
LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
//STYLE NEW BUTTONS
newTroop.setText(name);
newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
newTroop.setLayoutParams(newTroopParam);
remove.setTag("rmvBtn" + count);
remove.setText("-");
remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
remove.setLayoutParams(rmvBtnParam);
change.setText("...");
change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
change.setLayoutParams(chngNameParam);
//ADD VIEWS TO NEW LAYOUT
addTroopLayout.addView(newTroop);
addTroopLayout.addView(remove);
addTroopLayout.addView(change);
//ADD NEW LAYOUT TO mainPage LAYOUT
mainPage.addView(addTroopLayout);
//Increment Counter
count++;
}
}
Each time a layout is created it set with the following so that each layout will be named addTroopLayout1, addTroopLayout2, etc etc.
addTroopLayout.setTag("addTroopLayout" + count);
I did the same thing with the remove button
remove.setTag("rmvBtn" + count);
So now how do I access/edit/remove these? Could I do something like
Button rmvBtn1 = (Button) findViewByTag(R.id.rmvBtn1);
rmvBtn1.setOnClickListener(new view.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//REMOVE CREATED LAYOUT
//DECREMENT ALL LAYOUT TAGS BY 1 IF NOT LAST LAYOUT
//DECREMENT count VAR BY ONE
//ERASE ALL VARIABLES ASSOCIATED WITH THIS VIEW
}
});
This code is obviously giving me errors and im sure this is something simple. Thanks.
////////////////////EDIT/////////////////////
Sorry if I wasent clear on what I wanted. So I have created/styled a button using my if statement that is called from a method using an onClick:
Button newTroop = new Button(this);
remove.setTag("rmvBtn" + count);
Count starts at 1 and is incremented in when a button is pressed. Now I want to findViewByTag for that button to use it with something like:enter code here
Button rmvBtn1 = (Button) findViewByTag(rmvBtn1);
rmvBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//REMOVE CREATED LAYOUT
//DECREMENT ALL LAYOUT TAGS BY 1 IF NOT LAST LAYOUT
//DECREMENT count VAR BY ONE
//ERASE ALL VARIABLES ASSOCIATED WITH THIS VIEW
}
});
So specifically how to I use a button that was created with my if statement? Do I still have to define it by
Button rmvBtn1 = (Button) findViewByTag(rmvBtn1);
or is there another way I should be doing this?
keep view in remove button, and keep view's parent int view's tag
addTroopLayout.setTag(mainPage);
remove.setTag(addTroopLayout);
and then use it like this
rmvBtn1.setOnClickListener(new view.OnClickListener() {
#Override
public void onClick(View v) {
View willRemove = (View)v.getTag();
LinearLayout mainPage = (LinearLayout)willRemove.getTag();
mainPage.removeView(willRemove);
}
});
I don't use xml in my UI.
My code of mainlayout:
public class MainActivity extends ActionBarActivity {
LinearLayout LinLay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
this.setContentView(sv);
LinLay = new LinearLayout(this);
LinLay.setOrientation(LinearLayout.VERTICAL);
LinLay.setBackgroundColor(Color.parseColor("#000000"));
sv.addView(LinLay);
And adding a Edittext:
EditText txt = new EditText(this);
txt.setBackgroundColor(Color.parseColor("#ff9a16"));
txt.setHint("Txt(0,0)");
LayoutParams txtParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
txtParams.width = 300;
txtParams.height = 70;
txtParams.leftMargin = 0;
txtParams.topMargin = 0;
txt.setLayoutParams(txtParams);
LinLay.addView(txt);
Finally adding a Button:
Button btn = new Button(this);
btn.setBackgroundColor(Color.parseColor("#cb0016"));
btn.setText("Btn(0,0)");
LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
btnParams.width = 300;
btnParams.height = 70;
btnParams.leftMargin = 0;
btnParams.topMargin = 0;
btn.setLayoutParams(btnParams);
LinLay.addView(btn); }
The Edittext's must be X position = 0 and Y position = 0 of MainScreen.
The Button's must be X position = 0 and Y position = 0 of MainScreen.
But the Button taking referance is the Edittext and it takes position in X:0,Y:70 of MainScreen.
The program screen: prntscr.com/4ixo7z
If my LinearLayout that's LinLay is Horizontal, the button takes position in X:300,Y:0 of MyScreen. I want to taking position in MainScreen. I don't want to taking referance. Help me.
The Horizontal screen: prntscr.com/4ixo8i
Change your LinearLayout and use RelativeLayout, remove orientation. add your product relatively, this will solve your issue.