Search code examples
androidandroid-fragmentssettext

Android - Replacing fragment and change its TextViews


I'm trying to change the text of a TextView inside a fragment that replace an old fragment in the same activity.

I already searched for existing answers to this question, and I found these two, but the solutions doesn't seems to work for me:

Dynamically change TextView in Fragment (public void processMessage)

Change TextView inside Fragment

The problem is that when I create a method to set the text of a TextView inside my new fragment, it doesn't find the view I'm searching.

Here's the code of the fragment that have to replace the old one:

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;

public class Fragment_sbagliato extends Fragment {

public Fragment_sbagliato() {}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_sbagliato, container,
            false);
    return rootView;
}

public void myNewText(String[] text){
    TextView textView = (TextView)findViewById(R.id.answer);
    textView.setText(text[0]);
}

}

To be specific, the error is "answer cannot be resolved or is not a field".

Any suggestion?

Thanks in advance!


Solution

  • That is a compilation error - R.id.answer isn't defined. This usually happens because the java source file imports the platform "android.R" resource class instead of your app's specific "R" resource class or because there's an error in the XML resource file which is causing a problem when generating the resources.