Set textView text from a Fragment won't work [

2019-01-27 11:00发布

问题:

Using the 'if first run' statement to set some text from inside a fragment, the setText() method doesn't set any text and I can't work out why.

    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:

You are inflating your view twice instead of returning the one you did the work on to set the text correctly.

Replace

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

With

return view;