2013-04-29 126 views
45

中设置TextView TextAppeareance我要实现一个LinearLayout,其中输入字段是根据数据库表的字段数以编程方式生成的。以编程方式在android

不幸的是,当我试图在TextView中设置属性:textApperancetextApperanceLarge时,它不起作用。以下是我的代码...

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]); 
+0

通过不工作,我假设你的意思是文本只是“正常大小”? – HalR 2013-04-29 03:36:15

+0

默认大小是TextAppearanceSmall ...但我想设置... TextAppearanceLarge。 – 2013-04-29 03:36:51

+0

您正在构建自己的文本外观属性,或者您正在使用android。在你使用android的代码中。 – Unknown 2013-04-29 04:06:04

回答

153

使用方法如下。它会工作。

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

或者,因为API 23,您不需要传递上下文。因此,你可以简单地调用:

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

如果你想支持API 23或更高版本,以及较低的一个,你可以用下面的方法来简化你的任务。仅当您已经定位API 23或更高版本时才使用以下方法。如果您定位的API小于23,则下面的代码会给出错误,因为新方法不可用。

public void setTextAppearance(Context context, int resId) { 
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { 
     super.setTextAppearance(context, resId); 
    } else { 
     super.setTextAppearance(resId); 
    } 
} 
+3

非常感谢!有用 ! 我们什么时候应该使用 android.R.attr.textAppearanceLarge而不是android.R.style.TextAppearance_Large? – 2013-04-29 04:32:44

+0

@RajuGujarati:'android.R.attr.textAppearanceLarge'是一个属性,用于设置当前主题的样式。当您使用自定义主题时,您可以给它任何值。 'android.R.style.TextAppearance_Large'是一种风格,在这种情况下,它恰好是设置为attr的值,用于默认主题。 – njzk2 2014-07-08 20:07:38

+0

此方法在API级别23中已弃用。请在API 23+中使用setTextAppearance(int)。 – Sergii 2015-11-28 12:36:55