setText () не работает на раздутом макете - PullRequest
3 голосов
/ 22 ноября 2011

Я пытаюсь надуть 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 ]

7 голосов
/ 22 ноября 2011

Используйте это, чтобы получить TextView из макета.

TextView tvCsAddLink = (TextView)rowLink.findViewById(R.id.tvCsAddLink);                                       
4 голосов
/ 22 ноября 2011

вы надули свой XML на свой linearLayout rowLink, и вы пытаетесь найти TextView из макета вашего Activity (обычно main.xml), поэтому вам нужно найти свой textViewна вашем макете rowLink, как это:

TextView tvCsAddLink = (TextView)rowLink.findViewById(R.id.tvCsAddLink);  
3 голосов
/ 22 ноября 2011

Звоните findViewById(R.id.tvCsAddLink) на ваш надутый LinearLayout rowLink , теперь вы ищете его в текущей активности.

...