Dynamic TextView in Relative layout

前端 未结 3 1840
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 11:34

I am triying to use dynamic layout for comment part of my project but when i settext of textview dynamicly the output only appears in top of the screen. And it puts the outp

3条回答
  •  佛祖请我去吃肉
    2020-12-06 11:59

    You should use LinearLayout to automatically add one TextView after another.


    Assuming you can't live without RelativeLayout, you'll need to dynamically generate ids for all TextView you create in order to put one view under another. Here is example:

    public class HelloWorld extends Activity
    {       
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {       
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity);
    
            RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout);
    
            Random rnd = new Random();
            int prevTextViewId = 0;     
            for(int i = 0; i < 10; i++)
            {                       
                final TextView textView = new TextView(this);
                textView.setText("Text "+i);     
                textView.setTextColor(rnd.nextInt() | 0xff000000);            
    
                int curTextViewId = prevTextViewId + 1;
                textView.setId(curTextViewId);
                final RelativeLayout.LayoutParams params = 
                    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 
                                                    RelativeLayout.LayoutParams.WRAP_CONTENT);
    
                params.addRule(RelativeLayout.BELOW, prevTextViewId);
                textView.setLayoutParams(params);
    
                prevTextViewId = curTextViewId;
                layout.addView(textView, params);
            }              
        }    
    }
    

    enter image description here

提交回复
热议问题