Add TextViews programmatically to a XML Layout - android

This is a XML LinearLayout linlayout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mylinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
I want to add TextViews to this layout programmatically because the number of TextViews to be added can be different sometimes.
Here is the activity code:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.linlayout);
LinearLayout linear=(LinearLayout) findViewById(R.layout.mylinear);
TextView [] txt =new TextView[3];
for(int i=0;i<txt.length;i++)
{
txt[i]=new TextView(this);
txt[i].setText("text "+i);
txt[i].setLayoutParams(new
LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
linear.addView(txt[i]);
}
}
The LogCat don't display errors but the TextViews are not displayed when I run the app.
I try to put the line:
setContentView(R.layout.linlayout);
at the end, after the for, but doesn't work.

Use this :
TextView [] txt = new TextView[3];
for (int i=0; i<txt.length; i++) {
txt[i] = new TextView(YourActivity.this);
txt[i].setText("text " + i);
txt[i].setLayoutParams(newLayoutParams
(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
linear.addView(txt[i]);
}

It would be best to use a ListView. By the way did you change the orientation of your layout to a vertical orientation ? But if it necessary for you i suggesst this :
i suppose you have an element with a certain size.
final int size = 3; // replace with the size of your element
LinearLayout linear = (LinearLayout) findViewById(R.layout.mylinear);
for(int i=0;i<size;i++){
final TextView textView = new TextView(this);
textView.setText("text "+i);
textView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linear.addView(textView);
}

Related

Creating TextView by for loop, only the first created working

I am trying to create a brunch of TextView and show them on the screen by a for loop.
But only the first TextView shows the value "123" assigned.
There are still many TextView created but only the first one shows value.
I think I missed something, but do you have idea that what I had missed?
Thanks.
onCreate():
LinearLayout busStopLinearLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
// skipped
busStopLinearLayout = (LinearLayout) findViewById(R.id.bus_stop_linear_layout);
// skipped
}
The for loop I am asking for:
for (int i = 0; i < closestStop.size(); i++) {
TextView dummyTxt = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
dummyTxt.setLayoutParams(params);
dummyTxt.setText("123");
busStopLinearLayout.addView(dummyTxt);
busStopTextArray.add(dummyTxt);
}
activity.xml
<LinearLayout
android:id="#+id/bus_stop_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
Try This out
LinearLayout busStopLinearLayout = (LinearLayout) findViewById(R.id.busStopLinearLayout);
for(int i=0; i<closestStop.size(); i++){
TextView text = new TextView(this);
text.setText("123");
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
busStopLinearLayout.addView(text);
}

get TextView and EditText from Programatically created

i create 1 LinearLayout inside LinearLayout, that contains 1 EditText and 1 TextView programmatically and i need to get text from EditText and TextView. And this is my code:
main.xml:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp" >
<LinearLayout
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:gravity="right"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
MainActivity.java:
linearLayout = (LinearLayout) view.findViewById(R.id.result);
.......
public void addItem(){
LinearLayout childLayout = new LinearLayout(context);
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
childLayout.setLayoutParams(linearParams);
childLayout.setTag(item_name);
childLayout.setOrientation(LinearLayout.HORIZONTAL);
TextView item = new TextView(context);
item.setTag(item_name);
item.setText(item_name);
item.setTextSize(16);
item.setGravity(Gravity.LEFT);
LinearLayout.LayoutParams llp1 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp1.setMargins(0, 0, 15, 0);
item.setLayoutParams(llp1);
item.setTextColor(context.getResources().getColor(android.R.color.black));
EditText quantity = new EditText(context);
quantity.setText(nama_barang);
quantity.setTextSize(16);
quantity.setGravity(Gravity.CENTER_HORIZONTAL);
LinearLayout.LayoutParams llp2 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp2.setMargins(10, 0, 15, 0);
quantity.setLayoutParams(llp2);
quantity.setTextColor(context.getResources().getColor(android.R.color.black));
childLayout.addView(item);
childLayout.addView(quantity);
linearLayout.addView(childLayout);
}
Help me, please.
I've edit my question
Actually, my case above happened when i clicked addItem(), my app will display new TextView and EditText, so if this process is finished, and move to the next Fragment to display all the text of TextViews and EditTexts like this using StringBuilder:
Items Qtt
Cola......1
Chicken...1
Meat......2
Help me.
Do you want to get like this?
String str = item.getText().toString();
String str2 = quantity.getText().toString();
As stated above, using item.getText().toString(); is all you need, nonetheless I do presume your problem lies in the fact that you are declaring your Views inside the loop, by doing it locally later anywhere on the code you won't be getting any text at all.
Try declaring your Views as global variables or doing it outside of the loop such as;
//....
TextView item;
EditText quantity;
for(int i = 0; i < cartCount; i++) {
LinearLayout childLayout = new LinearLayout(context);
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
childLayout.setLayoutParams(linearParams);
childLayout.setTag(item_name);
childLayout.setOrientation(LinearLayout.HORIZONTAL);
item = new TextView(context);
item.setTag(item_name);
item.setText(item_name);
item.setTextSize(16);
item.setGravity(Gravity.LEFT);
LinearLayout.LayoutParams llp1 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp1.setMargins(0, 0, 15, 0);
item.setLayoutParams(llp1);
item.setTextColor(context.getResources().getColor(android.R.color.black));
quantity = new EditText(context);
quantity.setText(nama_barang);
quantity.setTextSize(16);
quantity.setGravity(Gravity.CENTER_HORIZONTAL);
LinearLayout.LayoutParams llp2 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp2.setMargins(10, 0, 15, 0);
quantity.setLayoutParams(llp2);
quantity.setTextColor(context.getResources().getColor(android.R.color.black));
childLayout.addView(item);
childLayout.addView(quantity);
linearLayout.addView(childLayout);
}
On the other hand, by looking at your code, are you trying to create a list of EditText and TextViews? If so, it would be wise to consider using a ListView with custom items; Here you can find a nice tutorial doing something simmilar.
This feels like you should be looking at an adapter view such as a recyclerview. You might start to see some performance issues using a linearlayout.
Anyway. You could add the views to an list as you add them to the linearlayout.
List<TextView> items = new LinkedList<>();
List<EditText> quantities = new LinkedList<>();
for(int i = 0; i < cartCount; i++) {
...
childLayout.addView(item);
childLayout.addView(quantity);
items.add(item);
quantities.add(quantity);
linearLayout.addView(childLayout);
}
then loop through your views
for (TextView textView : items) {
}
for (EditText editText : quantities) {
}
item.getText().toString()
quantity.getText().toString()

How can I set Imageview and Textview on same line in LinearLayout

I want to set Imageview and Textview on same line in LinearLayout but the Imageview is always higher than the Textview.
Here is my code:
String b[] = cacBuocThucHien.split("#");
for (int j = 0; j < b.length; j++) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(30,30);
lp.setMargins(50, 0, 0, 0);
ImageView img = new ImageView(RecipesDetailActivity.this);
TextView tv = new TextView(RecipesDetailActivity.this);
img.setLayoutParams(lp2);
img.setImageResource(R.mipmap.testic);
tv.setLayoutParams(lp);
tv.setText(b[j] + "\n");
layoutHuongDan.addView(img);
layoutHuongDan.addView(tv);
}
This You can use to put image in one line.. and it will work in all kind of layouts. Hope this will help you
<LinerLayout>
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
....... // Put how many TextViews you want
<TextView
android:id="#+id/textn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinerLayout>
You can set visibility gone initially if you wanna show these textviews only after setting text.
Now in your activity make an array of ids of textviews like this...
public static int[] textRows = {R.id.text1, R.id.text2, ........ R.id.textn};
then use for loop for initializing them and setting text and images like this
TextView[] allTexts = new TextView[n];
for (int i = 0; i < n; i++) {
allTexts[i] = (TextView) findViewById(textRows[i]);
allTexts[i].setText("your text");
allTexts[i].setCompoundDrawables(left_image, null, null, null);
}
It will work. Try it out
set textview drawable left no need of extra imageview
android:drawableLeft="#drawable/img"
If you only want to show an icon beside that TextView, in my opinion you should consider using drawable icon feature of TextView
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
But if you would insist to using two views beside each other, using layout gravity would be useful in such circumstances.
lp.gravity= Gravity.CENTER_VERTICAL;
If you want to display only TextView and ImageView.. go for setting CompounDrawable in TextView itself..
But, for having two views side-by-side in LinearLayout programmatically try setting the orientation=horizontal, check out this link.

issue with clear content in RelativeLayout

I am facing one issue for updating TextView content in RelativeLayout. When I update in the second time, I need to clear the previous text from RelativeLayout.
I have one RelativeLayout in my app activity_calendar.xml
<RelativeLayout
android:id="#+id/rel_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/linearLayout1"
android:layout_toRightOf="#+id/linearLayout1">
</RelativeLayout>
This is the Main Code :
public void listall () {
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rel_container);
int prevTextViewId = 0;
for (int i = 0; i < titleCalendar.length; i++) {
final TextView textView = new TextView(this);
textView.setText(titleCalendar[i]);
cnvrttime = hourCalendar[i] - 3;
addcnvrtTime = 60*cnvrttime;
curTextViewId = prevTextViewId + 1;
textView.setId(curTextViewId);
final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, addcnvrtTime);
params.setMargins(0, convertDPtoInt((float)addcnvrtTime), 0, 0);
textView.setLayoutParams(params);
prevTextViewId = curTextViewId;
relativeLayout.addView(textView, params);
}
You need to give the TextView an id so you can find it later:
textView.setId(1234);
Then later:
TextView textView = findViewById(1234);
textView.setText("New Text");
If there aren't any child Views inside the relative layout that you want to keep, call relativeLayout.removeAllViews() before your for loop. Otherwise, use removeView(View) or removeViewAt(int) to remove the ones you don't want.

Adding array of textviews dynamically to linear layout

I tried to add an array of textviews which i defined as a public variable, but when i run the application, it force closes as soon as it gets into for loop. This is the code:
LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
pairs=new TextView[num_match+1];
for(int l=1;l<=num_match;l++)
{
pairs[l].setTextSize(15);
pairs[l].setLayoutParams(lp);
pairs[l].setId(l);
pairs[l].setText(m1[l]+" - "+m2[l]);
myLayout.addView(pairs[l]);
}
You need to create new TextViews to put into the TextView array and you are skipping the first index (pairs[0]) which will lead to trouble later:
pairs=new TextView[num_match];
for(int l=0; l<num_match; l++)
{
pairs[l] = new TextView(this);
pairs[l].setTextSize(15);
pairs[l].setLayoutParams(lp);
pairs[l].setId(l);
pairs[l].setText(m1[l + 1]+" - "+m2[l + 1]);
myLayout.addView(pairs[l]);
}
From your comments, I included this simple working example to help you:
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView[] pairs=new TextView[4];
for(int l=0; l<4; l++)
{
pairs[l] = new TextView(this);
pairs[l].setTextSize(15);
pairs[l].setLayoutParams(lp);
pairs[l].setId(l);
pairs[l].setText((l + 1) + ": something");
myLayout.addView(pairs[l]);
}
}
}
With the layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
I think you need to initailize pairs[l] before using it, like this:
for(int l=1;l<=num_match;l++)
{
pairs[l] = new TextView();
//...
}
Otherwise it will have NullPointerException, and collapse as described.
Why have an array of TextViews? Can you replace it with ListView?
I think that would be a better way. Try this.

Categories

Resources