从xml定义TextView TypeFace?

时间:2011-05-03 09:57:50

标签: java android fonts typeface

我有一个使用SimpleAdapter的ListView,每行有2个TextViews,我想使用外部字体到两个TextView之一。这是该类的代码:

  public class QuranEnglish extends Activity {
<...>
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.quran_english);

    listview=(ListView) findViewById(R.id.QuranEnglishListView);    
    <..add into list..>
    SimpleAdapter adapter = new SimpleAdapter(
            this,
            list,
            R.layout.quran_english_row,
            new String[] {"Arabic","English"},
            new int[] {R.id.QuranEnglishTextViewArabic,R.id.QuranEnglishTextViewEnglish});

    listview.setAdapter(adapter);

每行的xml(quran_english_row.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:orientation="vertical">
    <LinearLayout android:gravity="right" android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="fill_parent">
        <TextView android:textSize="21px" android:text="TextView" android:id="@+id/QuranEnglishTextViewArabic" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    </LinearLayout>

    <TextView android:textSize="21px" android:text="TextView" android:id="@+id/QuranEnglishTextViewEnglish" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>

</LinearLayout>

布局的xml(quran_english.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:orientation="vertical">
    <ListView android:id="@+id/QuranEnglishListView" android:layout_width="fill_parent" android:layout_height="fill_parent"></ListView>

</LinearLayout>

那么如何将行中的TextView的外部字体(quran_english_row.xml)放入?我尝试使用这条线虽然它崩溃了我的应用程序:

((TextView) findViewById(R.id.QuranEnglishTextViewArabic)).setTypeface(Typeface.createFromAsset(getAssets(),"dejavusans.ttf"));

1 个答案:

答案 0 :(得分:0)

R.id.QuranEnglishTextViewArabic 

不是此处您的观点的ID。它是示例视图的id,用于填充列表。要更改字体,您需要获取列表的一个视图。如果您选择了一个视图,则此方法有效:

TextView view = getSelectedView();
if (view != null) {
  view.setTypeface(Typeface.createFromAsset(getAssets(),"dejavusans.ttf"));
}