我首先尝试了示例here(getActivity)中的提示,但它不起作用
TextView text = (TextView)
getActivity().findViewById(R.nrOfBooksInCollection);//This results in nullpointer exception
text.setText("Text from a fragment");//This results in nullpointer exception
以下代码可以使用neiter。我没有在Eclipse中使用下面的代码得到错误,它只是不改变textview“nrOfBooksInCollection”中的文本。
package com.ahmad.actionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TextView;
public class FragMent2 extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.summary, null);
SimpleBookManager testBook = new SimpleBookManager();
TextView nrOfBooksfield = (TextView) view.findViewById(R.id.nrOfBooksInCollection);
String text = Integer.toString(testBook.count());
nrOfBooksfield.setText(text);//The text doesn't change at all
nrOfBooksfield.setText("text");//Neither does this
return inflater.inflate(R.layout.summary, container, false);
}
}
当我使用Activities时它工作,所以XML文件很好。
答案 0 :(得分:1)
您正在ViewGroup之外夸大您的视图。尝试:
View view = inflater.inflate(R.layout.summary, container, null);
...
return view;