I'm using a FragmentPagerAdapter
in the MainActivity
. I use res\layout\fragment_text.xml
file to create two fragments each with different data entered by the user. When I try to findViewById()
, It returns data from a different fragment. Here is the applicable code:
//this is from my public class SectionsPagerAdapter extends FragmentPagerAdapter
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (position){
case 0: return MultipleChoiceSingleAnswerFragment.newInstance(position + 1);
**case 1: return TextFragment.newInstance("1", "2");**
**case 2: return TextFragment.newInstance("10", "20");**
case 3: return ScoreFragment.newInstance("100", "200");
default: return null;
}
}
//here I collect the fragment tags as they are being instantiated
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment newFragment = (Fragment) super.instantiateItem(container, position);
// save the appropriate fragment tag depending on position
fragmentTags[position] = newFragment.getTag();//store in array of Strings
return newFragment;
}
In an onclick
listener I try to retrieve the fragment and show text that the user entered, into an EditText
view, using a toast. This code is called in another Fragment that has just a TextView
and a Button
public void onScorePressed(){
int pageCount = mSectionsPagerAdapter.getCount();
**TextFragment textfragment = (TextFragment) getSupportFragmentManager().findFragmentByTag(fragmentTags[1]);
CharSequence text = textfragment.getAnswer()**;<<<<<main problem in call,see below
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
In line above `textfragment.getAnswer()' calls this method which exists in two instances of the same fragment class:
public class TextFragment extends Fragment {
//other code for building a Fragment
.....
//This method return text entered by user as well as the mParam1 used in the instantiation above in Fragment getItem case 1:;
public CharSequence getAnswer(){
EditText txt = (EditText) root.findViewById(R.id.text_answer);
return "mParam1=" + mParam1 + "text_answer=" + txt.getText();
}
The getAnswer method returns
"mParam1=1 text_answer=text entered"
from the second TextFragment instantiated in case 2 above. This shows that I'm actually getting the correct TextFragment because mParam1 matches the parameter passed in the instantiation. I need a better way to get the EditText View's text. Any help is appreciated. Thanks. Posts I used in my research:
https://stackoverflow.com/a/12805033/9226205
https://developer.android.com/guide/components/fragments.html
https://developer.android.com/reference/android/support/v4/app/FragmentManager.html