3

我試圖誇大LinearLayout在我的屏幕上構建自定義部分。setText()不適用於虛擬佈局

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

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

回答

6

使用此從佈局獲取TextView。

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

呼叫findViewById(R.id.tvCsAddLink)您充氣LinearLayoutrowLink,現在您正在當前活動中搜索它。

4

你誇大你的linearLayoutrowLink你的XML,並嘗試找到你Activity(usualy main.xml),所以你需要找到你的textView上佈局rowLink這樣的佈局TextView

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