Dynamically Adding LinearLayouts in Android - android

I'm trying to add LinearLayouts dynamically but it's just not working. I think I just need another set of eyes to look it over. Can anyone help me?
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.parentLayout);
lLayout = new LinearLayout[8];
for(int i = 0; i < lLayout.length; i++) {
lLayout[i] = new LinearLayout(this);
lLayout[i].setId(i);
lLayout[i].setOrientation(LinearLayout.HORIZONTAL);
if(i%2 == 0) {
lLayout[i].setBackgroundColor(Color.GREEN);
} else {
lLayout[i].setBackgroundColor(Color.MAGENTA);
}
parentLayout.addView(lLayout[i]);
}

You need to set LayoutParams, try adding this:
lLayout[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

It looks like you are trying to make a listview yourself using linearlayouts rather than actually using the ListView already supported.
If you are actually trying to do that, you should first give the layouts inside the view a width and height. I'd also put the list in a scrollview in case it overflows the outer layout.

Maybe try this
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.parentLayout);
lLayout = new LinearLayout[8];
for(int i = 0; i < lLayout.length; i++) {
lLayout[i] = new LinearLayout(this);
lLayout[i].setId(i);
lLayout[i].setOrientation(LinearLayout.HORIZONTAL);
if(i%2 == 0) {
lLayout[i].setBackgroundColor(Color.GREEN);
} else {
lLayout[i].setBackgroundColor(Color.MAGENTA);
}
LinearLayout.LayoutParams myLayoutParams = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
myLayoutParams.leftMargin = 0;
myLayoutParams.topMargin = 50 * i;
myLayoutParams.width = myScreenSize; //e.g. 480
myLayoutParams.height = 50;
lLayout[i].setLayoutParams(myLayoutParams);
parentLayout.addView(lLayout[i]);
}

Related

Set buttons ids with Custom Adapter

Which will be the better way to create a Vertical Lineal layout with four or more buttons in each row
The problems I have face are the following:
Setting the id of each button manually will result in a lot of repetitive code, more resources usage and you will have to change everyone to add a feature or change something (I think using an adapter will be the most efficient way, but...)
From what I know using a CustomAdapter don't help you set a unique ID to the buttons
Can you use an adapter to set a different id for each button dipending of the row?
Example:
second button of third row: r3b2
fifth button of first row: r1b5
Thanks.
You can create the buttons programmatically in our Activity class like this
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout); // the layout in which u want to display the buttons
layout.setOrientation(LinearLayout.VERTICAL);
int count = 1;
for (int i = 0; i < 5; i++) { // i = row count
LinearLayout row = new LinearLayout(getActivity());
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
for (int j = 0; j < 7; j++) { // j = column count (create 7 buttons in each row)
int id = count;
final Button btnTag = new Button(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
params.weight = 1;
params.gravity = Gravity.CENTER;
btnTag.setLayoutParams(params);
btnTag.setBackgroundColor(Color.parseColor("#ffffff"));
String dateSuffix = count + getDayNumberSuffix(count);
btnTag.setTag(dateSuffix);
btnTag.setId(id);
btnTag.setText(count + "");
btnTag.setTextSize(12.0f);
btnTag.setOnClickListener(getOnClickDoSomething(btnTag, count));
row.addView(btnTag);
count++;
}
layout.addView(row);
}
View.OnClickListener getOnClickDoSomething(final Button btnTag, final int count) {
return new View.OnClickListener() {
public void onClick(View v) {
// here you can do what u want to do on button click
}
}

setText() not working on dynamically added buttons in linearLayout

The title says it all.
I am making an application in which i have to add dynamic buttons in a linear layout i have tried:
testButtons = new Button[caseDetails.length()];
for (int i = 0; i < caseDetails.length(); i++) {
temp = caseDetails.getJSONObject(i);
Log.e("TEMP " + i, temp.toString());
testButtons[i] = new Button(this) ;
testButtons[i].setText("Hello Hi");
testButtons[i].setHeight(LayoutParams.WRAP_CONTENT);
testButtons[i].setWidth(LayoutParams.WRAP_CONTENT);
testButtons[i].setPadding(20, 20, 20, 20);
testLayout.addView(testButtons[i]);
}
All i can see on emulator is two buttons with no text. Why is this happening?
had the same problem.. try this..
testButtons = new Button[caseDetails.length()];
for (int i = 0; i < caseDetails.length(); i++) {
temp = caseDetails.getJSONObject(i);
testButtons[i] = new Button(this) ;
testButtons[i].setText("Hello Hi");
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
testButtons[i].setPadding(20, 20, 20, 20);
testLayout.addView(testButtons[i], lp);
}
also make sure your linearLayout's orientation is vertical. Good Luck! :)

android: how to fill a relativelayout ( screen size) with many textviews created dynamically?

I tried to use below code, but the textviews do not change line after it reach the end of screen.
RelativeLayout ll = (RelativeLayout)findViewById(R.id.viewObj);
int lastid=0;
for (int i=0; i<100; i++) {
String teststr = " hello ";
TextView textView2 = new TextView(this);
textView2.setId(i+1);
textView2.setTextSize(30);
textView2.setBackgroundColor(Color.GREEN);
textView2.setTextColor(Color.RED);
textView2.setTypeface(Typeface.MONOSPACE);
textView2.setText(teststr+String.valueOf(i));
if (i>0)
{
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.RIGHT_OF, lastid);
ll.addView(textView2, lay);
} else {
ll.addView(textView2);
};
lastid = textView2.getId();
}
However, I dont know how to determine when to change line. I just keep on putting new textview to the right of the last one created. Can anyone tell me the correct logic to do the task? many thanks.
Easy fix. Switch to a dynamically-created LinearLayout, and set its orientation to vertical:
lay.setOrientation(LinearLayout.VERTICAL);

Android: Dynamically add views to ScrollView

I have a ScrollView and I want to insert a user specified number of HorizontalScrollViews. So what user says he wants to have a matrix of 5x5 elements, I want to insert 5 HorizontalScrollViews with 5 EditText objects each. My program adds the first line just as it's supposed to, but the rest not.
for (int i = 0; i < number; i++) {
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(par2);
HorizontalScrollView row = new HorizontalScrollView(this);
row.setLayoutParams(par1);
row.addView(ll);
for (int j = 0; j < number; j++) {
EditText txt = new EditText(this);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txt.setHint(i+","+j);
ll.addView(txt);
}
latout_in_scrollview.addView(row);
}
Any ideas why? Thanks!
EDIT:
The 1:1 code im using
LinearLayout dijkstra_rows;
FrameLayout.LayoutParams par1 = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams par2 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_dijkstra);
dijkstra_rows = (LinearLayout) findViewById(R.id.dijkstra_rows);
Bundle extras = getIntent().getExtras();
number = extras.getInt("vertexes");
for (int i = 0; i < number; i++) {
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(par2);
HorizontalScrollView row = new HorizontalScrollView(this);
row.setLayoutParams(par1);
row.addView(ll);
for (int j = 0; j < number; j++) {
EditText txt = new EditText(this);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txt.setHint(i+","+j);
ll.addView(txt);
}
dijkstra_rows.addView(row);
}
}
ScrollView can contain only one childView. You can put any layout as per your requirement. I generally use Relative Layout...
Then add views dynamically to relative layout
viewLayout = (ViewGroup) mView.findViewById(R.id.YOUR_RELATIVE_LAYOUT_ID);
View lastCard = viewLayout.getChildAt(viewLayout.getChildCount() - 1);
// INFLATE YOUR NEW VIEW YOU WANT TO ADD
CardView cardView = (CardView)
LayoutInflater.from(getContext()).inflate(R.layout.card_nearest_stop, null);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//Set id to view
int id = 125;
if (lastCard != null) {
params.addRule(RelativeLayout.BELOW, lastCard.getId());
id = lastCard.getId() + 125;
}
cardView.setLayoutParams(params);
cardView.setId(id);
viewLayout.addView(cardView);
ScrollView is a single element container.
A ScrollView is a FrameLayout, meaning you should place one child in
it containing the entire contents to scroll; this child may itself be
a layout manager with a complex hierarchy of objects. A child that is
often used is a LinearLayout in a vertical orientation, presenting a
vertical array of top-level items that the user can scroll through.
You are adding multiple LinearLayouts here
for (int i = 0; i < number; i++) {
LinearLayout ll = new LinearLayout(this);
.
.
}
You should have only one out of this loop. Then add this one to your scrollView, in Loop you can add muliple HorizontolScrollViews to this LinearLayout

Android Creating button dynamically and fill layout

I'm creating a button dynamically. The number of button is depend on the size of arraylist. the problem is, after creating the button I will add to the layout using addview method. The problem is I'm using linear layout, as by default orientation for linear layout is horizontal, so the button will fill the layout horizontally. Because of that some of the button is not visible. What I'm trying to achieve is something look like this
My code is like below:
Button[] tv = new Button[arraylist.size()];
for(int i=0;i<arraylist.size();i++){
tv[i] = new Button(getApplicationContext());
tv[i].setText(arraylist.get(i).toString());
tv[i].setTextColor(Color.parseColor("#000000"));
tv[i].setTextSize(20);
tv[i].setPadding(15, 5, 15, 5);
linearlayout.addView(tv[i]);
}
If I set the orientation of linear layout to vertical the button will fill vertically. So if there any solution to create the button dynamically and fill the layout both horizontal and vertical as shown by image.
There is not a canned layout in the SDK that does exactly what you are aiming for (i.e. lay out as many children horizontally as will fit, then flow to the next line to lay out some more), so you will need to create a custom ViewGroup that accomplishes this purpose. Luckily for you, Romain Guy created one live on-screen during a presentation at Devoxx.
Here is a link to that presentation video.
Here is a link to the sample code and slides.
HTH
After 2 days struggling thinking bout this problem finally I've found the solution. I've try put all my contact list, store it in arraylist and create button for each element and I'm quite satisfy with the result after display on the screen. Here is how I do the trick. I really appreciate for any comment from others.
variable declaration;
int currWidth;
int currCounter;
boolean isNewLine;
LinkedList<HashMap<String,Object>> button;
ArrayList<String> nameNumber = new ArrayList<String>();
contactWrapper = (LinearLayout) findViewById(R.id.multiple_selection);
create button onClick event;
for(int i=0;i<nameNumber.size();i++){
tv[i] = new Button(getApplicationContext());
String[] namePhone = nameNumber.get(i).toString().split("##");
phoneNumber.add(namePhone[1]);
tv[i].setText(namePhone[0]);
tv[i].setTag(namePhone[1]);
tv[i].setTextColor(Color.parseColor("#000000"));
tv[i].setTextSize(20);
tv[i].setPadding(15, 5, 15, 5);
tv[i].measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("button", tv[i]);
map.put("width", tv[i].getMeasuredWidth());
button.add(map);
}
drawLayout();
drawlayout method is where I add button and arrange accordingly to fit the layout;
public void drawLayout(){
int counter=0;
contactWrapper.setOrientation(LinearLayout.VERTICAL);
currCounter=0;
currWidth=0;
isNewLine=false;
LinearLayout[] row = new LinearLayout[nameNumber.size()];
row[currCounter] = new LinearLayout(getApplicationContext());
#SuppressWarnings("rawtypes")
Iterator it = button.iterator();
for(int i = 0; i<button.size(); i++){
it.next();
row[currCounter].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
currWidth += Integer.parseInt(button.get(i).get("width").toString());
if(isNewLine){
if(currWidth < contactWrapper.getWidth()){
row[currCounter].addView((View) button.get(i).get("button"));
if(!it.hasNext()){
contactWrapper.addView(row[currCounter]);
}else{
if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}else{
isNewLine=false;
}
}
}else{
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}
}else{
if(currWidth < contactWrapper.getWidth()){
if(!it.hasNext()){
row[currCounter].addView((View) button.get(i).get("button"));
contactWrapper.addView(row[currCounter]);
}else{
row[currCounter].addView((View) button.get(i).get("button"));
if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}else{
isNewLine=false;
}
}
}else{
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}
}
counter++;
}
}
this code quite messy + I'm not fully utilize the size of array for
LinearLayout[] row = new LinearLayout[nameNumber.size()];
but it work for me.
use TableLayout instead of LinearLayout this is tutorial hope this will help you to get the idea
Does you set android:layout_width="fill_parent"?
Do this if you don't.
Well, you can try using more sophisticated way. You can create horizontal linear layout, and add buttons to it. Every time you're attempting to add new button, you check if there is place for it, by finding difference between layout's and buttons widths.
Each time your horizontal layout is filled, you add it to another vertical layout, and create another horizontal layout to store buttons left.
I used that trick in my apps.
try this its working fine
this.row = (LinearLayout)findViewById(R.id.tags);
this.row.setOrientation(LinearLayout.VERTICAL);
LinearLayout one = new LinearLayout(this);
//get the size of the screen
Display display = getWindowManager().getDefaultDisplay();
this.screenWidth = display.getWidth(); // deprecated
this.screenHeight = display.getHeight();// depreceted
for(int i=0; i<6; i++) {
one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
this.button = new Button(this);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
if(i==0) {
this.button.setText("Muhammad Aamir");
} else if(i==1) {
this.button.setText("Ahsan");
} else if(i==2) {
this.button.setText("Mujahid");
} else if(i==3) {
this.button.setText("Waqas");
} else if(i==4) {
this.button.setText("Ali");
} else {
this.button.setText("Ahmer");
}
//get the size of the button text
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(button.getTextSize());
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));
float size = mPaint.measureText(button.getText().toString(), 0, button.getText().toString().length());
size = size+14;
this.totalTextWidth += size;
if(totalTextWidth < screenWidth) {
one.addView(button);
} else {
this.row.addView(one);
one = new LinearLayout(this);
one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
one.addView(button);
this.totalTextWidth = size;
}
}
this.row.addView(one);
}

Categories

Resources