On create i am creating my layout problematically.After that on click on button i want to remove the previous layout content How could i do that i tried that removeView.But it didn't worked for me .Here is my code
void setDate(){
flightResult=(LinearLayout)findViewById(R.id.flightResultData);
LinearLayout.LayoutParams flightDetailsLayout = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout.LayoutParams forUnderLine = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
forUnderLine.setMargins(0,0, 0, 0);
flightDetailsLayout.setMargins(0, 40, 0, 0);
for(int i=0;i < 5;i++){
TextView line=new TextView(this);
line.setBackgroundResource(R.layout.shape_line);
line.setLayoutParams(forUnderLine);
if(i!=0){
flightResult.addView(line);
}
LinearLayout flightInformations=(LinearLayout)inflater.inflate(R.layout.flight_details_layout, null);
flightLogo=(ImageView)flightInformations.findViewById(R.id.flightLogo);
flightCompany = (TextView)flightInformations.findViewById(R.id.flightCompany);
flightLogo.setImageResource(R.drawable.airindia);
flightCompany.setText("AirIndia");
flightResult.addView(flightInformations);
}
TextView dummy=new TextView(this);
dummy.setLayoutParams(flightDetailsLayout);
flightResult.addView(dummy);
}
AFter on create on click of a button i have again call this function and at that time when i calling this it is appending the result .I am want new result on the click of the button what i have to do for this Please help me
And my xml file
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="#+id/sortFlightLayouts">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:id="#+id/flightResultData"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
View.setVisibility(View.GONE);
Related
I followed this piece of code written by Aby in another question: https://stackoverflow.com/a/22682248/5915747
The beginning of my text is being cut off on the left side of my screen. I'm missing quite a bit of info and not sure how to fix it, I have tried everything that worked for others but it has not worked for me.
popup.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollviewtest"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:context="com.info.PopupActivity"
android:background="#f0f0f0"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:id="#+id/rel_layout"
android:orientation="vertical">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/table_layout"
android:background="#80000000"
android:layout_centerHorizontal="true">
</TableLayout>
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
init method:
public void init() {
View popupview = getLayoutInflater().inflate(R.layout.popup, null);
popupWindow = new PopupWindow(
popupview, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
popupWindow.showAtLocation(popupview, Gravity.CENTER, 0, 0);
popup_shown[0] = true;
TableLayout tableLayout = (TableLayout) popupview.findViewById(R.id.table_layout);
TableRow row0 = new TableRow(this);
TextView text0 = new TextView(this);
text0.setText("Test Header1");
row0.addView(text0);
TextView text1 = new TextView(this);
text1.setText("Test Header2");
row0.addView(text1);
TextView text2 = new TextView(this);
text2.setText("Teset Header3");
row0.addView(text2);
TextView text3 = new TextView(this);
text3.setText("Test Header4");
row0.addView(text3);
TextView text4 = new TextView(this);
text4.setText("Test Header5");
row0.addView(text4);
tableLayout.addView(row0);
for (int i = 0; i < 8; i++) {
TableRow tableRow = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setGravity(Gravity.CENTER);
tv0.setText("long test field 0");
tableRow.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setGravity(Gravity.CENTER);
tv1.setText("long test field 1");
tableRow.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setGravity(Gravity.CENTER);
tv2.setText("long test field 2");
tableRow.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setGravity(Gravity.CENTER);
tv3.setText("long test field 3");
tableRow.addView(tv3);
TextView tv4 = new TextView(this);
tv4.setGravity(Gravity.CENTER);
tv4.setText("long test field 3");
tableRow.addView(tv4);
tableLayout.addView(tableRow);
}
}
The longer the strings are for the text views, the more it crops off, however it's a horizontal scrollview, so it should just start at the beginning of the screen and add length to the end, which is scrollable, right?
This is what it ends up looking like with the current strings in vertical/portrait orientation:
Vertical View
This is what it looks like in horizontal, it seems to fix since my screen is large enough for the data:
Horizontal View
If you have any questions, please ask!
Solved this by adding padding to the scrollview. It seems this is a common android bug.
I don't know will it work or not but try removing
android:layout_gravity="center"
line from Relative Layout
The way my program works is that I take user input for 3 items, create a horizontal LinearLayout programmatically with those three items. Then place that LinearLayout inside a RelativeLayout that is defined in XML.
User can keep adding these 3-item horizontal LLs to the bottom of the RelativeLayout, which acts as a list in this case.
I am specifying a weight in the setLayoutParams method for each TextView object
TextView quantityText = new TextView(MainActivity.this);
quantityText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
quantityText.setText("" + currentIngredientMeasurementQuantity);
TextView typeText = new TextView(MainActivity.this);
typeText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
typeText.setText(currentIngredientMeasurementType);
TextView nameText = new TextView(MainActivity.this);
nameText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 4f));
nameText.setText(currentIngredientName);
LinearLayout ll = new LinearLayout(MainActivity.this);
ll.setId(View.generateViewId());
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.ingredient_list_relativelayout);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//Find last member of RelativeLayout
View lastIngredient = (View) relativeLayout.getChildAt(totalIngredientQuantity - 1);
relativeParams.addRule(RelativeLayout.BELOW, lastIngredient.getId());
relativeParams.setMargins(0, 0, 0, 0);
ll.addView(quantityText);
ll.addView(typeText);
ll.addView(nameText);
relativeLayout.addView(ll, relativeParams);
The problem is, the TextViews aren't being displayed the way I'd like them to. I'd like each of the three items to line up vertically, like a proper list.
Instead, I get something like this. You can see that the length of the strings is somehow affecting the way the layout is stored/displayed.
I know it's a big block of code, but any help would be appreciated!
Try this:-
Create a custom layout insteadof creating controls as dynamically
custom.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="90">
<TextView
android:id="#+id/textview1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="30"
android:gravity="center"
android:text="text1"/>
<TextView
android:id="#+id/textview2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="30"
android:text="text2"/>
<TextView
android:id="#+id/textview3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="30"
android:text="text3"/>
</LinearLayout>
Add this view in RelativeLayout
View view = factory.inflate(R.layout.custom, null);
relativeLayout.addView(view);
You need to set the layout_width property to 0 for layout weight property to work well. I made a couple to changes to your code to make it work well for me.
Try this,
private void addNewRow(float currentIngredientMeasurementQuantity, String currentIngredientMeasurementType, String currentIngredientName) {
TextView quantityText = new TextView(MainActivity.this);
quantityText.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
quantityText.setText("" + currentIngredientMeasurementQuantity);
TextView typeText = new TextView(MainActivity.this);
typeText.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
typeText.setText(currentIngredientMeasurementType);
TextView nameText = new TextView(MainActivity.this);
nameText.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 4f));
nameText.setText(currentIngredientName);
LinearLayout ll = new LinearLayout(MainActivity.this);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
ll.setId(View.generateViewId());
} else {
ll.setId(totalIngredientQuantity);
}
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.ingredient_list_relativelayout);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//Find last member of RelativeLayout
View lastIngredient = (View) relativeLayout.getChildAt(totalIngredientQuantity - 1);
if (lastIngredient != null) {
relativeParams.addRule(RelativeLayout.BELOW, lastIngredient.getId());
relativeParams.setMargins(0, 0, 0, 0);
}
ll.addView(quantityText);
ll.addView(typeText);
ll.addView(nameText);
relativeLayout.addView(ll, relativeParams);
}
You have to set the Gravity to Left (or Start) on your TextViews before adding them to the LinearLayout, just like this:
LinearLayout.LayoutParams name_lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
name_lp.gravity = Gravity.LEFT;
nameText.setLayoutParams(name_lp);
Try to tell your your Textviews to use all the available space they can get. So they will fill the whole LinearLayout.
Instead of WRAP_CONTENT use MATCH_PARENT or FILL_PARENT
In XML you could use 0dip like described here: In android layouts what is the effect/meaning of layout_height="0dip"
Another idea would be to use TableLayout or GridLayout http://developer.android.com/reference/android/widget/GridLayout.html
http://developer.android.com/reference/android/widget/TableLayout.html
Have Fun
I tryning to get a LinearLayout in a ScrollView like this:
The greenspace should be wrap_content and the red one should take the remaining space.
But this is my Result:
This is my Code:
foreach(Ele el : elements) {}
LinearLayout layout = new LinearLayout(getActivity());
LayoutParams layout_parm = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(layout_parm);
TextView tv = new TextView(getActivity());
tv.setLayoutParams( new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1) );
tv.setBackgroundColor(getActivity().getResources().getColor((R.color.red)));
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
tv.setText("Name...");
tv.setPadding(0, 0, 0, getDP(5));
layout.addView(tv);
TextView iView = new TextView(getActivity());
iView.setText("OTO");
iView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
iView.setBackgroundColor(getActivity().getResources().getColor((R.color.green)));
iView.setLayoutParams( new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0) );
layout.addView(iView);
frg_layout.addView(layout);
}
I am so confused! Maybe you can help me to find out my fail...
Thank you!
The Parent-ViewGroup:
<LinearLayout
android:id="#+id/frg_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="top"
android:orientation="vertical" />
you change the layout orientation
LinearLayout layout = new LinearLayout(getActivity());
LayoutParams layout_parm = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(layout_parm);
uset this type in xml
<LinearLayout
android:id="#+id/frg_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/TextView1"
android:layout_width="250dp"
android:layout_height="60dp"/>
<TextView
android:id="#+id/textview2"
android:layout_width="250dp"
android:layout_height="60dp"
/>
</linearlayout>
I think you've mostly got it right, just need a few minor tweaks:
for each(Ele el:elements){
LinearLayout layout = new LinearLayout(getActivity());
LayoutParams layout_parm = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(layout_parm);
TextView tv = new TextView(getActivity());
//adjust the last number here to make the first block wider or larger as you want
tv.setLayoutParams(new LayoutParams(0, LayoutParams.WRAP_CONTENT, 2));
tv.setBackgroundColor(getActivity().getResources().getColor((R.color.red)));
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
tv.setText("Name...");
tv.setPadding(0, 0, 0, getDP(5));
layout.addView(tv);
TextView iView = new TextView(getActivity());
iView.setText("OTO");
iView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
iView.setBackgroundColor(getActivity().getResources().getColor((R.color.green)));
//adjust your layout param to be a weight instead of wrap_content
iView.setLayoutParams(new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
layout.addView(iView);
frg_layout.addView(layout);
}
See if that works! An alternative would be to build an xml layout which I think is generally cleaner, but programatically it should work roughly the same way.
Using LayoutInflater with xml will bring the solutuion!
Thank you!
I have written this piece of code. But it is not giving the proper result. Please let me know where is the mistake. And I don't want to use Linear Layout.
Here is the xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/custom_relativeLayout1"
android:orientation="horizontal"
android:background="#ffffff">
</RelativeLayout>
</LinearLayout>
String[] but = {"Hello", "Bye"};
int buttonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customLayout = (RelativeLayout) findViewById(R.id.custom_relativeLayout1);
//customLayout is object of relativelayout.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (butArray[i].getId() != 1)
{
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
else
{
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
}
RelativeLayout.RIGHT_OFhoryzontally or vertically align?
so for vertically
Btnparams.addRule(RelativeLayout.BELOW, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
or for horizontally
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
instead of
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
LinearLayout is very nice to use if you want do dynamically add Views and scale them the same. For example if you want to add buttons and have max 3 buttons per row, you can also use another LinearLayout to make a new row.
I 'abuse' the LinearLayout row and a Button for layoutparams templating.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_root"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/ll_row1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"/>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2"/>
</LinearLayout>
</LinearLayout>
Example code:
// Get LL and template params
LinearLayout root = (LinearLayout) findViewById(R.id.ll_root);
LinearLayout row1 = (LinearLayout) findViewById(R.id.ll_row1);
ViewGroup.LayoutParams llRowParams = row1.getLayoutParams();
ViewGroup.LayoutParams btnParams = findViewById(R.id.btn1).getLayoutParams();
// Make new button
Button newBtn = new Button(context);
newBtn.setLayoutParams(btnParams);
newBtn.setText("Button 3");
// Add button to row1
row1.addView(newBtn);
// Add new row
LinearLayout row2 = new LinearLayout(context);
row2.setLayoutParams(llRowParams);
root.addView(row2);
// TODO: add buttons to new row
// TODO: some logic to decide between adding to row or creating new row and adding button
Note: code is not tested, but you should get the idea.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (i != 0) {
Btnparams.addRule(RelativeLayout.RIGHT_OF, i-1);
}
customLayout.addView(butArray[i], Btnparams);
}
I try to add a TextView to a LinearLayout dynamically such as in the following code, but it doesn't appear when I run the application?
setContentView(R.layout.advanced);
m_vwJokeLayout=(LinearLayout) this.findViewById(R.id.m_vwJokeLayout);
m_vwJokeEditText=(EditText) this.findViewById(R.id.m_vwJokeEditText);
m_vwJokeButton=(Button) this.findViewById(R.id.m_vwJokeButton);
TextView tv=new TextView(this);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
What's the problem?
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
You can change lparams according to your needs
Here is a more general answer for future viewers of this question. The layout we will make is below:
Method 1: Add TextView to existing LinearLayout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_linearlayout);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example);
// Add textview 1
TextView textView1 = new TextView(this);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
textView1.setText("programmatically created TextView1");
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
linearLayout.addView(textView1);
// Add textview 2
TextView textView2 = new TextView(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
textView2.setLayoutParams(layoutParams);
textView2.setText("programmatically created TextView2");
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
linearLayout.addView(textView2);
}
Note that for LayoutParams you must specify the kind of layout for the import, as in
import android.widget.LinearLayout.LayoutParams;
Otherwise you need to use LinearLayout.LayoutParams in the code.
Here is the xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff99ccff"
android:orientation="vertical" >
</LinearLayout>
Method 2: Create both LinearLayout and TextView programmatically
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// NOTE: setContentView is below, not here
// Create new LinearLayout
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setBackgroundColor(0xff99ccff);
// Add textviews
TextView textView1 = new TextView(this);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
textView1.setText("programmatically created TextView1");
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView1.setPadding(20, 20, 20, 20); // in pixels (left, top, right, bottom)
linearLayout.addView(textView1);
TextView textView2 = new TextView(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
textView2.setLayoutParams(layoutParams);
textView2.setText("programmatically created TextView2");
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
linearLayout.addView(textView2);
// Set context view
setContentView(linearLayout);
}
Method 3: Programmatically add one xml layout to another xml layout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_linearlayout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dynamic_linearlayout_item, null);
FrameLayout container = (FrameLayout) findViewById(R.id.flContainer);
container.addView(view);
}
Here is dynamic_linearlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/flContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
And here is the dynamic_linearlayout_item.xml to add:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff99ccff"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff66ff66"
android:padding="20px"
android:text="programmatically created TextView1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffdbdb"
android:layout_gravity="right"
android:layout_margin="10px"
android:textSize="18sp"
android:text="programmatically created TextView2" />
</LinearLayout>
I customized more #Suragch code. My output looks
I wrote a method to stop code redundancy.
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}
It can be called like
createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20);
Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.
RelativeLayout primary_layout = new RelativeLayout(this);
LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
primary_layout.setLayoutParams(layoutParam);
// FOR LINEAR LAYOUT SET ORIENTATION
// primary_layout.setOrientation(LinearLayout.HORIZONTAL);
// FOR BACKGROUND COLOR
primary_layout.setBackgroundColor(0xff99ccff);
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
20, 10, 20));
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20));
TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
rowTextView.setText(text);
layout.addView(rowTextView);
This is how I'm using this:
private List<Tag> tags = new ArrayList<>();
if(tags.isEmpty()){
Gson gson = new Gson();
Type listType = new TypeToken<List<Tag>>() {
}.getType();
tags = gson.fromJson(tour.getTagsJSONArray(), listType);
}
if (flowLayout != null) {
if(!tags.isEmpty()) {
Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
flowLayout.removeAllViews();
for (Tag tag : tags) {
FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
rowTextView.setText(tag.getLabel());
rowTextView.setLayoutParams(lparams);
flowLayout.addView(rowTextView);
}
}
Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
}
And this is my custom TextView named tag:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textAllCaps="true"
fontPath="#string/font_light"
android:background="#drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">
this is my tag_shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>
efect:
In other place I'm adding textviews with language names from dialog with listview:
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/layoutTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>
class file:
setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());
textView.setText("testDynamic textView");
layoutTest.addView(textView);
If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.
It Should be like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>