GMX GMX - 28 days ago 6
Android Question

How create TextView programatically with this specifics Attributes?

I'm currently creating TextView like that:

LinearLayout myLayout = (LinearLayout) activity.findViewById(R.id.ll1);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

for(int l=0; l<4; l++)
{
pairs[l] = new TextView(context);
pairs[l].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
pairs[l].setLayoutParams(lp);
pairs[l].setId(l);
pairs[l].setText("asd");
myLayout.addView(pairs[l]);
}


Now I want set this attribute to all of this TextView:


  • FontFamily: cursive

  • SetTextSize not sp but dp (RESOLVED)

  • SetGravity: central_horizontal (RESOLVED)



I couldn't find a way for set those attribute when I create a TextView programatically, How can I do that?

Answer

In order to change the font family of a TextView use setTypeface

for instance:

Typeface tf = Typeface.create("cursive", Typeface.NORMAL);
for(int l=0; l<4; l++)
{
    pairs[l] = new TextView(context);
    pairs[l].setTypeface(tf);
    ...
}

Also, this may interest: How to change fontFamily of TextView in Android