Adding content to a linear layout dynamically?
In your onCreate()
, write the following
LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);
view1
, view2
and view3
are your TextView
s. They're easily created programmatically.
How to dynamically add LinearLayout on Android?
LinearLayout lLayout = new LinearLayout(context);
parentWidget.addView(lLayout);
How to add view in a linear layout dynamically
First, you have to get familiar with java (in my opinion).
1) declare a linear layout at XML layout. like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/AdvancedCatalogContainer"
>
</LinearLayout>
2) Get a referance to that view:
private LinearLayout rootView=findViewById(R.id.AdvancedCatalogContainer);
3) Declare a method like this:
public void fillLayout(LinearLayout root,TextView v){
v.setText("your text")
root.addView(v);
}
4) Call this method in your onCreate method or anywhere in ui thread.
... extends AsycTask<blah,blah,blah>{
onPostExecute(blah){
for(many times){
fillLayout(linearLayout,textView);
}
}
Edit
If you want to show a collection of data like a scrolling list please consider using ListView or RecycleView instead.
Dynamically adding a View to a LinearLayout with height of wrap_content doesn't display anything
You need to provide measurements of ImageCanvas with an onMeasure()
override:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(icon.getWidth(),icon.getHeight());
}
See Custom View Components.
When you explicitly supply a height, that height is set in the custom component. With wrap content, the height gets set to zero since it is neither specified nor explicitly measured. The above code will provide the correct measurements.
(icon.getHeight()
is what you really need and corresponds to wrap_content
. You may need a different value for icon.getWidth()
depending upon your design.)
Not sure why a NestedScrollView has any effect, but the code above will help.
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)
adding the views dynamically with layout weight property in Android
Problem is with your layout params. You need to use like below
private void addLayout(String textView1Text, String textView2Text, String checkBoxText) {
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
mLinearLayout.setLayoutParams(param);
TextView tv1 = new TextView(this);
tv1.setText(textView1Text);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);
lp.weight = 0.1f;
tv1.setLayoutParams(lp);
mLinearLayout.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(textView2Text);
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(0, 100);
lp1.weight = 0.6f;
tv2.setLayoutParams(lp1);
mLinearLayout.addView(tv2);
CheckBox cb = new CheckBox(this);
cb.setText(textView2Text);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(0, 100);
lp2.weight = 0.3f;
cb.setLayoutParams(lp2);
mLinearLayout.addView(cb);
}
Need to add layout dynamically
Use the LayoutInflater
to create a view based on your layout template, and then inject it into the view where you need it.
public static NavigableMap<Integer, String> navigableMap = new TreeMap<Integer, String>();
public static int count = 0; // to count no of views added
public static void add_new(final Activity activity)
{
final LinearLayout linearLayoutForm = (LinearLayout) activity.findViewById(R.id.formLayout);
final LinearLayout newView = (LinearLayout) activity.getLayoutInflater().inflate(R.layout.view_to_add, null);
newView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
final EditText edit_new = (EditText) newView.findViewById(R.id.fieldAttr2);
edit_new.setId(id++); // It will assign a different id to edittext each time while adding new view.
Log.i("actv id",edit_new.getId()+""); // You can check the id assigned to it here.
// use a Hashmap or navigable map (helpful if want to navigate through map)
// to store the values inserted in edittext along with its ids.
edit_new.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
navigableMap.put(edit_new.getId(), edit_new.getText().toString());
Log.i("navigablemap", navigableMap.toString());
}
});
// you can get values directly through map by referencing its ids.
// OR
EditText actv_uc = (EditText) linearLayoutForm.findViewById(navigableMap.lastKey());
// Provide the id of edittext you want to access
actv_uc.getText(); // to get value of EditText
actv_uc.setText("");
linearLayoutForm.addView(newView);
count++;
}
Call this function whenever you want to add new view. If you are calling this in Activity, then there is no need to pass Activity object as parameter. but if you are using this in fragment, then need to pass a Parent Activity object to function.
Very easy and helpful tutorial for adding views dynamically :-
http://android-er.blogspot.in/2013/05/add-and-remove-view-dynamically.html
Hope this will help you. Thank you
getting text from dynamically added edit text in linear layout
You can do it like this:
First of All in your class you add a field:
...
EditText myEditText;
...
Then after adding your linearLayout you store your editText in the field like this:
...
final LinearLayout newView = (LinearLayout)getLayoutInflater().inflate(R.layout.single_skill_row, null);
myEditText = newView.findViewById(R.id.editDescricao);
...
After that in the onClick callback of your button you can get it's text like this:
register_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = myEditText.getText().toString();
});
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
Related Topics
Error 12501 Authenticating with Google Sign-In
Android Recyclerview Findviewholderforadapterposition Returns Null
How to Access a File from Asset/Raw Directory
What Do I Do About: This Requires Android.Permission.Interact_Across_Users_Full
How to Kill Sub Activities and Bring Activity to Top of Stack
Scan Android Sd Card for New Files
Android Studio: Gradle: Error: Cannot Find Symbol Variable
Android Sms Receiver Not Working
Find Current Location Latitude and Longitude in Android
What Is Setcontentview(R.Layout.Main)
How to Implement My Own Disk Cache with Picasso Library - Android
Java.Lang.Noclassdeffounderror: Com.Google.Android.Gms.Internal.Zzmp
Android Custom View Group Delegate Addview
Initiate a Phone Call on Android with Special Character #
Adb Got Two Same Serial Numbers When Connected to Two Smart Phones
Get File Path of Image on Android
Highlight Listview Selected Row
Handlers, Messagequeue, Looper, Do They All Run on the UI Thread