In my app, I have multiple instances of the same fragment, ActivityFragment
. In each fragment, there is an activity_text
textview. When the fragment is added to the layout, I want to set the activity_text
textview within that fragment during onCreate
. However, when I try to do this, every ActivityFragment
onscreen will have their activity_text
textview changed.
Is there any way that I can limit setText
to within the scope of an individual fragment without using unique Tags or IDs for each fragment?
Here is my ActivityFragment 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++) {
//This ensures each fragment receives a unique String
text = "success" + i;
ActivityFragment myFragment = new ActivityFragment();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container, myFragment).commit();
}
}
}