Replacing one fragment with another fragment in viewpager - android

I am having trouble showing my new fragment . Basically what i doing is i have a viewpager having 3 pages , in the second page i m hiding the current fragment and adding a new one. Everything goes perfectly except that i can't see my new fragment.
My Mainactivity.java
public class MainActivity extends AppCompatActivity {
ViewPager viewPager = null;
NavigationDrawerFragement drawerFragement;
Bitmap image = null;
int notificationExtra = 0;
int nid=0;
Toolbar toolbar;
private void startGetLocationService() {
Intent i = new Intent(this, GetUserLocationService.class);
startService(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_register);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
drawerFragement = (NavigationDrawerFragement) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragement.setUp((DrawerLayout) findViewById(R.id.drawer_layout),toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
//getSupportActionBar().setIcon(R.drawable.account);
getSupportActionBar().setTitle("Eventyze");
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
fragment = new ReminderFragment();
if (i == 1)
fragment = new EventFragment();
if (i == 2)
fragment = new InvitationFragment();
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0)
return "Reminders";
if (position == 1)
return "Events";
if (position == 2)
return "Invitations";
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
#Override
protected void onResume() {
super.onResume();
if(notificationExtra==1){
viewPager.setCurrentItem(2);
}
}
}
the onclick in my 2nd page .
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
InvitedEventsFragment fragment2 = new InvitedEventsFragment();
fragmentTransaction2.hide(EventFragment.this);
fragmentTransaction2.add(R.id.viewpager, fragment2);
fragmentTransaction2.commit();
My InvitedEventsFragment.java
public class InvitedEventsFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_invited_events_fragment, container, false);
}
return view;
} }
My activity_invited_events_fragment.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black">
<Button
android:id="#+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/appbarcol2"
android:text="New Fragment"
android:textAllCaps="true"
android:textColor="#android:color/white"
android:textStyle="bold" /> </LinearLayout>
Can someone tell me why it doesn't show anything i the new fragment.

If you're using a ViewPager, the adapter should manage the Fragments.
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import java.util.List;
public class ExampleAdapter extends FragmentPagerAdapter
{
List<Fragment> fragmentList;
public ExampleAdapter(FragmentManager fm, List<Fragment> fragmentList)
{
super(fm);
this.fragmentList = fragmentList;
}
#Override public Fragment getItem(int position)
{
return fragmentList.get(position);
}
#Override public int getCount()
{
return fragmentList.size();
}
public void removeItem(int position, ViewPager pager)
{
pager.setAdapter(null);
this.fragmentList.remove(position);
pager.setAdapter(this);
}
}

Related

how to override and display title of tabs in viewpager2 in tablayout

I am using a TabLayout inside a Fragment. The content of the TabLayout (made of 2 fragments) is displayed but not the title of the tabs. I believe it's a layout problem but i'm not sure on how to fix it.
Also what would be the overrided method for ViewPager2 that was used in ViewPager (getPagetitle) ?
main Fragment
public class CommunityFragment extends Fragment {
private TabLayout tbL;
private ViewPager2 vp;
private RecipeViewPagerAdapter rvpa;
public CommunityFragment() {
// Required empty public constructor
}
public static CommunityFragment newInstance(){
return new CommunityFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_community, container, false);
tbL = rootView.findViewById(R.id.tabL);
vp = rootView.findViewById(R.id.pager);
rvpa = new RecipeViewPagerAdapter(this);
vp.setAdapter(rvpa);
rvpa.addFragment(new AllFragment(),"All time");
rvpa.addFragment(new DayFragment(),"Today");
new TabLayoutMediator(tbL, vp, new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
//////title????
}
}).attach();
return rootView;
}
}
Adapter
public class RecipeViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> listF = new ArrayList<>();
private ArrayList<String> listT = new ArrayList<>();
public RecipeViewPagerAdapter(#NonNull Fragment fragment) {
super(fragment);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return listF.get(position);
}
//new method ????
public CharSequence getPageTitle(int position){
return listT.get(position);
}
#Override
public int getItemCount() {
return listT.size();
}
public void addFragment(Fragment frag, String title){
listF.add(frag);
listT.add(title);
}
}
fragment layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".fragments.CommunityFragment">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
app:tabIndicatorColor="#color/yellowCool"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
put this in your main activity....
myAdapter=new FragmentAdapter(this);
myViewPager2.setAdapter(myAdapter);
String [] tabTtiles={"Home","Chat","Notification","Account"};
new TabLayoutMediator(myTabLayout, myViewPager2,(myTabLayout, position) ->
myTabLayout.setText(tabTtiles[position])).attach();
Your tabLayout doesn't display. Use this:
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" // add this line
/>
TabLayoutMediator:
new TabLayoutMediator(tbL, vp, new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
if(position == 0)
tab.setText("All time");
else
tab.setText("Today");
}
}).attach();
You can use the following adapter for the viewPager2:
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 10;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull #Override public Fragment createFragment(int position) {
return CardFragment.newInstance(position);
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
}
on the mainActivity you need to have something inline with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
}
}
As per documentation:
The TabLayoutMediator object also handles the task of generating page
titles for the TabLayout object, which means that the adapter class
does not need to override getPageTitle():
And to do that:
TabLayout tabLayout = view.findViewById(R.id.tab_layout);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText("OBJECT " + (position + 1))
).attach();

Hide AppBarLayout using toolbar in fragment in Android

This is my manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
This is my some part of MainActivity.java
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment,recepie_fragment,products_fragment,swadeshi_fragment,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_yash);
//setSupportActionBar(toolbar);
//setSupportActionBar(null);
// final View ab=(View)findViewById(R.id.appbarmain);
fragmentManager = getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
recepie_fragment=new Recepie_Fragment();
products_fragment=new Products_Fragment();
swadeshi_fragment=new Swadeshi_Fragment();
fragment=recepie_fragment;//new Fragment();
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
previous=fragment;
BottomBar bb=BottomBar.attach(this,savedInstanceState);
bb.setActiveTabColor("RED");
bb.setItemsFromMenu(R.menu.bottom_buttons, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(int menuItemId) {
fragmentTransaction=fragmentManager.beginTransaction();
switch(menuItemId)
{
case R.id.button1:
previous=fragment;
// ab.setAlpha(0);
fragment=recepie_fragment;//new Recepie_Fragment();
// fragment.setRetainInstance(true);
break;
case R.id.button2:
//getSupportActionBar().show();
previous=fragment;
fragment=products_fragment;//new Products_Fragment();
//fragment.setRetainInstance(true);
break;
case R.id.button3:
previous=fragment;
//getSupportActionBar().show();
fragment=swadeshi_fragment;//new Swadeshi_Fragment();
//fragment.setRetainInstance(true);
break;
}
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
}
});
}
Here is my RecepieFragment.java
public class Recepie_Fragment extends Fragment {
View rootView;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
int logo_ids[]={R.drawable.main_course,R.drawable.cakes,R.drawable.specials};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void setupTabIcons()
{
tabLayout.getTabAt(0).setIcon(logo_ids[0]);
tabLayout.getTabAt(1).setIcon(logo_ids[1]);
tabLayout.getTabAt(2).setIcon(R.drawable.extra);
// tabLayout.getTabAt(1).setCustomView();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//getActivity().getApplication().setTheme(R.style.AppTheme_NoActionBar);
rootView=inflater.inflate(R.layout.recepie_viewpager, container, false);
//getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
toolbar=(Toolbar)rootView.findViewById(R.id.toolbar_yash);
// ((AppCompatActivity) getActivity()).findViewById(R.id.toolbar_yash).animate().translationY(-(R.id.toolbar_yash).getBottom()).setInterpolator(new AccelerateInterpolator()).start();
viewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
setRetainInstance(true);
viewPager.setOffscreenPageLimit(3);
tabLayout = (TabLayout)rootView. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
//actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
private int previousState, currentState;
#Override
public void onPageScrollStateChanged(int state) {
int currentPage = viewPager.getCurrentItem(); //ViewPager Type
if (currentPage == 2 || currentPage == 0) {
previousState = currentState;
currentState = state;
if (previousState == 1 && currentState == 0) {
viewPager.setCurrentItem(currentPage == 0 ? 2 : 0);
}
}
}
});
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());//(getActivity().getSupportFragmentManager());
adapter.addFrag(new Main_Course(), "");
adapter.addFrag(new Cakes(), "");
adapter.addFrag(new Specials(), "");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter 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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
And this the xml file i am using :
tools:context=".activity.activity.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appbarmain"
android:theme="#style/AppTheme.NoActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_yash"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Below type of visualisation is created when I'm trying to hide the toolbar/actionbar in recepies fragment. What I want is whenever I move into products or swadeshi fragment I get this action bar but when in recepie fragment my actionbar hides and screen consists of my viewpager of 3 elements as shown of cake but instead a blank is created.

Fragment null when call function viewpager

My Fragment class:
onCreatedView:
parentActivity = (MainActivity) getActivity();
parentView = inflater.inflate(R.layout.fragmentla, container, false);
mFragmentAdapter = new myFragmentAdapter(parentActivity.getSupportFragmentManager(), parentView.getContext());
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) parentView.findViewById(R.id.viewpager);
viewPager.setAdapter(mFragmentAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) parentView.findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
Thats my fragment (Blue border). My fragment contains toolbar, tablayout, and viewpager.
My FragmentAdapter class:
public class myFragmentAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "ITEM1", "ITEM2" };
private Context context;
public myFragmentAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return FirstFragment.newInstance(position + 1);
} else {
return SecondFragment.newInstance(position + 1);
}
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
And this is my FirstFragment class:
public static FirstFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
FirstFragment fragment = new FirstFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentView = inflater.inflate(R.layout.fragment_first_newest, container, false);
sometext = (TextView) parentView.findViewById(R.id.wi_my_text);
return parentView;
}
So, my question is: Everytime that I press my menu button in toolbar the textview should change, but this return null cause "onCreatedView" is not called anymore. I tried with this in Fragment class:
public boolean onOptionsItemSelected(MenuItem item){
...
Fragment mFragment = mFragmentAdapter.getItem(0);
if(mFragment instanceof FirstFragment){
((FirstFragment) mFragment).OnButtonPressed();
}
}
Then on my FirstFragment but still getting null exception:
public void OnButtonPressed() {
someText.setText("its working");
createLocationRequest();
}
UPDATED: MY XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:id="#+id/wi_my_text"
android:layout_height="24dp"
android:layout_gravity="center"
android:gravity="center"
android:textStyle="bold"
android:paddingEnd="5dp"
android:text="texttest"/>
</LinearLayout>

ViewPager inside a

I have an activity that has a viewpager fragment in it
one of the pages has another viewpager fragment in it
the problem is, when i reach the page of the inner viewpager fragment, the "onCreateView" of the inner viewpager fragments doesnt get called, and so the page is blank.
Why is that ?
here is my code :
fragment_viewpager.xml
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
fragment_viewpager_with_logo.xml
<include layout="#layout/logo" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
public class ViewPagerFragment extends Fragment {
private ViewPager fragmentPager;
private PagerAdapter fragmentAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container instanceof ViewPager) {
return inflater.inflate(R.layout.fragment_viewpager_with_logo, container, false);
}
return inflater.inflate(R.layout.fragment_viewpager, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fragmentPager = (ViewPager)getView().findViewById(R.id.pager);
fragmentPager.setAdapter(fragmentAdapter);
}
public void setAdapter(PurchaseFragmentStatePagerAdapter fragmentAdapter) {
this.fragmentAdapter = fragmentAdapter;
}
public void setCurrentItem(int i) {
fragmentPager.setCurrentItem(i);
}
public int getCurrentItem() {
return fragmentPager.getCurrentItem();
}
public void setOnPageChangeListener(OnPageChangeListener l) {
if (fragmentPager == null) {
fragmentPager = (ViewPager) getView().findViewById(R.id.pager);
}
fragmentPager.setOnPageChangeListener(l);
}
}
in some activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
MyFragmentStatePagerAdapter fragmentAdapter = new MyStatePagerAdapter(getSupportFragmentManager());
List<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(settingsFragment);// settings
ViewPagerFragment vpFragment = new ViewPagerFragment();
fragments.add(vpFragment);
fragmentAdapter.setFragments(fragments);
fragmentPager.setAdapter(fragmentAdapter);
MyFragmentStatePagerAdapter innerFragmentAdapter = new MyFragmentStatePagerAdapter(getSupportFragmentManager());
List<Fragment> innerFragments = new ArrayList<Fragment>();
innerFragments.add(settingsFragment);
innerFragmentAdapter.setFragments(innerFragments);
vpFragment.setAdapter(innerFragmentAdapter);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.content_fragment, fragmentPager).commit();
}
MyFragmentStatePagerAdapter
public class MyFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
private List<BaseFragment> fragments;
#Inject
public MyFragmentStatePagerAdapter(FragmentManager fm) {
super(fm);
}
public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
#Override
public BaseFragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments == null ? 0 : fragments.size();
}
}
In the Fragment use fragment.getChildFragmentManager() in FragmentPagerAdapter's constructor instead of getActivity().getFragmentManager()

PullToRefresh list in paged fragment

I want to create PullToRefresh list fragment with pager.
I'm using ActionBarSherlock, and this implementation of the list. I had no problems without fragment, but I need to support two-pane layout.
layout files
activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SubcatNavActivity" />
</LinearLayout>
fragment
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/subcat_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Activity is pretty simple
public class SubcatNavActivity extends SherlockFragmentActivity
{
private SubcatNavPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_subcat_nav);
mPager = new SubcatNavPager(this);
mPager.initialisePaging();
setProgressBarIndeterminateVisibility(true);
}
}
I have created pager class to also use it later in main activity for two-pane mode.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class SubcatNavPager implements ActionBar.TabListener
{
public SectionsPagerAdapter mSectionsPagerAdapter;
public ViewPager mViewPager;
private SherlockFragmentActivity mFragmentActivity;
public SubcatNavPager(SherlockFragmentActivity fa) {
mFragmentActivity = fa;
}
public void initialisePaging() {
mFragmentActivity.setTitle(mFragmentActivity.getResources().getString(SiteContent.curr_cat.nameID));
try {
List<Fragment> fragments = new Vector<Fragment>();
mSectionsPagerAdapter = new SectionsPagerAdapter(mFragmentActivity.getSupportFragmentManager(), fragments);
for (int i = 0; i < SiteContent.curr_cat.content.size(); ++i) {
Fragment tmp = SiteContent.curr_cat.fragment.newInstance();
if (!(tmp instanceof ContentDownloader)) {
throw new IllegalStateException(
"Fragment must implement content downloader interface.");
}
Bundle args = new Bundle();
args.putInt(SubcatListFragment.SUBCAT_IDX, i);
tmp.setArguments(args);
fragments.add((Fragment)tmp);
}
mViewPager = (ViewPager)mFragmentActivity.findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
final ActionBar actionBar = mFragmentActivity.getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
actionBar.setDisplayHomeAsUpEnabled(true);
}
catch (Exception e) {}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
int pos = tab.getPosition();
SiteContent.setCurrSubCat(pos);
mViewPager.setCurrentItem(pos);
((ContentDownloader)mSectionsPagerAdapter.getItem(pos)).downloadContent(false);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
private List<Fragment> fragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fList) {
super(fm);
fragments = fList;
}
#Override
public Fragment getItem(int position) {
Fragment tmp = fragments.get(position);
return tmp;
}
#Override
public int getCount() { return fragments.size(); }
#Override
public CharSequence getPageTitle(int position) {
return mFragmentActivity.getResources().getString(SiteContent.curr_cat.content.get(position).nameID);
}
}
}
And finally, the fragment itself
import com.actionbarsherlock.app.SherlockListFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class SubcatListFragment extends SherlockListFragment implements ContentDownloader
{
public static final String SUBCAT_IDX = "subcat_idx";
protected ArrayAdapter<SiteItem> adapter;
protected DownloadSubcatTask loadTask;
protected SiteSubcat subcat;
private PullToRefreshListView mPullToRefreshListView;
private boolean loadRequested;
public SubcatListFragment() {
adapter = null;
loadRequested = false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
subcat = SiteContent.curr_cat.content.get(args.getInt(SUBCAT_IDX));
adapter = new ArrayAdapter<SiteItem>(getActivity(), android.R.layout.simple_list_item_1, subcat.items);
this.setListAdapter(adapter);
if (loadRequested == true)
downloadContent(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_subcat_nav, container, false);
ListView lv = (ListView) layout.findViewById(R.id.subcat_list);
ViewGroup parent = (ViewGroup) lv.getParent();
int lvIndex = parent.indexOfChild(lv);
parent.removeViewAt(lvIndex);
mPullToRefreshListView = new PullToRefreshListView(layout.getContext());
mPullToRefreshListView.setMode(Mode.BOTH);
mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>()
{
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
downloadContent(true);
}
});
parent.addView(mPullToRefreshListView, lvIndex, lv.getLayoutParams());
return layout;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent subcatIntent = new Intent(getActivity(), NewsActivity.class);
SiteContent.setCurrItem((int)id);
startActivity(subcatIntent);
}
#Override
public void downloadContent(boolean bRefresh) {
// on first call to onTabSelected this fragment is not created, yet
if (subcat == null)
loadRequested = true;
else
{
loadRequested = false;
if (loadTask == null && (adapter.isEmpty() == true || bRefresh == true))
(loadTask = new DownloadSubcatTask()).execute(subcat.getUrl());
}
}
protected void showProgress(boolean bShow) {
getActivity().setProgressBarIndeterminateVisibility(bShow);
}
private class DownloadSubcatTask extends DownloadTask {
public DownloadSubcatTask() {}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress(true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter.clear();
loadTask = null;
try {
SiteContent.curr_cat.parser.newInstance().parse(result, adapter);
}
catch (Exception e) {}
mPullToRefreshListView.onRefreshComplete();
adapter.notifyDataSetChanged();
showProgress(false);
}
}
}
As you can see, everything consists of stuff from examples. But the problem is that list is not shown when I start the app. I can see the tabs, the loading indicator is gone (and I know adapter has data) but list area is clear white. And I can't pull the list to refresh it. But if i try to swap pages, suddenly data appears in previous page (actually not previous, but the one before). It seems it has something to do with adapter loading first two fragments, but I can figure out what's wrong.
How to make lists appears when they are loaded?
And more general question, is this the right architecture to go on?
EDIT:
if I remove all pull-to-refresh code like this
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View layout = inflater.inflate(R.layout.fragment_subcat_nav, container, false);
return layout;
}
and set default list id in the fragment layout android:id="#android:id/list" list view is displayed as it should. can't figure out why pull-to-refresh causes problems.
this is how i fixed the problem (list fragment need to return a list view)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_subcat_nav, container, false);
ListView lv = (ListView) layout.findViewById(android.R.id.list);
mPullToRefreshListView = new PullToRefreshListView(getActivity());
mPullToRefreshListView.setLayoutParams(lv.getLayoutParams());
mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>()
{
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
downloadContent(true);
}
});
return mPullToRefreshListView;
}

Categories

Resources