4

我正在尝试充气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);
4

3 回答 3

8

使用它从布局中获取 TextView。

TextView tvCsAddLink = (TextView)rowLink.findViewById(R.id.tvCsAddLink);                                       
于 2011-11-22T11:59:19.167 回答
5

你已经在你的 XML 上膨胀了linearLayout rowLink ,你试图TextView从你的Activity(通常main.xml)的布局中找到你,所以你需要textView像这样在你的布局 rowLink 上找到你的:

TextView tvCsAddLink = (TextView)rowLink.findViewById(R.id.tvCsAddLink);  
于 2011-11-22T12:04:55.107 回答
4

调用findViewById(R.id.tvCsAddLink)你膨胀的LinearLayoutrowLink,现在你正在当前活动中搜索它。

于 2011-11-22T11:58:43.757 回答