view.xml
と呼ばれるを含むとView
呼ばれるレイアウトがありますview_related
。基本的に、私の辞書アプリでは、エントリに関連する単語がある場合、ヘッダー「関連するエントリ」とすべての関連する単語を表す一連のsview_related
を含むに置き換えます。LinearLayout
TextView
のメソッドににをNullPointerException
追加するたびに取得し続けます。コードは非常に単純に見えますが、その理由がわかりません。TextView
LinearLayout
Activity
onCreate()
view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="@+id/view_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12pt"
android:textColor="#fff"
android:textStyle="bold"
android:background="#990011"
android:padding="10dp"
android:text="lalala word"
/>
<ScrollView android:id="@+id/view_description"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/view_header">
<LinearLayout android:id="@+id/view_description_content"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="@string/demo_definition"
/>
<!-- THIS WILL BE REPLACED -->
<View android:id="@+id/view_related"
android:layout_width="match_parent"
android:layout_height="wrap_content"></View>
</LinearLayout>
</ScrollView>
</RelativeLayout>
view_related.xml、view.xmlの要素をLinearLayout
置き換えますView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/view_related_entries"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/view_related_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="#fff"
android:textStyle="bold"
android:textSize="7pt"
android:background="#000"
android:text="Related entries"
/>
<LinearLayout android:id="@+id/view_related_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</LinearLayout>
</LinearLayout>
そして最後に、onCreate
今のところ関連するエントリが「Hello」と「Goodbye:」であると想定しているメソッド。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
LinearLayout ll = (LinearLayout) findViewById(R.id.view_related_list);
TextView tv = new TextView(this);
tv.setText("Hello");
ll.addView(tv); // NULL POINTER EXCEPTION
tv = new TextView(this);
tv.setText("Goodbye");
ll.addView(tv);
LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = findViewById(R.id.view_related);
ViewGroup parent = (ViewGroup) view.getParent();
int index = parent.indexOfChild(view);
parent.removeView(view);
View llview = li.inflate(R.id.view_related_entries, parent, false);
parent.addView(llview, index);
}