NullPointerException a call tag fragment ViewPager - android

Need help, trying to invoke a method fragment of Activity, I think that is not correct ask tags for fragments.
so ask tags:
public class TitleAdapter extends FragmentPagerAdapter {
public final String titles[] = new String[] { "A", "B", "C" };
public final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new FragmentA();
fm.beginTransaction().add(frags[0], "fragA").commit();
frags[1] = new FragmentB();
fm.beginTransaction().add(frags[1], "fragB").commit();
frags[2] = new FragmentC();
fm.beginTransaction().add(frags[2], "fragC").commit();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
Feel right from causing onCreate(Bundle savedInstanceState)
public class MainActivity extends FragmentActivity {
TitleAdapter titleAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
FragmentManager fm = getSupportFragmentManager();
FragmentA fragment = (FragmentA)fm.findFragmentByTag("fragA");
fragment.bgStop();
Here the method itself
public class FragmentA extends Fragment {
final static String LOG_TAG = "myLogs";
static Button btnPlay;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
btnPlay = (Button) rootView.findViewById(R.id.btnStart);
return rootView;
}
public void bgPlay(){
btnPlay.setText("Play");
btnPlay.setBackgroundResource(R.drawable.play_button);
}
public void bgStop(){
btnPlay.setText("Stop");
btnPlay.setBackgroundResource(R.drawable.stop_button);
}
}

There are so many problems with that code. Here, let me fix that for you.
The following is untested, just edited in my favourite text editor.
public class TitleAdapter extends FragmentPagerAdapter {
public final String titles[] = new String[] { "A", "B", "C" };
public final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
// do not commit any fragments here, the adapter handles that.
frags[0] = new FragmentA();
frags[1] = new FragmentB();
frags[2] = new FragmentC();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
Then in the activity:
public class MainActivity extends FragmentActivity {
TitleAdapter titleAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
final TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Fragment fragment = titleAdapter.getItem(position);
// Ideally use some sort of interface here.
if (fragment instanceof FragmentA) {
((FragmentA) fragment).bgStop();
}
}
});
}
}

Related

Two fragments refactoring into one

I created two fragments: 'scheduleFragment' and 'clockFragment'. After setting up
public class ClockFragment extends AppCompatActivity implements View.OnClickListener {
private int notificationId = 1;
in MainActivity.java, the pageAdapter
scheduleFragment = new ScheduleFragment();
clockFragment = new ClockFragment();
tabLayout.setupWithViewPager(viewPager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), 0);
viewPagerAdapter.addFragment(clockFragment, "Clock");
viewPagerAdapter.addFragment(scheduleFragment, "Schedule");
viewPager.setAdapter(viewPagerAdapter);
creates an error that states I have to switch refactor the clockFragment into the scheduleFragment so one fragment is created.
I need these two fragments because, in the ClockFragment (tab), the clock must appear to users and on the ScheduleFragment (tab), the schedule of users is present. I am not sure how I can separate the two tabs without causing an error.
Some explanation over why this error occurs and a solution will be greatly appreciated.
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ViewPager viewPager;
private TabLayout tabLayout;
private ScheduleFragment scheduleFragment;
private ClockFragment clockFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tab_layout);
scheduleFragment = new ScheduleFragment();
clockFragment = new ClockFragment();
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_baseline_add_alarm_24);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_baseline_assignment_turned_in_24);
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments = new ArrayList<>();
private List<String> fragmentTitle = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public ViewPagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
public void addFragment(ClockFragment fragment, String title) {
fragments.add(fragment);
fragmentTitle.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitle.get(position);
}
}
}
First ClockFragment extends Activity which means it is not a fragment.
I will give you an example of how you should do things:
public class ChildFragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.child_fragment_1_layout, container, false);
Button buttonInFragment1 = rootView.findViewById(R.id.button_1);
buttonInFragment1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "button in fragment 1", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Now do Fragment 2:
public class ChildFragment2 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.child_fragment_1_layout, container, false);
Button buttonInFragment1 = rootView.findViewById(R.id.button_1);
buttonInFragment1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "button in fragment 2", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Now add a new class for the adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new ChildFragment1(); //ChildFragment1 at position 0
case 1:
return new ChildFragment2(); //ChildFragment2 at position 1
}
return null; //does not happen
}
#Override
public int getCount() {
return 2; //three fragments
}
}
And your MainActivity would look something like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
}

how to transaction replace a fragment in tabs

I have an Android tabs with 3 fragments and a FAB. I want to replace to a new fragment when click the FAB but when i click the button it replace with a blank fragment. And when i click on my tabs, it doesn't show its fragment but an empty fragment instead (sometimes it show right but i don't know when)
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private TabLayout tabLayout;
private FloatingActionButton fabAdd;
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.container);
PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager());
pageAdapter.addFragment(new Wallet(), "Wallet");
pageAdapter.addFragment(new History(),"History");
pageAdapter.addFragment(new Setting(),"Setting");
mViewPager.setAdapter(pageAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
manager = getSupportFragmentManager();
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddAccount addAccount = new AddAccount();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,addAccount);
transaction.commit();
}
});
}
}
And here is my adapter:
public class AccountAdapter extends BaseAdapter {
private Context context;
private int layout;
private List<Account> accountList;
public AccountAdapter(Context context, int layout, List<Account> accountList) {
this.context = context;
this.layout = layout;
this.accountList = accountList;
}
#Override
public int getCount() {
return accountList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(layout,null);
TextView accountName = (TextView) view.findViewById(R.id.tvAccount);
TextView accountAddress = (TextView) view.findViewById(R.id.tvAddress);
Account account = accountList.get(i);
accountName.setText(account.getAccountName());
accountAddress.setText(account.getAccountAddress());
return view;
}
}
Here is one of my Fragments (the other is same):
public class AddAccount extends Fragment {
public AddAccount() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_account,container,false);
}
}
I'm new to Android and not good English, so forgive me if i make grammar mistake.
Edit: Is there any way to show a new fragment to a viewpager?
Use this code inside onClick
Fragment fragment = new AddAccount();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.commit();
and use this for your adapter
class AccountAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}

Replacing a fragment inside a Viewpager

I am able to get DFragment on top of AFragment and on press back of DFragment I am getting AFragment. But the problem that I am facing is when AFragment is shown,BFragment and CFragment show their respective layouts. But when I traverse from A to D, then B and C show D's layouts only.
I have tried notifyDataSetChanged on the Adapter but still doesn't work properly. Please help
My MainActivity
public class MainActivity extends FragmentActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence tabTitles[] = {"A", "B", "C"};
int numTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), tabTitles, numTabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
}
}
This is my ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence tabTitles[];
int numTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence tabTitles[], int numTabs) {
super(fm);
this.tabTitles = tabTitles;
this.numTabs = numTabs;
}
#Override
public Fragment getItem(int position) {
if(position==0)
return new AFragment();
else
if(position==1)
return new BFragment();
else
return new CFragment();
}
#Override
public int getCount() {
return numTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
This is my 0th fragment
public class AFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View rootView =inflater.inflate(R.layout.a,container,false);
Button b = (Button)rootView.findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity) context).getSupportFragmentManager().beginTransaction().add(R.id.container, new DFragment())
.addToBackStack("").commit();
}
});
return rootView;
}
}
This is the new fragment that comes on top of my 0th fragment
public class DFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_d,null);
return rootView;
}
}

NullPointerException when you scroll fragments ViewPager

Need your help, after clicking on the button in the fragment A ViewPager want to page through the next piece I NullPointerException an error that points to this code Fragment fragment = titleAdapter.getItem (position); how can I fix it?
Maybe something I'm doing wrong, but in the end I would like to get that when you click on one fragment changed the image and text in the other two.
TitleAdapter.java:
public class TitleAdapter extends FragmentPagerAdapter {
public final String titles[] = new String[] { "A", "B", "C" };
public final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new FragmentA();
frags[1] = new FragmentB();
frags[2] = new FragmentC();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
MainActivity.java:
public class MainActivity extends FragmentActivity {
boolean isPlayingA = false;
boolean isPlayingB = false;
boolean isPlayingC = false;
TitleAdapter titleAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
final TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
}
public void playA() {
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
public void onPageSelected(int position) {
Fragment fragment = titleAdapter.getItem(position);
if (fragment instanceof FragmentB) {
((FragmentB) fragment).bgStop();
}
if (fragment instanceof FragmentC) {
((FragmentC) fragment).bgStop();
}
}
});
}
isPlayingB = false;
isPlayingC = false;
}
}
code is identical to that of the other fragments
FragmentA.java:
public class FragmentA extends Fragment {
final static String LOG_TAG = "myLogs";
static Button btnPlay;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
btnPlay = (Button) rootView.findViewById(R.id.btnStart);
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View rootView) {
if (((MainActivity)getActivity()).isPlayingA) {
bgPlay();
}else{
bgStop();
((MainActivity)getActivity()).playA();
}
((MainActivity)getActivity()).isPlayingA = !((MainActivity)getActivity()).isPlayingA;
}
});
return rootView;
}
public void bgPlay(){
btnPlay.setText("Play");
btnPlay.setBackgroundResource(R.drawable.play_button);
}
public void bgStop(){
btnPlay.setText("Stop");
btnPlay.setBackgroundResource(R.drawable.stop_button);
}
}
In the onCreate method you have created another variable for TitleAdapter overriding global(class) variable.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
//Here
final TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
}
Instead your onCreate method should be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
}

Viewpager and Sherlock Fragments. How to do somethng inside fragment from FragmentActivity?

I have a parent SherlockFragmentActivity class that contains ViewPager with 4 Fragments inside.
One of them extends from SherlockListFragment and I want to scroll it to top by click on it's tab.
MainActivity class:
public class MainActivity extends SherlockFragmentActivity {
ViewPager viewPager;
TabAdapter tabAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(Constants.THEME);
viewPager = new ViewPager(this);
viewPager.setId(R.id.pager);
viewPager.setBackgroundResource(R.color.background_color);
tabAdapter = new TabAdapter(this,viewPager);
super.onCreate(savedInstanceState);
setContentView(viewPager);
// Action bar setup
setupTabs(savedInstanceState);
}
private void setupTabs(Bundle savedInstanceState) {
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i = 1; i <= 4; i++) {
ActionBar.Tab tab = getSupportActionBar().newTab();
switch (i) {
case 1:
tab.setText(R.string.feed).setTabListener(tabAdapter);
tabAdapter.addTab(EventListFragment.class);
break;
case 2:
tab.setText(R.string.downloads).setTabListener(tabAdapter);
tabAdapter.addTab(LocalEventListFragment.class);
break;
case 3:
tab.setText(R.string.tags).setTabListener(tabAdapter);
tabAdapter.addTab(TagsFragment.class);
break;
case 4:
tab.setText(R.string.settings).setTabListener(tabAdapter);
tabAdapter.addTab(SettingsFragment.class);
break;
}
getSupportActionBar().addTab(tab);
}
}
TabAdapter class:
public static class TabAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
private final ActionBar mActionBar;
private final ViewPager mViewPager;
public TabAdapter(SherlockFragmentActivity activity, ViewPager pager){
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(Class<?> clss){
classes.add(clss);
mFragments.add(Fragment.instantiate(mContext, clss.getName(),
null));
}
#Override
public Fragment getItem(int i) {
return mFragments.get(i);
}
public int getId(int index){
return mFragments.get(index).getId();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// fixed double call onTabReselected
if (mActionBar.getSelectedNavigationIndex() != position)
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int i) {
}
#Override
public int getCount() {
return 4;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
final int position = tab.getPosition();
final Fragment fragment = mFragments.get(position);
if (fragment != null) {
switch (position) {
case 0:
// call tab's ListFragment scroll to top item
((EventListFragment) fragment).scrollToTop();
break;
case 1:
// do something
break;
}
}
}
onTabReselected called, then user press current tab, so I try to do EventListFragment scrolling:
EventListFragment class:
public class EventListFragment extends SherlockListFragment {
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mAdapter = new EventListAdapter(getSherlockActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View eventListLayout = inflater.inflate(R.layout.eventlist_fragment,null);
ListView lv = (ListView) eventListLayout.findViewById(android.R.id.list);
ViewGroup parent = (ViewGroup) lv.getParent();
//Remove ListView and add PullToRefreshListView in its place
int lvIndex = parent.indexOfChild(lv);
parent.removeViewAt(lvIndex);
mPullToRefreshListView = onCreatePullToRefreshListView(inflater, savedInstanceState);
parent.addView(mPullToRefreshListView, lvIndex, lv.getLayoutParams());
return eventListLayout;
}
public void scrollToTop() {
if (getSherlockActivity() != null) { // null after screen rotation
final ListView listView = getListView();
listView.post(new Runnable(){
public void run() {
listView.smoothScrollToPosition(0);
}});
}
}
It works on application start, but after screen rotation scrollToTop - getSherlockActivity() returns null.
If remove this condition check, have an exception:
java.lang.IllegalStateException: Content view not yet created
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
at com.project.fragment.EventListFragment.scrollToTop(EventListFragment.java:337)
at com.project.MainActivity$TabAdapter.onTabReselected(MainActivity.java:411)
at com.actionbarsherlock.internal.app.ActionBarWrapper$TabWrapper.onTabReselected(ActionBarWrapper.java:327)
I haven't totally understatinding how to ViewPager and its FragmentPagerAdapter works. So can't find a problem, that occurs.
Use this FragmentPageAdapter:
public class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "CATEGORIAS", "PRINCIPAL", "AS MELHORES", };
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
};
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {Fragment f = null;
switch(position){
case 0:
{
f = new ArrayListFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 1:
{
f = new HomeFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 2:
{
f = new EndlessCustomView();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
return f;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
This Activity:
public class BaseSampleActivity extends SlidingFragmentActivity {
private static final Random RANDOM = new Random();
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
protected ListFragment mFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.themed_titles);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
Applied solution according to this post:
MainActivity class:
//...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
FragmentManager manager = getSupportFragmentManager();
for (int i = 0; i < tabAdapter.getClasses().size(); i++) {
String className = tabAdapter.getClasses().get(i).getName();
if (manager.findFragmentByTag(className) != null) {
manager.putFragment(outState, className, manager.findFragmentByTag(className));
}
}
}
//...
TabAdapter class:
//...
public void addTab(Class<?> clss, FragmentManager manager, Bundle savedInstanceState) {
classes.add(clss);
String className = clss.getName();
tags.add(className);
Fragment fragment;
if (savedInstanceState != null) {
fragment = manager.getFragment(savedInstanceState, className);
if (fragment == null) {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
} else {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
mFragments.add(fragment);
}
//...
where createFragment is a simple method, that creates needed fragment by passed class name.

Categories

Resources