如何在setContentView()布局中引用TextView?

时间:2015-07-22 14:31:20

标签: java android fonts textview layout-inflater

所以我设法获得了一个不在setContentView()布局中的TextView的引用,但我仍然无法设置自定义字体(我再也没有得到NullPointerException了,所以至少那个好) >这是我使用的代码:

dataTable

这是我在上面的LayoutInflater中获得的布局:

LayoutInflater mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View textview= (View) mInflater.inflate(R.layout.item, null);

        TextView myTextView = (TextView) textview.findViewById(R.id.helloText);
        Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/custom_font.ttf");
        myTextView.setTypeface(tf);

如果我将android:textStyle =“bold”添加到上面item.xml中的T​​extView,它可以工作,但是当我尝试使用下面的代码以编程方式将其设置为自定义字体时,我什么也得不到:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_gravity="center"
    android:layout_width="300dp"
    android:layout_height="230dp">

    <TextView
        android:id="@+id/helloText"
        android:textSize="20sp"
        android:textColor="#567dc0"
        android:background="#fbcb43"
        android:gravity="center"
        tools:text="@string/hello_world"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <View
        android:id="@+id/item_swipe_left_indicator"
        android:alpha="0"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_margin="10dp"
        android:background="#A5F" />

    <View
        android:id="@+id/item_swipe_right_indicator"
        android:alpha="0"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_margin="10dp"
        android:layout_gravity="right"
        android:background="#5AF" />

</FrameLayout>

顺便说一句,我没有收到任何错误。

1 个答案:

答案 0 :(得分:0)

您实质上是以编程方式创建一个新的TextView,方法是从xml中扩展它,然后在其上设置自定义字体。您没有看到更改的原因是文本视图不在您的屏幕上。您需要指定textview的添加位置,方法是在inflate方法中设置root,或者以编程方式将其添加到内容布局中的ViewGroup。