Android -Dynamic TextView over previous TextView

171 views Asked by At

I am making an example of dynamic textview, that are created by pressing a button. the format in which they are created is similar to:

1- Textview (fist created)
2- TextView
3- TextView (last created)

I wonder if we can create them in an ascending order, one above the previous TextView. something like this:

3- TextView (last created)
2- TextView
1- TextView (first created)

this is my example code:

 private OnClickListener onClick() {
     return new OnClickListener() {

         @Override
         public void onClick(View v) {
             mLayout.addView(createNewTextView("TextView"));
             count = count +1;
         }
     };
 }

 private TextView createNewTextView(String text) {
     final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
     final TextView textView = new TextView(this);
     textView.setLayoutParams(lparams);
     textView.setText(count+ "- " + text);
     textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
     return textView;
 }}
2

There are 2 answers

0
Gopal Gopi On BEST ANSWER

You can specify the index where TextView has to be added in ViewGroup...

ViewGroup.addView(TextView, 0);

each time you are creating a TextView and adding to mLayout, add with the index 0 which will add on top of previous TextView

mLayout.addView(createNewTextView("TextView"),0);
0
Lalith B On

You could create a LinearLayout and add one below the other, using layout.addView(TextView). I've a psedo code below which explains how it is done.

for(Option option : options){
     view = View.inflate(mContext,R.layout.textView,null);
     ((TextView)view.findViewById(R.id.txt_key)).setText(" SOME TEXT : ");
     ((TextView)view.findViewById(R.id.txt_value)).setText("SOME VALUE ");
     mLlCtr.addView(view);
}