Raju Gujarati Raju Gujarati - 3 months ago 26
Android Question

Setting TextView TextAppeareance Programmatically in android

I am going to implement a

LinearLayout
in which the input fields are programmatically generated according to the number of fields of the database table.

Unfortunately, when I am trying to set the attribute:
textApperance
as
textApperanceLarge
in the
TextView
, it doesn't work. Below is my code...

for (int i = 0; i < selectedProducts; i++) {

premLayout[i] = new LinearLayout(this);
premLayout[i].setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
premLayout[i].setOrientation(LinearLayout.HORIZONTAL);
premLayout[i].setGravity(Gravity.TOP);

premTextView[i] = new TextView(this);
premTextView[i].setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
2.0f));
premTextView[i].setTextAppearance(this, android.R.attr.textAppearanceLarge);

premTextView[i].setText(premiumChannels.get(i));
premTextView[i].setId(i + 600);

int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
premTextView[i].setWidth(px);

premLayout[i].addView(premTextView[i]);

Answer

Use like this. It will work.

textView.setTextAppearance(this, android.R.style.TextAppearance_Large);

Update: Since API 23, you don't need to pass context parameter. Hence, you can simply call:

textView.setTextAppearance(android.R.style.TextAppearance_Large);

If you want to support API 23 or higher as well as lower one, you can use the below method to simplify your task. Use the below method only if you are already targeting API 23 or higher. If you are targeting API is less than 23, the below code will give error as the new method wasn't available in it.

public void setTextAppearance(Context context, int resId) {

    if (Build.VERSION.SDK_INT < 23) {

        super.setTextAppearance(context, resId);

    } else {

        super.setTextAppearance(resId);
    }
}
Comments