我想要一個TextView總是說當前的日期。但是,setText方法使用NullPointerExeption崩潰程序...截至目前,日期不是問題 - 我只使用常規文本來測試它。我不知道放置代碼的最佳位置,因此我決定使用onActivityCreated。怎麼回事,還有什麼我可以做的,讓我的代碼更好? *請注意,textview位於fragment_page中,而不是fragment_page 2,因爲這是滑動標籤佈局中的第一個標籤。爲什麼在一個片段中設置textview文本會導致崩潰?
片段類
public class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
if(mPage < 2) {
view = inflater.inflate(R.layout.fragment_page, container, false);
} else {
view = inflater.inflate(R.layout.fragment_page_2, container, false);
}
return view;
}
//@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
/*Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
*/
TextView textView = (TextView) getView().findViewById(R.id.current_date);
textView.setText("sadFace"); //null pointer exeption on this line
}
}
片段XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp" >
<ImageView
android:layout_width="239dp"
android:id="@+id/logo"
android:layout_height="100dp"
android:src="@drawable/logo"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/current_date"
android:text="Today is January 1st, 2015"
android:layout_toRightOf="@id/logo"
android:gravity="center"
android:layout_alignBottom="@id/logo"/>
</RelativeLayout>
</LinearLayout>
謝謝,它爲我工作! – Carl 2016-03-09 06:57:50