How to add multiple textviews to relativelayout dynamically

时间:2018-02-03 09:28:19

标签: android android-layout

I want to add multiple textviews to relativelayout dynamically, for example, when i click a button, a new textview should be added to layout, also i want to change font size, style of these textviews individually, how i can achieve that.thanx

2 个答案:

答案 0 :(得分:0)

Create your styles for the textView and add the params dynamically like below

On Button Click

TextView textView = new TextView(this);
textView.setText("Test");
RelativeLayout.LayoutParams layoutParams =
      new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textView.setLayoutParams(layoutParams);
relativeLayout.addView(textView);

答案 1 :(得分:0)

first of all, you have to declare relative layout in XML file like below:

    <RelativeLayout 
            android:id="@+id/rlMain"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
    </RelativeLayout>

After that put this code in java file :

RelativeLayout m_rl = (RelativeLayout)findViewById(R.id.rlMain);
final Button addTextViewButton= (Button)findViewById(R.id.addTextViewButton);

LinearLayout LL_Outer = new LinearLayout(this);;
LL_Outer.setOrientation(LinearLayout.VERTICAL); // set orientation
LL_Outer.setBackgroundColor(color.white); // set background
// set Layout_Width and Layout_Height
LinearLayout.LayoutParams layoutForOuter = new 
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
LinearLayout.LayoutParams.MATCH_PARENT);
LL_Outer.setLayoutParams(layoutForOuter);

addTextViewButton.setOnClickListener(new Button.OnClickListener(){
    public void onClick(View v){
        TextView text = new TextView(this);
        text.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        text.setText("");

        Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
        text.setTypeface(typeFace);
        text.setTextSize(50);
        LL_Outer.addView(text);

    }
});
   m_rl.addView(text);