Changing the value of a TextView inside a ViewPager - android

I have the following problem, I have a ViewPager, the Viewpager contains a Fragment and this fragment contains a textview that contains an int value (8000 in this case). What i want is a way to make gain 500 when the button _Mas500 is pressed. When i run the proyect it appears this error:
08-06 22:42:15.687: E/AndroidRuntime(8639): FATAL EXCEPTION: Thread-10
08-06 22:42:15.687: E/AndroidRuntime(8639): java.lang.IllegalStateException: Must be called from main thread of process
Any ideas are accepted! Thanks!
Heres my code:
public class MainActivity extends ActionBarActivity {
private int _JugLP;
private DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
private Button _Mas500;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
declarar();
_Mas500.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int n = _JugLP + 500;
mDemoCollectionPagerAdapter.setLP(mViewPager.getCurrentItem(),
n);
mDemoCollectionPagerAdapter.notifyDataSetChanged();
}
});
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
declarar();
}
public void declarar() {
mViewPager = (ViewPager) findViewById(R.id.pager);
_JugLP = 8000;
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(
getSupportFragmentManager(), _JugLP);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
_Mas500 = (Button) findViewById(R.id.btn_mas500);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class DemoCollectionPagerAdapter extends
FragmentStatePagerAdapter {
int _LP;
DemoObjectFragment[] fragments;
public DemoCollectionPagerAdapter(FragmentManager fm, int n) {
super(fm);
_LP = n;
fragments = new DemoObjectFragment[n];
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, _LP);
fragments[0].setArguments(args);
fragments[1].setArguments(args);
}
#Override
public Fragment getItem(int i) {
return fragments[i];
}
public void setLP(int i, int LP) {
fragments[i].setLP(_LP);
}
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return POSITION_NONE;
}
#Override
public int getCount() {
// For this contrived example, we have a 100-object collection.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Titulo";
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
private TextView _TxtVwLP;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
_TxtVwLP = (TextView) rootView.findViewById(android.R.id.text1);
_TxtVwLP.setText(Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
public void setLP(int LP) {
_TxtVwLP.setText(String.valueOf(LP));
}
}
}

I think your problem is in notifyDataSetChanged. because when you call notifyDataSetChanged you tell the viewPager hey viewPager i have removed or created some children for you, reload yourself. and when he reload himself he creates fragments without any changed you have already made. so I think you should change your logic.
look at these for solution:
Android FragmentStatePagerAdapter, how to tag a fragment to find it later
Is it possible to access the current Fragment being viewed by a ViewPager?

Thanks mmlooloo! After reading the useful documents you posted I was able to generate an answer. Here's what i Changed:
_Mas500.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int n = _JugLP + 500;
_JugLP=n;
DemoObjectFragment x = (DemoObjectFragment) mDemoCollectionPagerAdapter
.instantiateItem(mViewPager,
mViewPager.getCurrentItem());
x.setLP(n);
}
});
After trying it several times, the textview finally changed! It seems to work fine and I think that solves my problem for now. Thanks mmlooloo!

Related

Fragment is showing but not attached to activity

Hi i am working in an app, in which:
View pager is there on an activity.
On that view pager i am showing 2 fragments(frag1 and frag2).
on button click on frag1 we have added one more fragment(lets say frag3).
and on back press on frag3 i come back on frag1.
Issue:
the issue is when i come back to frag1 from frag3 on back press, sometimes frag1 is not attached to the activity.
i am not able to figure out how this is happening.
if this is happening then what is the solution so i can stop activity to detach the frag1 or re-initialize the frag1 again.
Please help.
This code may help you
public class PageAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final int[] PAGER = new int[] {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4
};
private int mCount = PAGER.length;
public PagerFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new PagerFragment(PAGER[position]);
}
#Override
public int getIconResId(int index) {
return ICONS[index % PAGER.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
Defining Fragments
public final class PagerFragment extends Fragment {
private static final String KEY_CONTENT = "PagerFragment:Content";
int imageSource;
public PagerFragment(int imageSource) {
this.imageSource = imageSource;
}
public PagerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
imageSource = savedInstanceState.getInt(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.indicatorpage, null);
ImageView image = (ImageView) root.findViewById(R.id.pagerImage);
image.setImageResource(imageSource);
setRetainInstance(true);
return root;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_CONTENT, imageSource);
}
}
MainActivity Class
public class MainActivity extends FragmentActivity {
PagerFragmentAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new PagerFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("selected page is :" + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
CirclePageIndicator mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
mIndicator.setRadius(7 * density);
mIndicator.setPageColor(0x00000000);
mIndicator.setFillColor(0xFFFFFFFF);
mIndicator.setStrokeColor(0xFFFFFFFF);
mIndicator.setStrokeWidth(1 * density);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

FragmentStatePagerAdapter and ViewPager: Fragments instantiate out of order

I am trying to use FragmentStatePagerAdapter with ViewPager to achieve a sequential slide scroll view (similar to most pdf readers). However, while running the code, the following is happening:
When the activity becomes visible, the first page is instantiated with a different (2nd) page's value. However, when scrolled to some other page and then back to page 1, the page displays default text from layout file.
Only 2nd and 2nd to last pages instantiate with the passed value (that too with values from other pages, not their own). Rest of the pages display default text from layout file.
On debugging, I noticed that the index/currentItemNumber changes when ViewPager.populate() calls ViewPager.addNewItem(). Ever more strange is the fact that setText() is called on the TextView (part of fragment layout), but text does not change from the default text.
Am I missing something?
Here is the code below:
MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private ViewPager mPager;
private Button mButtonFirst;
private Button mButtonPrev;
private Button mButtonGoTo;
private Button mButtonNext;
private Button mButtonLast;
private TextView mPageCount;
private EditText mPageNumber;
private TextView mError;
private int mNumScreens;
private int mCurrScreen;
private MyPagerAdapter mMyPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpViews();
setUpListeners();
setUpPager();
}
private void setUpViews() {
mPager = (ViewPager) findViewById(R.id.my_pager);
// Get other view handles...
mError = (TextView) findViewById(R.id.error_details);
}
private void setUpListeners() {
// Set this class as click handler for all buttons
}
private void setUpPager() {
String[] strings = new String[] {
"1",
"2",
"3",
"4",
"5",
"6"
};
// Success!
// Set adapter and update views
mMyPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), strings);
mPager.setAdapter(mMyPagerAdapter);
mNumScreens = strings.length;
mPageCount.setText("/" + Integer.toString(mNumScreens));
mCurrScreen = -1;
GoToScreen(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// Handle options
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_first:
GoToScreen(1);
break;
case R.id.button_prev:
GoToScreen(mCurrScreen - 1);
break;
case R.id.button_goto:
{
int screen;
boolean reset = false;
try {
screen = Integer.parseInt(mPageNumber.getText().toString());
reset = !SetToScreen(screen);
} catch (NumberFormatException e) {
e.printStackTrace();
reset = true;
}
if(reset) {
mPageNumber.setText(Integer.toString(mCurrScreen));
}
}
break;
case R.id.button_next:
GoToScreen(mCurrScreen + 1);
break;
case R.id.button_last:
GoToScreen(mNumScreens);
break;
}
}
private void GoToScreen(int screen) {
if(SetToScreen(screen)) {
mPageNumber.setText(Integer.toString(mCurrScreen));
}
}
private boolean SetToScreen(int screen) {
// Switch to a valid screen
if(screen >= 1 && screen <= mNumScreens && mCurrScreen != screen) {
mPager.setCurrentItem(screen - 1, false);
// Handle button visibility
// Update current screen
mCurrScreen = screen;
return true;
}
return false;
}
MyPagerAdapter.java
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private final String[] mStrings;
public MyPagerAdapter(FragmentManager fm, String[] strings) {
super(fm);
mStrings = strings;
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public Fragment getItem(int position) {
return ScreenFragment.newInstance(mStrings[position]);
}
}
ScreenFragment.java
public class ScreenFragment extends Fragment {
private static final String ARG_SCREEN_STRING= "screen_string";
private String mScreenInfo;
private TextView mStatementLabel;
public static ScreenFragment newInstance(String screenString) {
ScreenFragment fragment = new ScreenFragment();
Bundle args = new Bundle();
args.putString(ARG_SCREEN_STRING, screenString);
fragment.setArguments(args);
return fragment;
}
public ScreenFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mScreenInfo = getArguments().getString(ARG_SCREEN_STRING);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_screen, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setUpViews();
setUpFields();
}
private void setUpFields() {
mStatementLabel.setText(mScreenInfo);
}
private void setUpViews() {
mStatementLabel = (TextView) getActivity().findViewById(R.id.qnr_screen_statement);
}
}
The problem was solved when I moved calls to setUpViews() and setUpFields() to onCreateView() from onActivityCreated(), with little modifications. This is how the new onCreateView() looks like (I moved the content of the above mentioned functions here)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_screen, container, false);
mStatementLabel = (TextView) v.findViewById(R.id.qnr_screen_statement);
mStatementLabel.setText(mScreenInfo);
return v;
}
I am yet to figure out why that was causing the problem. Will update if I find anything.

How to get the selected page index of ViewPager in fragment

I'm making use of ViewPagerIndicator, and I have my adapter defined like this:
public class MyPagerAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
private final static String TAB_ITEMS[] = { "Tab 1", "Tab 2", "Tab 3", "Tab 4"};
private int count = TAB_ITEMS.length;
public MyPagerAdapter (FragmentManager fm) {
super(fm);
}
#Override
public int getIconResId(int index) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new BaseFragment();
return fragment;
}
#Override
public int getCount() {
return count;
}
And this is my activity that will contain my fragments:
public class MyActivity extends FragmentActivity implements
OnPageChangeListener {
private int tabPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter (
getSupportFragmentManager());
pager.setAdapter(adapter);
UnderlinePageIndicator indicator = (UnderlinePageIndicator) findViewById(R.id.indicator);
indicator.setFades(false);
indicator.setViewPager(pager);
indicator.setOnPageChangeListener(this);
}
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
setTabPosition(position);
Toast.makeText(MyActivity.this,
"Changed to page: " + position, Toast.LENGTH_SHORT).show();
}
public void setTabPosition(int position) {
this.tabPosition = position;
}
public int getTabPosition() {
return this.tabPosition;
}
}
Finally the definition of BaseFragment:
public class BaseFragment extends Fragment implements OnItemClickListener {
private final static String TAG = "BaseFragment";
private int tabPosition;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_base, container,
false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
tabPosition = ((MyActivity) getActivity()).getTabPosition();
Toast.makeText(getActivity(), "page " + tabPosition, Toast.LENGTH_SHORT)
.show();
}
Now , this is my problem:
The toast in onPageSelected of the activity always shows the correct page when a new page is selected or swiped to.
However, the toast in my fragment only shows the correct page when you swipe to either page 1 or page 2. The only time it toasts page 0 is anytime the app is launched. After that, when the user swipes to page 0 or page 4, no toast is shown at all, not even an empty toast.
I wrote the getTabPosition() and setTabPosition() methods with the intention of getting the current selected tab position in the fragment, but it obviously doesn't work correctly hence I dont get toasts on pages 0 and 4.
My question is: how do I get the selected page position in my BaseFragment, since I need that position to load the appropriate data?
Hope I was clear enough?
Each Fragment will display a different set of data, then maybe it is a good idea to have one fragment for each. Here is what I did to display different Fragments for different data in the FragmentPagerAdapter:
#Override
public Fragment getItem(int index) {
Fragment fragment = null;
// Define the page for each index
switch(index){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
}
This may not be the best approach but in your activity that holds reference to ViewPager try this:
public class TabbedViewActivity extends FragmentActivity {
ViewPager viewPager;
public static int tabIndex = 0;
#Override
protected void onCreate(Bundle bundle) {
......
viewPager = (ViewPager)findViewById(R.id.pager);
TabbedViewActivity.tabIndex = 0; // in the start index is always 0 unless coded otherwise
viewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
TabbedViewActivity.tabIndex = position;
}
});
}
Then you can always access this variable statically like this in your Fragment TabbedViewActivity.tabIndex
pager.getCurrentItem();
it return current fragment index

How to pass a string between fragments in a viewpager

I'm trying to pass a string between two fragments in a viewpager but I didn't found the right way to do it.
Here is my code so far :
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 6;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new MyFragment();
case 1:
return new part2();
case 2:
return new Part3();
case 3:
return new Part4();
case 4:
return new Part5();
case 5:
return new Part6();
default:
return null;
}
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page #" + ( position + 1 );
}
}
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I'm not using tabs with the viewpager. What should I write in the fragments?
UPDATE :
I tried to implement an interface like suggested in the answers :
public interface OnTogglePressListener {
public void onTogglePressed(String msg);
}
On the first fragment :
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
try {
buttonListener = (OnTogglePressListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onTogglePressed");
}
super.onAttach(activity);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
buttonListener.onTogglePressed("Off");
... }
On the second fragment :
public String getEtat(String etat)
{ state =etat;
return etat;
}
On the main activity :
public void onTogglePressed(String etat)
{
Part5 p = (Part5)getSupportFragmentManager().findFragmentById(R.layout.frag_2);
p.getEtat(etat);
}
But I got a NullPointerException everytime.
You're obviously using ViewPager and you can take advantage of it. You can add a tag to a ViewPager like this:
Activity:
pager.setTag("some text"); // pager is a ViewPager object
Then you can get this data via ViewGroup in a fragment like this:
Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
String result = container.getTag().toString();
// do something with the result
return view;
You can also setTag() to the container in the fragment.
This is the cleanest solution I found for sending data among fragments and their mother activity. Another solution (not mentioned here so far) is sending data through SharedPreferences, but I would suggest using tags if possible.
So i found the solution, the implementation is correct, the only thing that I should do the treatement I want in the method on the second fragment and that's it !

Refresh fragment view when button is clicked

I have a fragment activity that uses a ViewPager to display a set of fragments. On the fragment activity I have a button that when clicked, it sends a message to the current fragment to refresh its contents. Everything works ok (activity / current fragment communication) except the fact that I cannot refresh the fragment's view. Accessing the current view by getView() does not work as this function returns null; it seems that after the fragment is created (on ViewCreated is called) getView gets destroyed. Am I missing something here? How to I cause a fragment to redraw its contents programmatically? It seems that the only way this works is when the fragment is created from the parent activity. Do I have to remove and re-add the fragment again to do this?
Here is the code:
The main activity:
public class MainActivity extends FragmentActivity {
private MyAdapter mAdapter;
private static ViewPager mPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViewPager();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_test:
updateFragment();
return true;
default: return true;
}
}
private void updateFragment() {
for (int i=0; i< mAdapter.getCount(); i++) {
SampleFragment fragment = (SampleFragment) mAdapter.getItem(i);
fragment.update();
}
}
private void setupViewPager() {
try {
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(this.mAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
SampleFragment fragment = new SampleFragment(position);
return fragment;
}
#Override
public int getCount() {
return 5;
}
}
}
and the fragment class:
public class SampleFragment extends Fragment{
private int myPosition = -1;
public SampleFragment(int position) {
this.myPosition = position;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
update(view, "Updated from onCreateView");
return view;
}
#Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.textTitle).setOnClickListener(myClickListener);
}
private OnClickListener myClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.textTitle:
break;
}
}
};
public void update() {
update(getView(), "Updated from main");
}
private void update(View view, String subtitleText) {
TextView title = (TextView) view.findViewById(R.id.textTitle);
TextView subtitle = (TextView) view.findViewById(R.id.textSubtitle);
title.setText("Fragment " + myPosition);
subtitle.setText(subtitleText);
}
}
The error happens on view.FindViewById (view is null) when called from the menu item in the main activity.
You can take a look at this article which explains how to keep references to the fragments in your ViewPager.
There are two methods described on the page. The first one involves setting a tag when you add the fragment using the FragmentManager. Then you can retrieve the fragment using findFragmentByTag(). However, I did not see how to make this work using FragmentPagerAdapter or FragmentStatePagerAdapter, since these implementations add the fragments for you. If you are using your own custom PagerAdapter, this may work for you.
The other method, which does work for FragmentPagerAdapter or FragmentStatePagerAdapter, involves keeping a map of all your fragments, updating inside your getItem() and destroyItem() implementations. This method has worked for me.
Once you have a reference to the current fragment, you can just call a method in your fragment to refresh its view.

Categories

Resources