Fragment is showing but not attached to activity - android

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);
}
}

Related

How to count fragments?

I have an activity and pager adapter in it which displays 3 fragments. The fragments are shuffled. I need to know the number of each page when I am swiping through them and that number needs to be displayed in a textView. For example, when I am in the first page number 1 is displayed, second page - number 2 and so on.
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int arg0) {
return this.fragments.get(arg0);
}
#Override
public int getCount() {
return this.fragments.size();
}
public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
}
mainActivity.java
public class testActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager_adapter);
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you want to be displaying the number in your fragment, use this
In your Activity
#Override
public Fragment getItem(int position) {
// Here you can add an argument that will be passed to the fragment
// In your case you need to pass the page number
Fragment fragment = this.fragments.get(arg0);
Bundle b = new Bundle();
b.putInt("page_number", position);
fragment.setArguments(b);
return fragment;
}
In you fragment do this
int number;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read the data that Activity passed to us
if (savedInstanceState == null) {
Bundle args = getArguments();
if (args != null) {
number = args.getInt("page_number") + 1;
}
}
else {
number = savedInstanceState.getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Here you need to find your TextView and show the number
View v = inflater.inflate(R.layout.some_layout, container, false);
((TextView) v.findViewById(R.id.someTextView)).setText(String.format("%d", number));
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("page_number", number);
}
If you want to be displaying the number in your Activity, use this
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
// !!! Change ME!!!!!
textView = (TextView) findViewById(R.id.someTextView);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
textView.setText("Position: " + i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
pager.setAdapter(mPagerAdapter);
}
Use PageChangeListener as:
yourPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
yourTextView.setText("Page: " + position);
}
... ...
});

Android FragmentPagerAdapter detect if user has visited a specific tab

I have multiple tabs using FragmentPagerAdapter but the ViewPager creates a page before and after my current tab and the OnCreate() method gets called even when I'm not on that tab. It becomes really difficult to run a specific operation on a specific tab rather than executing before visiting the tab. Is there anyway so that I can detect if the user has visited the particular tab from the tab itself?
public class MainActivity extends ActionBarActivity implements ViewPager.OnPageChangeListener {
public static final int TAB_PROFILE = 0;
public static final int TAB_JOBS = 1;
public static final int TAB_GPS = 2;
public static final int TAB_COMMENTS = 3;
public static final int TAB_OTHERS = 4;
Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mPager.setOnPageChangeListener(this);
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setCustomTabView(R.layout.custom_tab_item, R.id.tabText);
mTabs.setDistributeEvenly(true);
mTabs.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccent));
mTabs.setViewPager(mPager);
}
#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;
}
if (id == R.id.action_search) {
startActivity(new Intent(this, subActivity.class));
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d("CURRENT_TAB", "" + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
class MyPagerAdapter extends FragmentPagerAdapter {
//String[] tabsTitle = getResources().getStringArray(R.array.tabs);
int tabIcons[] = {R.drawable.ic_tab_home,
R.drawable.ic_tab_job,
R.drawable.ic_tab_map,
R.drawable.ic_tab_comments,
R.drawable.ic_tab_others};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
//tabsTitle = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Logs.logs("getItem called for " + position);
switch (position) {
case TAB_PROFILE:
fragment = FragmentProfile.newInstance("" + position, "true");
break;
case TAB_JOBS:
fragment = FragmentJobs.newInstance("" + position, "true");
break;
case TAB_GPS:
fragment = FragmentGPS.newInstance("" + position, "true");
break;
case TAB_COMMENTS:
fragment = FragmentComments.newInstance("" + position, "true");
break;
case TAB_OTHERS:
fragment = FragmentOthers.newInstance("" + position, "true");
break;
}
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
Drawable drawable = getResources().getDrawable(tabIcons[position]);
drawable.setBounds(0, 0, 36, 36);
ImageSpan imageSpan = new ImageSpan(drawable);
SpannableString spannableString = new SpannableString(" ");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
#Override
public int getCount() {
return 5;
}
}
}
Tab #1
public class FragmentProfile extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_profile, container,false);
return view;
}
}
Okay after searching for a quite long time, I finally figured out that you were calling setOnPageChangeListener() for ViewPager instead of calling setOnPageChangeListener() for SlidingTabLayout
This question was answered here,
onPageScrolled() not being called
What about havong your main fragment implementing ViewPager.OnPageChangeListener , then you may override onPageSelected

Switch between different ViewPagers

I am trying to switch between different ViewPagers (using e.g. a button). It is basically a small tool to optically compare different versions of images. Right now I have only implemented a single ViewPager nested in a RelativeLayout (need the layout for something else). The content is filled by a custom PagerAdapter.
Any ideas on how to change forth and back between multiple ViewPagers?
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new SheetPagerAdapter());
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SheetPagerAdapter.java
public class SheetPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 4;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
SheetView sheetView = new SheetView(container.getContext(), position);
container.addView(sheetView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return sheetView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
SheetView.java
public class SheetView extends RelativeLayout {
private final String[] images = {
"page01.jpg",
"page02.jpg",
"page03.jpg",
"page04.jpg"
};
private SubsamplingScaleImageView scaleImageView;
public SheetView(Context context, int page) {
super(context);
scaleImageView = new SubsamplingScaleImageView(context);
this.addView(scaleImageView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
scaleImageView.setImage(ImageSource.asset(images[page]));
}
}
I finally ended up using a FrameLayout with multiple ViewPagers as child elements.
Only the "active" Layout is set visible:
public class MainActivity extends ActionBarActivity {
private ArrayList<ViewPager> viewPagerList = new ArrayList<>();
private final int NUM_LAYERS = 10;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout container = (FrameLayout) findViewById(R.id.frame_container);
// Add ViewPagers and fill ArrayList
for(int i = 0; i < NUM_LAYERS; i++) {
ViewPager vp = new ViewPager(this);
vp.setVisibility(View.INVISIBLE); // Make invisible
viewPagerList.add(vp);
container.addView(vp);
}
// Make first ViewPager visible
viewPagerList.get(0).setVisibility(View.VISIBLE);
}
// Switch to other ViewPager
public void setViewPager(int number) {
for (ViewPager vp : viewPagerList) {
vp.setVisibility(View.INVISIBLE);
}
viewPagerList.get(number).setVisibility(View.VISIBLE);
}
}

Changing the value of a TextView inside a ViewPager

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!

Actionbar retaining menu item in Gingerbread and below

I'm having a strange problem using an ActionView in my Actionbar (specifically ActionbarSherlock). This issue is only happening in devices below SDK 3.0 (basically Gingerbread devices is all I'm testing on).
My app has a ViewPager and I am animating one of my menu items while an AsyncTask is running. If I touch the ActionView before swiping everything is ok, if I swipe to any of the views, then go back to the first view, which is the only view to have the ActionView, and touch the ActionView the icon is doubling up on itself, like so:
I had this same issue previously, before I implemented a ViewPager, and I fixed it by stopping and starting the animation in onCreateOptionsMenu and calling invalidateMenuOptions, which is why I have ActivityCompat.invalidateOptionsMenu(this); in onResume of the Activity. I was hoping, by calling that, the menu would refresh itself and fix the duplicating, but it isn't.
UPDATE Using getSherlock().dispatchInvalidateOptionsMenu(); seems to, at least, get the menu to refresh itself, but it causing the ActionView to go nuts.
ViewPager:
public class Main extends SherlockFragmentActivity
{
private static List<Integer> mIds;
private static SparseArray<Fragment> mPageReferenceMap = new SparseArray<Fragment>();
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
GetListingFragment().StopAnimation(); //needed to add this because the ActionView was showing on the other views when swiping
}
#Override
public void onPageScrolled(int position, float offset, int offsetPixel) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
mIds = new ArrayList<Integer>();
mIds.add(0);
mIds.add(1);
mIds.add(2);
}
#Override
public void onResume()
{
super.onResume();
ActivityCompat.invalidateOptionsMenu(this);
}
private ListingFragment GetKeywordsFragment()
{
ListingFragment lf = (ListingFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentListing);
if (lf == null)
{
final MyFragmentPagerAdapter fpa = (MyFragmentPagerAdapter)mViewPager.getAdapter();
lf = (ListingFragment)fpa.getFragment(0);
}
return lf;
}
private static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
if (index == 0)
{
final ListingFragment lf = ListingFragment.newInstance();
mPageReferenceMap.put(index, lf);
return lf;
}
else
{
final DetailFragment df = DetailFragment.newInstance(mIds.get(index));
mPageReferenceMap.put(index, df);
return df;
}
}
public Fragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
#Override
public int getCount() {
return 3;
}
}
}
Fragment:
public class ListFragment extends SherlockListFragment
{
private int mId;
private MenuItem refreshItem;
private AsyncTask<Void, String, Void> gi;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public static ListingFragment newInstance(int id) {
ListingFragment lf = new ListingFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
lf.setArguments(bundle);
return lf;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments() != null)
mId = getArguments().getInt("id");
return inflater.inflate(R.layout.listing, container, false);
}
private class GetItems extends AsyncTask<Void, String, Void> {
#Override
protected void onPreExecute()
{
StartAnimation();
}
#Override
protected Void doInBackground(Void... unused)
{
//background process to get items
}
protected void onPostExecute(final Void unused)
{
StopAnimation();
}
}
#Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.keyword_menu, menu);
StopAnimation();
refreshItem = menu.findItem(R.id.refresh);
if (fi != null && fi.getStatus() == AsyncTask.Status.RUNNING)
StartAnimation();
super.onCreateOptionsMenu(menu, inflater);
}
private void StartAnimation() {
if (refreshItem != null && refreshItem.getActionView() == null)
{
final LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ImageView ivRefresh = (ImageView)inflater.inflate(R.layout.refresh_view, null);
final Animation rotation = AnimationUtils.loadAnimation(activity, R.anim.refresh);
ivRefresh.startAnimation(rotation);
refreshItem.setActionView(ivRefresh);
}
}
public void StopAnimation()
{
if (refreshItem != null && refreshItem.getActionView() != null)
{
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
}
#Override
public boolean onOptionsItemSelected(final MenuItem item)
{
if (item.getItemId() == R.id.getitems) {
gi = new GetItems(getActivity(), null);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
Looks like this is a known bug in ABS:
https://github.com/JakeWharton/ActionBarSherlock/issues/331

Categories

Resources