32

I cannot find how to change fragment's textview from an Activity. I have 4 files :

MainActivity.java
activity_main.xml
FragmentClass.java
frag_class.xml

frag_class.xml has textView, I want to change the text from MainActivity.java. FragmentClass extends Fragment, this fragment is displayed in MainActivity FragmentClass has:

public void changeText(String text){
 TextView t = (TextView) this.getView().findViewById(R.id.tView);
 t.setText(text);
}

and in MainActivity I tried this:

FragmentClass fc = new FragmentClass();
fc.changeText("some text");

But sadly this code gives me NullPointerException at fc.changeText("some text"); I've also tried changing the text directly from MainActivity with:

 TextView t = (TextView) this.getView().findViewById(R.id.tView);
 t.setText(text);

which Failed.

[EDIT] The full code is here

m-ric
  • 5,621
  • 7
  • 38
  • 51
Cԃաԃ
  • 1,259
  • 1
  • 15
  • 29

5 Answers5

12

You can find the instance of Fragment by using,

For support library,

YourFragment fragment_obj = (YourFragment)getSupportFragmentManager().
                                              findFragmentById(R.id.fragment_id);

else

YourFragment fragment_obj = (YourFragment)getFragmentManager().
                                             findFragmentById(R.id.fragment_id); 

Then create a method in the Fragment that updates your TextView and call that method using fragment_obj like,

fragment_obj.updateTextView();

Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
  • 4
    ClassCastException, I don't have frament tag in my activity_main.xml, I just have LinearLayout with id frag and I use getSupportFragmentManager().beginTransaction().replace(R.id.frag, fr).commit(); for the fragment to appear – Cԃաԃ Apr 30 '13 at 08:25
  • Could that be the cause of ClassCastException? – Cԃաԃ Apr 30 '13 at 08:26
  • yes thats because you are not having fragment in the xml. But as you might be adding the fragment dynamically, hopefully you will be having the instance of Fragment. – Lalit Poptani Apr 30 '13 at 08:46
  • I do have instance of fragment: Fragment fr = MyFragment.newInstance(); and in MyFragment class public static Fragment newInstance(){ MyFragment myFrag = new MyFragment(); return myFrag; } How can i apply your code? – Cԃաԃ Apr 30 '13 at 09:00
  • well just create a public method in your `MyFragment` class with updating the value of TextView and call it from the FragmentActivity using `myFrag.method_name();` – Lalit Poptani Apr 30 '13 at 09:03
  • I know that a lot to ask, but could you please look at full code here: http://pastebin.com/NQBieFLi – Cԃաԃ May 02 '13 at 02:02
  • @Prabuddham is this a proper approach – Akshay Mukadam Sep 07 '14 at 13:38
  • `FragOne frag = (FragOne)getFragmentManager().findFragmentById(R.id.textviewinfragment);`. I get the following error: 'incomaptible type` – Si8 Oct 02 '16 at 18:20
  • `R.id.textview‌​infragment` is id of your Fragment or TextView? – Lalit Poptani Oct 03 '16 at 04:55
12

From activity to Fragment by Fragment Transaction:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
    }
    public static void changeFragmentTextView(String s) {
        Fragment frag = getFragmentManager().findFragmentById(R.id.yourFragment);
        ((TextView) frag.getView().findViewById(R.id.textView)).setText(s);  
    }
}
mmBs
  • 8,421
  • 6
  • 38
  • 46
Daryn
  • 770
  • 9
  • 19
  • 1
    the text is not changing. Sorry, but what would be R.id.yourFragment if I don't have fragment tag? would it be the container in activity_main.xml that holds the fragment, or would that be the id of frag_class.xml's outter layout's id? – Cԃաԃ Apr 30 '13 at 08:41
  • You must create your fragment's own layout, for example, "frag.xml" and edit R.id.yourFragment to R.id.frag. – Daryn Apr 30 '13 at 08:44
  • 1
    The fragment is created dynamically and as I have read on SO it is not possible to give an id to a dynamically created fragment. In my xml files I don't have . I did give tag when I was creating replacing fragment, and changed your code to findFragmentByTag, but it still gives me null pointer exception. Could you please see the full code here http://pastebin.com/NQBieFLi ? – Cԃաԃ May 02 '13 at 01:04
6

@Lalit answer is correct but I see that you dont need to create a function like fragment_obj.updateTextView();. I set all my view as class level objects and was able to update the textview directly.

fragmentRegister.textViewLanguage.setText("hello mister how do you do");

Note: If you need to perform more than one action then having a function is the way to go.

Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
  • 1
    I don't know if it's a good practice either, but that seems like a good alternative :). Once I even used static variables to use them in fragments... That was the easiest way of setting text, it worked for me since i was only getting like 0 to 10 short strings. Anyway, I'm sure your answer will be useful to someone, and since it's working solution here is yours +1; – Cԃաԃ Jun 17 '14 at 04:29
1

I accomplished it other way. I have my app working like this:

After firing my app, I have MainActivity with HomeFragment created. In HomeFragment I have Button and TextView for connecting / showing state of BluetoothConnection.

In HomeFragment I implemented Handler for receiving information from BluetoothService. After receiving message I wanted to update TextView and Button text. I created public interface in HomeFragment with method that is getting String arguments for TextView and Button. In onAttach(Activity a) I created mCallback object for talking to activity.

Next step is implementing this Interface in MainActivity. From this Activity I am updating TextView and Button. Everything looks like this:

HomeFragment.java

public interface ViewInterface{
    public void onViewUpdate(String buttonTxt, String txtTxt);
}

@Override
public void onAttach(Activity a){
    super.onAttach(a);
    try{
        mCallback = (ViewInterface)a;
    }catch (ClassCastException e){
        e.printStackTrace();
    }
}

private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MESSAGE_STATE_CHANGE:

                    if(true) Log.i(CLASS_TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                    switch (msg.arg1) {
                        case BluetoothConnectionService.STATE_CONNECTED:

                            threadTextString = "Connected to: " + connectedDeviceName;
                            threadBtnString = "Disconnect";
                            mCallback.onViewUpdate(threadBtnString, threadTextString);
                            break;
                        case BluetoothConnectionService.STATE_CONNECTING:
                           threadTextString = "Connecting...";
                            mCallback.onViewUpdate(threadBtnString, threadTextString);
                            break;
                         case BluetoothConnectionService.STATE_NONE:

                            threadBtnString = "Connect";
                            threadTextString = "You're not connectedd";
                            mCallback.onViewUpdate(threadBtnString, threadTextString);
                            break;
}

private void updateBtn(Button btn, String data){
    btn.setText(data);
    Log.d(CLASS_TAG + "/" + "updateBtn", "Data: " + data);
}

private void updateTxt(TextView txt, String data){
    txt.setText(data);
    Log.d(CLASS_TAG + "/" + "updateTxt", "Data: " + data);

}

public void update(String buttonTxt, String txtTxt){
    this.updateTxt(connectTxt, txtTxt);
    this.updateBtn(connectButton, buttonTxt);
}

MainActivity.java

@Override
public void onViewUpdate(String buttonTxt, String txtTxt) {
    HomeFragment homeFragment = (HomeFragment)getSupportFragmentManager().findFragmentById(R.id.frame_container);
    if(homeFragment != null){
    homeFragment.update(buttonTxt, txtTxt);
    }
}
Mariusz Brona
  • 1,549
  • 10
  • 12
0
public class Dcrypt extends Fragment {

Button butD;
ImageButton Dcopy;
EditText getPass;
TextView txtShow;

use this line of code to get support of text field

private FragmentManager supportFragmentManager;
Simon H
  • 2,495
  • 4
  • 30
  • 38
Amank
  • 1
  • 2