setText()无法处理膨胀的布局

时间:2011-11-22 11:56:20

标签: android android-layout nullpointerexception layout-inflater

我正在尝试通知LinearLayout在屏幕上构建自定义栏目。

String txt = "testing";
LinearLayout rowLink = (LinearLayout)getLayoutInflater().inflate(R.layout.additional_link, null);
TextView tvCsAddLink = (TextView)findViewById(R.id.tvCsAddLink);                                       
tvCsAddLink.setText(txt);

// adding this inflated layout to an existing layout
myLinearLayout.addView(rowLink);

additional_link.xml的内容如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/llCsAddLink"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/white_row"
    android:clickable="true"
    >        
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:src="@drawable/youtube_icon" />        
    <TextView
        android:id="@+id/tvCsAddLink"       
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"        
        android:paddingLeft="10px"
        android:paddingRight="20px"
        android:textSize="16dp"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_gravity="center_vertical" />
</LinearLayout>

我收到了NullPointerException

tvCsAddLink.setText(txt);

3 个答案:

答案 0 :(得分:7)

使用此方法从布局中获取TextView。

TextView tvCsAddLink = (TextView)rowLink.findViewById(R.id.tvCsAddLink);                                       

答案 1 :(得分:4)

您已在linearLayout rowLink上夸大了XML,并尝试从TextView(usualy Activity)的布局中找到main.xml ,所以你需要在布局rowLink上找到textView,如下所示:

TextView tvCsAddLink = (TextView)rowLink.findViewById(R.id.tvCsAddLink);  

答案 2 :(得分:3)

在充气findViewById(R.id.tvCsAddLink) rowLink 上致电LinearLayout,现在您正在当前活动中搜索。

相关问题