因此,我今天开始使用片段,并且尝试在片段打开时设置TextView值。值可以更改,因此我将其全部打包到1个函数中,以便可以调用它来更新数据。
这里:
public void loadDetails(){
ShortcutFunc sf = new ShortcutFunc(this.getActivity());
ConversePrefs cp = new ConversePrefs(this.getActivity());
sf.setTextValue(getActivity(), R.id.profile_name, cp.GetStringSetting("name", "unset") + " " + cp.GetStringSetting("surname", "unset"));
String dob = cp.GetStringSetting("dob", "unset");
String bod[] = dob.split("\\-");
LocalDate birthdate = new LocalDate (Integer.valueOf(bod[2]), Integer.valueOf(bod[1]), Integer.valueOf(bod[0]));
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
sf.setTextValue(getActivity(), R.id.profile_bd, dob + " (" + String.valueOf(age) + ")");
sf.setTextValue(this.getActivity(), R.id.profile_country, cp.GetStringSetting("country", "unset").toString());
sf.setTextValue(this.getActivity(), R.id.profile_email, cp.GetStringSetting("email", "unset").toString());
String joined[] = cp.GetStringSetting("join", "unset").split("\\s+");
String joinedArray[] = joined[0].split("\\-");
LocalDate joindate = new LocalDate(Integer.valueOf(joinedArray[0]), Integer.valueOf(joinedArray[1]), Integer.valueOf(joinedArray[2]));
LocalDate today = new LocalDate();
//Years joinedThen = Years.yearsBetween(joindate, today);
Days joinedThen = Days.daysBetween(joindate, today);
sf.setTextValue(this.getActivity(), R.id.profile_join, joined[0] + " (" + joinedThen.toString() + " Days)");
sf.setTextValue(this.getActivity(), R.id.profile_user, cp.GetStringSetting("username", "unset").toString());
}
ShortcutFunc包含以下功能:
public void setTextValue(Activity act, int id, String text){
TextView tv = (TextView)act.findViewById(id);
tv.setText(text);
}
我用它来节省时间并设置TextViews而不进行所有声明等。
我在tv.setText(text)ShortcutFunc函数上得到NullPointerException。
这就是我所谓的loadDetails():
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadDetails();
}
那怎么了
最佳答案
这些TextView是您的Fragment
的成员,而不是保存Activity
的Fragment
的成员。您应该从OnCreateView()
方法中为片段夸大的视图初始化它们
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.my_view, container, false);
textView = (TextView) view.findViewById(R.id.my_text_view);
return view;
}