How to add a TextView to a LinearLayout dynamically in Android?
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
Dynamically add textViews to a linearLayout
Something like the following should be what you need:
final int N = 10; // total number of textviews to add
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
myTextViews[i] = rowTextView;
}
Adding TextViews inside horizontal LinearLayout dynamically
The interestWidth and parentWidth are initially 0 because they have not been laid out when getWidth is called.
get width for dynamically created textViews
The above link helped me getting width of dynamically created textViews from interestList.
And by using ViewTreeObserver on interestLinearLayout I was able to get the width of LinearLayout after it was laid out.
Finally, the above code should be modified as below to add textViews from JAVA inside a LinearLayout.
final LinearLayout interestLinearLayout = findViewById(R.id.interests);
interestLinearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
interestLinearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
String interestList[]={"Travel","Music","Photography","Sports","Dance","Animals","SciFi Movies"};
int interestWidth =0;
int parentWidth = interestLinearLayout.getWidth(); // got width inside view tree observer for linearlayout
for(String interest: interestList) {
TextView textView = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(2,0,10,2);
textView.setLayoutParams(params);
textView.setPadding(2, 2, 2, 2);
textView.setText(interest);
textView.setIncludeFontPadding(true);
textView.measure(0,0); //using approach mentioned in link to get width of text views
interestWidth += textView.getMeasuredWidth();
if(interestWidth<parentWidth)
interestLinearLayout.addView(textView);
else
break;
}
}
});
Horizontally Add TextViews to Equally Weighted Linear Layout Dynamically
Remove in your LinearLayout android:weightSum="1"
and define this LinearLayout.LayoutParams
:
val linearLayout : LinearLayout = findViewById(R.id.layout)
val lp = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT)
lp.weight = 1f
Then just apply to the views added in the layout:
val textView : TextView = TextView(context)
textView.setText("Text1")
textView.height = ...
//...
val textView2 : TextView = TextView(context)
textView2.setText("Text2")
textView2.height = ...
//....
linearLayout.addView(textView, lp)
linearLayout.addView(textView2, lp)
To add textview dynamic at run time Android
You could create a TextView dynamically like this for example:
//create a TextView with Layout parameters according to your needs
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//if your parent Layout is relativeLayout, just change the word LinearLayout with RelativeLayout
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
//get the parent layout for your new TextView and add the new TextView to it
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example);
linearLayout.addView(tv);
And in the tv.setText(...);
line you could set the text, that your got from your database.
Dynamically Creating Multiple TextViews in LinearLayout
It's giving NPE because you are not setting your activity layout properly.
Do this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.whereLinearLayoutMasterIs); // Add your layout here
root=(LinearLayout)findViewById(R.id.master);
t=new TextView[10];
LinearLayout.LayoutParams dim=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for(int i=0;i<10;i++)
{
t[i]=new TextView(this);
t[i].setLayoutParams(dim);
t[i].setText("YOHOHO: "+i);
root.addView(t[i]);
}
}
NOTER.layout.whereLinearLayoutMasterIs
is indicative, use your layout in which R.id.master
is
Adding multiple textviews dynamically in linear layout
use flexbox layout add this dependancy to your project
implementation 'com.google.android:flexbox:0.3.2'
and add the layout to your xml
<com.google.android.flexbox.FlexboxLayout
android:id="@+id/tagsView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="stretch"
app:alignContent="stretch"/>
and in your java class
private void setUpTags() {
tagsCount = //... integer number of textviews
private TextView[] tags= new TextView[tagsCount];//create dynamic textviewsarray
LinearLayout.LayoutParams layoutParams = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//loop to customize the text view and add it to flex box
for (int i = 0; i < tagsCount; i++) {
tags[i] = new TextView(getContext());
GradientDrawable gD = new GradientDrawable();
int strokeWidth = 5;
int strokeColor = getResources().getColor(R.color.strokColor);
gD.setStroke(strokeWidth, strokeColor);
gD.setCornerRadius(15);
gD.setShape(GradientDrawable.RECTANGLE);
tags[i].setBackground(gD);
tags[i].setText("this is tag text");
layoutParams.setMargins(10, 5, 10, 5);
tags[i].setPadding(17, 15, 17, 15);
tagsView.addView(tags[i], layoutParams);
}
}
Adding multiple TextViews into LinearLayout dynamically
You are adding the same view to the layout again.
Change your function to
public void addNotHiredRoomsToLayout() {
for (String name : Constants.existingRoomNames) {
textView2 = new TextView(this);
boolean contains = false;
for (Room room : mCalendarModel.mList.getRoomList()) {
if (room.getName().equals(name)) {
contains = true;
}
}
if (!contains) {
textView2.setText(name + ": Free");
linearLayout.addView(textView2);
}
}
}
Related Topics
Eclipse Indigo - Cannot Install Android Adt Plugin
Android Spinner with Different Layouts for "Drop Down State" and "Closed State"
How to Populate Android Room Database Table on First Run
Android How to Create Triangle and Rectangle Shape Programmatically
Android - Hide All Shown Toast Messages
Start a Service in a Separate Process Android
Android Listview Get Selected Item
Android Slidingtablayout with Icons
Android: 2 or More Expandablelistview Inside Navigation Drawer
Sms Delivery Report in Android
Firebase Cloud Messaging - How to Validate Tokens
Create SQLite Database in Android
Calling Android Dialog Without It Fading the Background
Error:Execution Failed for Task ':App:Transformclasseswithdexfordebug' in Android Studio
How to Use Bluetooth in Android Emulator
Android Alternate Row Colors in Listview