0

In my application, I have multiple instances of the same fragment. I want to be able to setText of a Textview within each individual fragment. However, when I try to setText of a fragment's Textview, it will change that Textview in every fragment.

How would I be able to change a Textview in an individual instance of a fragment, without using unique Tags or IDs for each fragment?

Here is my fragment class:

public static class ActivityFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, Bundle savedInstanceState) {
        final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);

        final TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
        //Calling setText changes the activityText Textview in every fragment onscreen
        activityText.setText(text);


        return fragment1;
    }
}

Here is my MainActivity class:

public class MainActivity extends FragmentActivity {
Static String text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    for (int i = 0; i != 5; i++) {
        text = "success" + i;
        ActivityFragment myFragment = new ActivityFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.fragment_container, myFragment).commit();
    }
}    
Ewen Crawford
  • 89
  • 2
  • 8

2 Answers2

0

Use replace instead of add

  getFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, myFragment).commit();

But you should have a different id(fragments) for your purpose.

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
0

You can pass title inside the constructor of your fragment and no need to create static variable for a title. like:

ActivityFragment myFragment = new ActivityFragment(title);

inside you fragment,

String title;

public void ActivityFragment(String title) // your constructor
{
      this.title=title;
}

in

onCreateView()

activityText.setText(title);
Mehta
  • 1,228
  • 1
  • 9
  • 27