Android:无法在片段中设置TextView值

时间:2015-01-04 20:23:23

标签: android android-fragments

所以我今天开始使用片段,我试图在片段打开时设置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(文本)上获得了ShortcutFunc函数的NullPointerException。

这就是我调用loadDetails()的方法:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadDetails();
    }

那有什么不对?

1 个答案:

答案 0 :(得分:1)

这些TextView是您Fragment的成员,而不是持有Activity的{​​{1}}的成员。您应该从Fragment方法

中为您充气的视图中初始化它们
OnCreateView()