从Fragment中设置textView文本不起作用

时间:2016-02-07 16:50:50

标签: java android android-fragments

使用'如果是第一次运行'语句从片段内部设置一些文本, setText()方法没有设置任何文本,我无法解决原因。

    public class TabFragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
        Profile profile = Profile.getCurrentProfile();
        final String id = profile.getId();
        final String userName = profile.getName();
        final String firstName = profile.getFirstName();


        SharedPreferences prefs = this.getActivity().getSharedPreferences("com.george.coffeeconversation", Context.MODE_PRIVATE);
        TextView startTextView = (TextView)view.findViewById(R.id.start_text);
        if (prefs.getBoolean("firstrun", true)) {
            startTextView.setText(getResources().getString(R.string.lets_start));
            prefs.edit().putBoolean("firstrun", false).apply();
        }
        else{
            startTextView.setText(getResources().getString(R.string.welcome)+ " " + firstName);
        }

        return inflater.inflate(R.layout.tab_fragment_1, container, false);
    }
}

1 个答案:

答案 0 :(得分:0)

您要对视图进行两次充气,而不是返回您完成工作的视图以正确设置文本。

替换

return inflater.inflate(R.layout.tab_fragment_1, container, false);

使用

return view;
相关问题