Skip to content Skip to sidebar Skip to footer

Change Textview Inside Fragment

I followed this guy's tutorial on how to make an ActionBar. Let's say I want to change the TextView inside one of the fragments. So I added this on my StartActivity.java, under onC

Solution 1:

If you want change your component, I suggest you to make a method inside the fragment like this:

import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;

    publicclassDetailFragmentextendsFragment {

        @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            Viewview= inflater.inflate(R.layout.details, container, false);
            return view;
        }


        publicvoidsetText(String text){
            TextViewtextView= (TextView) getView().findViewById(R.id.detailsText);
            textView.setText(text);
        }

    }

Solution 2:

Could you try to replace getView() with getActivity()?

publicvoidsetText(String text){
        TextView textView = (TextView) getActivity().findViewById(R.id.detailsText);
        textView.setText(text);
    }

Solution 3:

I found an answer here, and on Stack overflow

It uses the inflater: (for me it worked)

publicclassMyFragmentextendsFragment {

    @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Viewinf= inflater.inflate(R.layout.fragment_place, container, false);
        TextViewtv= (TextView) inf.findViewById(R.id.textview);
        tv.setText("New text");
        return inf;
    }
}

Solution 4:

in your main activity, instantiate your fragment class like this

publicclassMainActivityextendsAppCompatActivity {
          private YourFragmentClass your_fragment;

          @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_main);

              your_fragment = newYourFragmentClass("pass the string value here")
    }
}

in your fragment class, you can then get the string and setText with it like this

publicclassYourFragmentclassextendsFragment {

     private String your_text;


      publicYourFragmentClass(String your_text) {
       this.your_text = your_text;
      }


      @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        // Inflate the layout for this fragmentViewview= (View)inflater.inflate(R.layout.fragment_layout, container, false);

       //set the text of your text viewTextViewtextView= (TextView) view.findViewById(R.id.text_view_id);
        textView.setText(your_text);
    }
}

Post a Comment for "Change Textview Inside Fragment"