在Android中以编程方式设置TextView TextAppeareance [英] Setting TextView TextAppeareance Programmatically in android
问题描述
我将实现一个 LinearLayout
,其中根据数据库表的字段数以编程方式生成输入字段.
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.
不幸的是,当我尝试在 TextView
中将属性 textApperance
设置为 textApperanceLarge
时,它不起作用.下面是我的代码...
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]);
推荐答案
使用如下.会起作用的.
Use like this. It will work.
textView.setTextAppearance(this, android.R.style.TextAppearance_Large);
或者,从API 23开始,您不需要传递上下文.因此,您可以简单地致电:
Or, since API 23, you don't need to pass a context. Hence, you can simply call:
textView.setTextAppearance(android.R.style.TextAppearance_Large);
如果您想同时支持API 23或更高版本以及更低版本,可以使用以下方法简化您的任务.仅当您已经定位到API 23或更高版本时,才使用以下方法.如果您要定位的API小于23,则以下代码将显示错误,因为其中没有新方法.
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 < Build.VERSION_CODES.M) {
super.setTextAppearance(context, resId);
} else {
super.setTextAppearance(resId);
}
}
这篇关于在Android中以编程方式设置TextView TextAppeareance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!