문제

I'm trying to inflate a LinearLayout to build a customized section on my screen.

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);

The content of my additional_link.xml is as follows:

<?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>

I'm getting a NullPointerException on the line:

tvCsAddLink.setText(txt);
도움이 되었습니까?

해결책

Use this to get TextView from layout.

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

다른 팁

you have inflated your XML on your linearLayout rowLink , and you try to find the TextView from the layout of your Activity ( usualy main.xml ) , so you need to find your textView on your layout rowLink like this :

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

Call findViewById(R.id.tvCsAddLink) on your inflated LinearLayoutrowLink, now you are searching it in the current activity.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top