gpt4 book ai didi

Android:无法在 fragment 中设置 TextView 值

转载 作者:行者123 更新时间:2023-11-30 02:27:18 25 4
gpt4 key购买 nike

所以我今天开始使用 fragment ,我试图在 fragment 打开时设置 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 而无需做所有声明等。我在 ShortcutFunc 函数的 tv.setText(text) 上得到 NullPointerException。

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

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

怎么了?

最佳答案

这些 TextView 是您的 Fragment 的成员,而不是持有 FragmentActivity 的成员。您应该从您在OnCreateView() 方法

中为您的 fragment 膨胀的 View 初始化它们
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;
}

关于Android:无法在 fragment 中设置 TextView 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27769959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com