My app creates drawer submenus from sharedpreference values. These submenus are basically called "interests" or categories. I'm trying to move this same functionality to tablayout since that is much more convenient but can't seem to get it to work!
Edit: New code based on suggestions.
TabsFragment:
public class HomeTabsFragment extends Fragment implements ViewPager.OnPageChangeListener {
private View view;
private SectionsPagerAdapterHome homePageAdapter;
public ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.view = inflater.inflate(R.layout.fragment_articles_tabs, container, false);
TabLayout tabLayout = view.findViewById(R.id.home_list_tabs);
viewPager = view.findViewById(R.id.home_list_tabs_container);
homePageAdapter = new SectionsPagerAdapterHome(getFragmentManager());
viewPager.setAdapter(homePageAdapter);
viewPager.setOffscreenPageLimit(tabLayout.getTabCount());
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
if(SharedPrefernces.getUserInterests()!=null) {
List<String> my_interests = SharedPrefernces.getUserInterests();
Collections.sort(my_interests, String::compareToIgnoreCase);
my_interests.add(0, getString(R.string.all_stories));
for (String interest : my_interests) {
homePageAdapter.addTabPage(new FeedsFragment(), interest);
}
}
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = homePageAdapter.getFragment(position);
if (fragment != null) {
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Adapter:
public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private FragmentManager fragmentManager;
private ArrayList fragmentTags = new ArrayList();
private ArrayList<String> titles = new ArrayList();
protected SectionsPagerAdapterHome(FragmentManager fm) {
super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
fragmentManager = fm;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
fragmentTags.add(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
Object tag = fragmentTags.get(position);
if (tag != null) {
fragment = fragmentManager.findFragmentByTag(String.valueOf(tag));
}
return fragment;
}
#Override
public Fragment getItem(int position) {
return FeedsFragment.newInstance();
}
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragmentTags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
I'm not sure how I can achieve this so need help.
Since you are using a ViewPager with an Adapter instead of using tabLayout.addTab(...) you have to add the item in the adapter.
Something like:
public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private ArrayList fragmentTags = new ArrayList();
private ArrayList<String> titles = new ArrayList();
//.....
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragmentTags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tables.get(position);
}
}
Related
I'm trying to make a tab layout with each page having a RecyclerView inside of it. I'm using fragments with RecyclerView in them, then i put them inside of ViewPager. The problem is that even though tabs are being shown it's content is always empty.
My Activity class
public class Spells_Act extends AppCompatActivity {
private ViewPager pager;
private Spells_Slide slider;
private TabLayout tabLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spells);
tabLayout = findViewById(R.id.tab);
pager = findViewById(R.id.pager);
slider = new Spells_Slide(getSupportFragmentManager());
slider.AddFragment(new Fragment1(), "one");
slider.AddFragment(new Fragment1(), "two");
slider.AddFragment(new Fragment1(), "three");
pager.setAdapter(slider);
tabLayout.setupWithViewPager(pager);
}
}
My ViewPager adapter
public class Spells_Slide extends FragmentPagerAdapter {
private Context context;
LayoutInflater inflater;
private List<RecyclerView> pages;
private List<String> list = new LinkedList<>();
private final List<Fragment> stFragment = new ArrayList();
public Spells_Slide(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return stFragment.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object
object) {
return false;
}
public void AddFragment(Fragment fragment, String title) {
list.add(title);
stFragment.add(fragment);
}
My Fragment class
public class Fragment1 extends Fragment {
View v;
private RecyclerView recycler;
Adapter_Rec adapter;
private List<Spells> Spells = new LinkedList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Spells.add(new Spells("Ghost Sound", "Figment sounds", 0));
Spells.add(new Spells("Disrupt Undead", " Deals 1d6 damage to one undead", 0));
Spells.add(new Spells("Resistance", "Subject gains +1 on saving throws", 0));
Spells.add(new Spells("Ray of Frost", "Ray deals 1d3 cold damage", 0));
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.frag1, container, false);
recycler = v.findViewById(R.id.frag_recycler);
recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new Adapter_Rec(Spells, getContext());
recycler.setAdapter(adapter);
return v;
}
}
And finally my RecyclerViewAdapter
public class Adapter_Rec extends
RecyclerView.Adapter<Adapter_Rec.MyViewHolder> {
private List<Spells> list = new LinkedList<>();
Context context;
public Adapter_Rec(List<Spells> list, Context context)
{
this.context=context;
this.list=list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(context).inflate
(R.layout.spells_recycle,parent,false);
MyViewHolder vholder = new MyViewHolder(v);
return vholder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.check.setOnCheckedChangeListener(null);
holder.name.setText(list.get(position).getName());
holder.benefits.setText(list.get(position).getDescription());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder
{
TextView name;
TextView benefits;
CheckBox check ;
public MyViewHolder(View item)
{ super(item);
name = item.findViewById(R.id.namee);
benefits = item.findViewById(R.id.desc);
check =item.findViewById(R.id.check);
}
}
}
delete isViewFromObject method, or return super.isViewFromObject(view, object);
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object
object) {
//return false; // return false will never show this fragment
return super.isViewFromObject(view, object);
}
I have created tabbed activity, which has viewpager with two instances of one fragment class. This fragment contains listbox, and I have written few functions to
interact with listview items, and one function in activity to do the same thing. The point is when im trying to call fragment methods, it always trying to update the listview of fragment, which was created at first, but when i call function from activity it works absolutely correct. Whats the problem?
Here is the code of activity:
public class CategoriesActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
SparseArray<Fragment> registeredFragments = new SparseArray<>();
Toolbar toolbar;
FloatingActionButton btnAddCategories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
assignElements();
prepareToolbar();
prepareEelements();
}
public void assignElements() {
toolbar = findViewById(R.id.action_bar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
btnAddCategories = findViewById(R.id.btnAddCategory);
// Set up the ViewPager with the sections adapter.
mViewPager = findViewById(R.id.container);
}
public void prepareToolbar() {
toolbar.setTitle("Категории");
toolbar.setTitleTextColor(getResources().getColor(R.color.colorTextLight));
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void prepareEelements() {
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
btnAddCategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TabCategoriesFragment tabCategoriesFragment = (TabCategoriesFragment) getRegisteredFragment(mViewPager.getCurrentItem());
tabCategoriesFragment.addNewCategory();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.home:
finish();
break;
case R.id.homeAsUp:
finish();
break;
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = TabCategoriesFragment.newInstance(false);
break;
case 1:
fragment = TabCategoriesFragment.newInstance(true);
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
}
And of the fragment:
public class TabCategoriesFragment extends Fragment {
private static final String ARG_INCOMING = "Incoming";
private OnFragmentInteractionListener mListener;
public int Incoming = -1;
ListView listView;
ArrayList<Categories> categories;
CategoriesListViewAdapter categoriesListViewAdapter;
DBHelper dbHelper;
SQLiteDatabase sqLiteDatabase;
public TabCategoriesFragment() {
}
public int selectedPostion;
public static TabCategoriesFragment newInstance(boolean Incoming) {
TabCategoriesFragment fragment = new TabCategoriesFragment();
Bundle args = new Bundle();
args.putBoolean(ARG_INCOMING, Incoming);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (getArguments().getBoolean(ARG_INCOMING)) {
Incoming = 1;
} else {
Incoming = 0;
}
}
}
public void assignElements(View view) {
dbHelper = new DBHelper(getContext());
sqLiteDatabase = dbHelper.getWritableDatabase();
categories = new ArrayList<>();
categoriesListViewAdapter = new CategoriesListViewAdapter(getContext(), categories);
}
#SuppressLint("ClickableViewAccessibility")
public void prepareElements() {
filldata();
listView.setAdapter(categoriesListViewAdapter);
categoriesListViewAdapter.notifyDataSetChanged();
registerForContextMenu(listView);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedPostion = position;
getActivity().openContextMenu(listView);
return true;
}
});
}
public void deleteCategory(boolean deletecosts, String name) {
try {
//delete from db
} catch (Exception e) {
Toast.makeText(getContext(), "Произошла ошибка" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public String getTableName() {
if (Incoming == 1) {
return "incomingcategories";
} else {
return "outcomingcategories";
}
}
public String getSign() {
if (Incoming == 1) {
return ">";
} else {
return "<";
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Objects.requireNonNull(getActivity()).getMenuInflater().inflate(R.menu.edit_category_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
//final int selectedPostion = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
int id = item.getItemId();
final CheckBox checkBox = new CheckBox(getContext());
switch (id) {
case R.id.categoryDelete:
deleteCategory(categories.get(selectedPosition);
filldata();
categoriesListViewAdapter.notifyDataSetChanged();
case R.id.categorySetbydefault:
break;
case R.id.categoriesSetBydefault:
setCategoryBydefault(categories.get(selectedPostion).description);
filldata();
categoriesListViewAdapter.notifyDataSetChanged();
break;
}
return true;
}
public void setCategoryBydefault(String name) {
//set
}
#Override
public void onStart() {
super.onStart();
prepareElements();
CategoriesActivity categoriesActivity = (CategoriesActivity) getActivity();
}
public void filldata() {
categories.clear();
//do some stuff
}
public void addNewCategory() {
//do some stuff
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_categories, container, false);
listView = view.findViewById(R.id.CategoriesListView);
assignElements(view);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
I have tried to add a fragment inside another fragment inside viewpager using getChildFragmentManager(). I got following error,
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1549)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:654)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:625)
at com.lakeba.gameon.userprofile.UserProfileContainerFragment.replaceFragment(UserProfileContainerFragment.java:72)
And I tried this workaround but still getting same error.
UserProfileContainerFragment.java
public class UserProfileContainerFragment extends CustomFragment {
private View rootView;
private Fragment fragment1;
public UserProfileContainerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public static UserProfileContainerFragment newInstance() {
UserProfileContainerFragment fragment = new UserProfileContainerFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_user_profile_container, container, false);
if(savedInstanceState == null) {
UserProfileFragment userProfileFragment = UserProfileFragment.newInstance();
getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, userProfileFragment)
.commitAllowingStateLoss();
}
return rootView;
}
/*#Override
public void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}*/
public void replaceFragment(Fragment fragment, boolean addToBackStack){
fragment1 = fragment;
if(addToBackStack){
/*getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, fragment)
.addToBackStack(null)
.commit();*/
getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, fragment)
.addToBackStack(null)
.commit();
//.commitAllowingStateLoss();
}
else{
getChildFragmentManager().beginTransaction()
.replace(R.id.user_profile_container, fragment)
.commit();
//.commitAllowingStateLoss();
}
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
HomeMapActivity.java
public class HomeMapActivity extends AppCompatActivity implements UserProfileFragment.OnUserProfileFragmentListener{
private Toolbar homeToolbar;
private ViewPager homeViewPager;
private TabLayout homeTabLayout;
private UserProfileContainerFragment userProfileContainerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_map);
/*homeToolbar = (Toolbar) findViewById(R.id.home_toolbar);
setSupportActionBar(homeToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/
homeViewPager = (ViewPager) findViewById(R.id.home_view_pager);
HomeViewPagerAdapter homeViewPagerAdapter = new HomeViewPagerAdapter(getSupportFragmentManager());
userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(new UserProfileContainerFragment(),"Profile");
homeViewPager.setAdapter(homeViewPagerAdapter);
homeTabLayout = (TabLayout) findViewById(R.id.home_tabs);
homeTabLayout.setupWithViewPager(homeViewPager);
setTabIcons(homeTabLayout);
homeTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int tabPosition = tab.getPosition();
tab.setIcon(tabIconsArrayActivated[tabPosition]);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
int tabPosition = tab.getPosition();
tab.setIcon(tabIconsArray[tabPosition]);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
int tabPosition = tab.getPosition();
tab.setIcon(tabIconsArrayActivated[tabPosition]);
}
});
homeTabLayout.getTabAt(1).select();
}
private void setTabIcons(TabLayout homeTabLayout) {
homeTabLayout.getTabAt(0).setIcon(tabIconsArray[0]);
homeTabLayout.getTabAt(1).setIcon(tabIconsArray[1]);
homeTabLayout.getTabAt(2).setIcon(tabIconsArray[2]);
homeTabLayout.getTabAt(3).setIcon(tabIconsArray[3]);
}
#Override
public void onUserProfileEditButtonClicked() {
userProfileContainerFragment.replaceFragment(EditUserProfileFragment.newInstance(),true);
}
private class HomeViewPagerAdapter extends FragmentStatePagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public HomeViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
//return mFragmentTitleList.get(position);
return null;
}
public void addFragment(Fragment fragment,String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
}
If you look at the code in your onCreate() method you'll see the lines:
userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(new UserProfileContainerFragment(),"Profile");
You first initialize the userprofileContainerFragment field with a new instance of UserProfileContainerFragment and then right below you create a new instance of UserProfileContainerFragment to be used in the ViewPager(you can easily observe this by placing a log statement in the constructor of UserProfileContainerFragment...you'll see two instances being created). Later in your code you try to use the field userProfileContainerFragment which will lead to a failure as that instance of UserProfileContainerFragment is not attached to the activity at all(this isn't the fragment used by the ViewPager).
Your code should look like below, to maintain the proper reference and not create detached fragments:
userProfileContainerFragment = new UserProfileContainerFragment();
homeViewPagerAdapter.addFragment(userProfileContainerFragment,"Profile");
I'm new to Android programming.
I googled & stackoverflowed, read android docs but nothing helped me or maybe I didn't understand well.
I'm trying to AsyncTask UI to fragment via onPageSelected from ViewPager.
Like AndroMoney app ViewPager(Before onPageSelected, it shows "loading...", when onPageSelected, it AsyncTasked and loaded.):
AndroMoney ViewPager Fragment Screenshoot
but my code is: it asynctasked while swipping and sometimes it stops between two fragments like this:
my code viewpager screenshot
unlike AndroMoney app, my code doesn't asynctask onPageSelected.
here is MyFragment.java:
public class MyFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
final StringBuilder buffer=new StringBuilder();
View v;
public static final MyFragment newInstance(int message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putInt(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.myfragment_layout, container, false);
new AsyncDatabase().execute();
return v;
}
public class AsyncDatabase extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params){
int message = getArguments().getInt(EXTRA_MESSAGE);
BibleService bService=new BibleServiceImpl(getActivity().getApplication());
List<Bible> bible=bService.getBibleByChapterNumber("Salm", message);
for(Bible b: bible){
for(int i=0;i<10;i++){
buffer.append(b);
}
}
return null;
}
#Override
protected void onPostExecute(Void result){
TextView txt1=(TextView)v.findViewById(R.id.textView1);
TextView txt2=(TextView)v.findViewById(R.id.textView2);
txt1.setText("Done");
txt2.setText(buffer.toString());
}
#Override
protected void onPreExecute(){
TextView txt1=(TextView)v.findViewById(R.id.textView1);
txt1.setText("Loading...");
}
#Override
protected void onProgressUpdate(Void... values){
}
}
}
here is PageViewActivity.java:
public class PageViewActivity extends FragmentActivity{
MyPageAdapter pageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setOffscreenPageLimit(1);
pager.setAdapter(pageAdapter);
pager.setCurrentItem(11);
pager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
public void onPageSelected(int position) {
}
});
}
private List<Fragment> getFragments() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int j = 2; j < 150; j++) {
fList.add(MyFragment.newInstance(j));
}
return fList;
}
private class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
I tested stupidly by adding the following code:
public void onPageSelected(int position) {
new MyFragment().new AsyncDatabase().execute();
}
It didn't work.:-P
So, how to asynctask to fragment from onPageSelected of PageViewActivity like AndroMoney app.
Expose a new method in your fragment:
public void executeAsyncTask() {
new AsyncDatabase().execute();
}
In the activity, make your list of fragments final, so you can access it in the Adapter:
final List<MyFragment> fragments = getFragments();
Then change your onPageSelected() method to be:
public void onPageSelected(int position) {
fragments.get(position).executeAsyncTask();
}
You'll also need to update the MyPagerAdapter to use MyFragment instead of Fragment:
private class MyPageAdapter extends FragmentStatePagerAdapter {
private List<MyFragment> fragments;
public MyPageAdapter(FragmentManager fm, List<MyFragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
private List<MyFragment> getFragments() {
List<MyFragment> fList = new ArrayList<MyFragment>();
for (int j = 2; j < 150; j++) {
fList.add(MyFragment.newInstance(j));
}
return fList;
}
I'm in the process of setting up a DrawerItemClickListener however I'm getting an error stating: DrawerItemClickListener cannot be resolved to a type even though I declare the method further down in the code. I've looked it over several times and I do not see what I have done wrong.
private void _initMenu() {
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(this, Player.class);
intent.putExtra("id", video.getId());
intent.putExtra("title", video.getTitle());
intent.putExtra("uploader", video.getUploader());
intent.putExtra("viewCount", video.getviewCount());
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn,
R.drawable.island_up_btn, R.drawable.latin_up_btn,
R.drawable.pop_up_btn, R.drawable.samba_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP", "TimMcGrawVEVO", "TiestoVEVO",
"EminemVEVO" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
drawerListView.setItemChecked(position, true);
String text = "menu click... should be implemented";
Toast.makeText(Home.this, text, Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
}
}
You need to create class DrawerItemClickListener implements ListView.OnItemClickListener
Full example and explanation in Android docs https://developer.android.com/training/implementing-navigation/nav-drawer.html#ListItemClicks
the fragment from it:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
Move the DrawerItemClickListener class out of the ImagePagerAdapter class as at present it is not visible.
Your listener object is defined inside ImagePagerAdapter class, it won't be accessible in its parent class.
You can move DrawerItemClickListener to its parent class, then it should be accessible:
private void _initMenu() {
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// do your thing
}
}