android's websiteのアンドロイドトレーニングに従っています。私は断片的なところで固まっている。問題は、断片化したテキストビューへの参照を取得できないことです。getActivity()。フラグメントがビルドを完了してもfindViewById(int id)がnullを返します
TextView view = (TextView) getActivity().findViewById(R.id.article_s);
1つのアクティビティに2つのフラグメントがあります。 1つはプレーンな単純なListFragment
であり、もう1つはプレーンな単純なTextView
です。ここにフラグメントとアクティビティのレイアウトXMLファイルがあります。
ArticleFragment:
<!-- This is fragment_article.xml -->
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some Text"
android:textSize="18sp"
android:id="@+id/article_s"/>
MainActivity(すべてのフラグメントへの私のコンテナ)
<!-- This is activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_height="match_parent"
android:name="com.example.bora.fragmentsmyway.HeadlinesFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp" />
<fragment
android:layout_height="match_parent"
android:name="com.example.bora.fragmentsmyway.ArticleFragment"
android:layout_weight="2"
android:id="@+id/article_fragment"
android:layout_width="0dp" />
</LinearLayout>
自体ののTextViewの内容を更新するために、文字列を受け取り、私のArticleFragment
の公共の方法があります:
public void updateView(String article) {
TextView view = (TextView) getActivity().findViewById(R.id.article_s);
try{
view.setText(article);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
すべてのビューが作成された後、私は私のMainActivityのupdateView
メソッド。しかし、記事TextViewを見つけようとするとNullPointerException
が出ます。 TextViewのリソースIDを変更してクリーニングを試みました。
しかし、私はこの問題の解決策を見つけました。私はなぜ知らないが、私はfragment_article.xml
にLinearLayout
でTextView
を包むときに動作するようです:
<LinearLayout
xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some Text"
android:textSize="18sp"
android:id="@+id/article_s" />
</LinearLayout>
しかし、私はこの疑問に思って:どのように、チュートリアルのサンプルでは、コードの作業上のとできませんの私が書いたときに働く?私はすべてのコードを手紙でチェックしましたが、私のアリの違いはありません。それはバージョンのためですか?
私はmarshmallowであるAPI 23を使用しています。
R.id.articleからR.id.article_sに変更する –
**私は理由はわかりませんが、Text_Viewをfragment_article.xml **内のLinearLayoutでラップすると動作するようです。コードを見せてくれますか? – Raghunandan
@Raghunandan私は追加しました。 – Bora