PullToRefresh list in paged fragment - android

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

Related

Android view pager not displaying Fragment when it is called again

I have a slider menu in my application, when I click on an item in the menu it displays the corresponding fragment. That fragmet has a tablayout and a viewpager. The Fragment xml is given below
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:background="#color/colorPrimary"
app:tabSelectedTextColor="#color/textColorPrimary"
app:tabTextColor="#color/colorAccent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_below="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
Below given is the code snippet of the fragment clicked on the slider menu
public class MyCoursesFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
public MyCoursesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new ScheduledFragment(), "SCHEDULED");
adapter.addFragment(new LiveStreamingFragment(), "LIVE STREAMING");
adapter.addFragment(new UpcomingFragment(), "UPCOMING");
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("mlearning", "inside my course");
View rootView = inflater.inflate(R.layout.fragement_courses, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
There are three tabs in the above fragment. The xml for each fragment contains a list view, the xml is given below.
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvList"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:backgroundTint="#888686" />
The code for the tablayout fragment is given below:
public class ScheduledFragment extends Fragment {
public ScheduledFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("mlearning", "inside scheduled");
View rootView = inflater.inflate(R.layout.fragment_scheduled, container, false);
ArrayList<CoursePojo> searchResults = GetSearchResults();
final ListView lv1 = (ListView) rootView.findViewById(R.id.lvList2);
lv1.setAdapter(new MyCustomCourseList(getActivity(), searchResults));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
CoursePojo fullObject = (CoursePojo) o;
//Toast.makeText(getBaseContext(), "You have chosen: " + " " + fullObject.getId(), Toast.LENGTH_LONG).show();
}
});
return rootView;
}
private ArrayList<CoursePojo> GetSearchResults(){
ArrayList<CoursePojo> results = new ArrayList<CoursePojo>();CoursePojo coursePojo3=new CoursePojo();
coursePojo3.setName("Android");
coursePojo3.setDesc("First os was released without a phone ");
coursePojo3.setStartdate("20 Mar");
coursePojo3.setEndDate("8 Apr");
coursePojo3.setProgress("40");
results.add(coursePojo3);
// Inflate the layout for this fragment
return results;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}}
Initially when I click on the menu fragment, the values in the tab fragment comes as it is mentioned in the code. But if I again tap on the menu slider the items in the tab layout are not displaying.And also some tabs empty or some tabs are having some value. Where am I going wrong?
Use FragmentStatePagerAdapter instant of FragmentPagerAdapter.
Try populating data in List inside onResume()

Replacing one fragment with another fragment in viewpager

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

How to enable CardView in ViewPager

I have tried using CardView in ViewPager and everytime I swipe left/right on CardView it goes to the next screen. I want the card to delete itself then. Currently as a standalone both are working fine but when I combine then only viewpager is working and not cardswipe dismiss.
I tried to disable ViewPager with the code below but this code also disables CardView swipe gestures. How can I make only CardView to have gesture and when you swipe in between 2 cards then its should have ViewPager as its not connected to card element.
Or disable ViewPager completely and use it as buttons and enable swipe on CardView. I really appreciate any help. Thanks in Advance.
FYI: I have tried android_horizontal_listview in ViewPager and that works fine and exactly like this.
For ViewPager:
mPager.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
For CardView:
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(mRecyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
});
mRecyclerView.addOnItemTouchListener(swipeTouchListener);
Mainactivity.java
public class MainActivity extends Activity implements ActionBar.TabListener {
ViewPager vp;
View viewpager_layout_1;
View viewpager_layout_2;
View viewpager_layout_3;
ActionBar.Tab tab_1;
ActionBar.Tab tab_2;
ActionBar.Tab tab_3;
ActionBar bar;
/////
String jsonstring1;
CardViewAdapter spinnerArray;
ImageLoader imageLoader = ImageLoader.getInstance();//
DisplayImageOptions options;
ArrayList<HashMap<String, String>> array_list1;
RecyclerView recyclerView;
RelativeLayout re1;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mContext = this;
viewpager_layout_1 = new View(mContext);
viewpager_layout_1 = getLayoutInflater().inflate(R.layout.sample1, null);
viewpager_layout_3 = new View(mContext);
viewpager_layout_3 = getLayoutInflater().inflate(R.layout.sample2, null);
viewpager_layout_2 = new View(mContext);
viewpager_layout_2 = getLayoutInflater().inflate(R.layout.sample3, null);
vp = (ViewPager) findViewById(R.id.vp);
bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
Vector<View> pages = new Vector<View>();
pages.add(viewpager_layout_1);
pages.add(viewpager_layout_3);
pages.add(viewpager_layout_2);
CustomPagerAdapter adapter = new CustomPagerAdapter(mContext, pages);
vp.setAdapter(adapter);
vp.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
bar.setSelectedNavigationItem(position);
}
});
tab_1 = bar.newTab();
tab_1.setCustomView(R.layout.tab_layout_1);
tab_1.setTabListener(this);
bar.addTab(tab_1);
tab_2 = bar.newTab();
tab_2.setCustomView(R.layout.tab_layout_2);
tab_2.setTabListener(this);
bar.addTab(tab_2);
tab_3 = bar.newTab();
tab_3.setCustomView(R.layout.tab_layout_3);
tab_3.setTabListener(this);
bar.addTab(tab_3);
////
imageLoader.init(ImageLoaderConfiguration.createDefault(MainActivity.this));
jsonstring1 = "[{\"category\":\"1\",\"no\":\"1\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/c/c3/Jordan_by_Lipofsky_16577.jpg\"},{\"category\":\"2\",\"no\":\"2\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/Basketball_World_Cup_2014.jpg/800px-Basketball_World_Cup_2014.jpg\"},{\"category\":\"3\",\"no\":\"3\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/4/4e/Basketball_Goal.jpg\"},{\"category\":\"4\",\"no\":\"4\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/1/10/Basketball_through_hoop.jpg\"}]";
//////////
array_list1 = new ArrayList<HashMap<String, String>>();
JSONArray arr = null;
try {
arr = new JSONArray(jsonstring1);
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
String category = e1.getString("category").trim();
String no = e1.getString("no").trim();
String image = e1.getString("image").trim();
HashMap<String, String> map = new HashMap<String, String>();
map.put("category", category);
map.put("no", no);
map.put("image", image);
// adding HashList to ArrayList
array_list1.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OnItemTouchListener itemTouchListener = new OnItemTouchListener() {
#Override
public void onCardViewTap(View view, int position) {
Toast.makeText(MainActivity.this, "Tapped " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton1Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button1 in " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton2Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button2 in " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
};
spinnerArray = new CardViewAdapter(itemTouchListener, MainActivity.this, array_list1);
recyclerView = (RecyclerView) viewpager_layout_3.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
SlideInBottomAnimationAdapter alphaAdapter = new SlideInBottomAnimationAdapter(spinnerArray);
ScaleInAnimationAdapter alphaAdapter2 = new ScaleInAnimationAdapter(alphaAdapter);
final AlphaInAnimationAdapter alphaAdapter3 = new AlphaInAnimationAdapter(alphaAdapter2);
alphaAdapter3.setDuration(500);
alphaAdapter3.setFirstOnly(true);
recyclerView.setAdapter(alphaAdapter3);
final SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(recyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// mItems.remove(position);
Toast.makeText(MainActivity.this, array_list1.get(position) + " swiped left", Toast.LENGTH_SHORT).show();
array_list1.remove(position);
alphaAdapter3.notifyItemRemoved(position);
}
alphaAdapter3.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
//
Toast.makeText(MainActivity.this, array_list1.get(position) + " swiped right", Toast.LENGTH_SHORT).show();
array_list1.remove(position);
alphaAdapter3.notifyItemRemoved(position);
}
alphaAdapter3.notifyDataSetChanged();
}
});
recyclerView.addOnItemTouchListener(swipeTouchListener);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
vp.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 2) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_2);
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_1);
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_33);
} else if (tab.getPosition() == 1) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_22);
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_1);
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_3);
} else if (tab.getPosition() == 0) {
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_11);
if (tab_2 != null) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_2);
}
if (tab_3 != null) {
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_3);
}
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
}
public interface OnItemTouchListener {
// this will disallow the touch request for parent scroll on touch of child view
/**
* Callback invoked when the user Taps one of the RecyclerView items
*
* #param view the CardView touched
* #param position the index of the item touched in the RecyclerView
*/
public void onCardViewTap(View view, int position);
/**
* Callback invoked when the Button1 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton1Click(View view, int position);
/**
* Callback invoked when the Button2 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton2Click(View view, int position);
}
public class CustomPagerAdapter extends PagerAdapter {
private final Context mContext;
private final Vector<View> pages;
public CustomPagerAdapter(Context context, Vector<View> pages) {
this.mContext = context;
this.pages = pages;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View page = pages.get(position);
container.addView(page);
return page;
}
#Override
public int getCount() {
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
ArrayList<HashMap<String, String>> d;
Activity a;
private List<String> cards;
private OnItemTouchListener onItemTouchListener2;
public CardViewAdapter(OnItemTouchListener onItemTouchListener, Activity a, ArrayList<HashMap<String, String>> d) {
// this.cards = cards;
this.onItemTouchListener2 = onItemTouchListener;
this.a = a;
this.d = d;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_layout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
// viewHolder.title.setText(cards.get(i));
HashMap<String, String> item = d.get(i);
viewHolder.title.setText(item.get("category"));
imageLoader.displayImage(item.get("image"), viewHolder.im2);
}
#Override
public int getItemCount() {
// return d == null ? 0 : d.size();
return (null != d ? d.size() : 0);
// return d.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
MotionEvent motionEvent;
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
// private RecyclerView mRecyclerView;
private SwipeableRecyclerViewTouchListener.SwipeListener mSwipeListener;
// Transient properties
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
private int mDismissAnimationRefCount = 0;
private float mAlpha;
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private int mAnimatingPosition = ListView.INVALID_POSITION;
private View mDownView;
private boolean mPaused;
private float mFinalDelta;
///
private TextView title;
private Button button1;
private Button button2;
private ImageView im2;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.card_view_title);
im2 = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativelayout_1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:id="#+id/linearlayout_1"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
</RelativeLayout>
sample2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/re1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
To solve this issue I used an ItemTouchHelper provided by Android to easily swipe to delete an item from a RecyclerView.
Please see implementation below:
MainActivity:
Here I have the implementation of the ViewPager and it's child Fragments.
package za.co.gadgetgirl.testcardpager;
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.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
Frag1 frag1 = new Frag1();
Frag2 frag2 = new Frag2();
Frag3 frag3 = new Frag3();
adapter.addFragment(frag1, "frag1");
adapter.addFragment(frag2, "frag2");
adapter.addFragment(frag3, "frag3");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
Frag1:
On this Fragment I have a RecyclerView that has an ItemTouchHelper attached. The ItemTouchHelper listens for the onSwiped(...) method that is defined in the SimpleCallback interface and I just remove the swiped item in this method.
package za.co.gadgetgirl.testcardpager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Frag1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag1, container, false);
final RecyclerView rv = (RecyclerView) v.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
final RVAdapter rvAdapter = new RVAdapter(Person.initializeData());
rv.setAdapter(rvAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
rvAdapter.removeItem(viewHolder.getAdapterPosition());
}
});
itemTouchHelper.attachToRecyclerView(rv);
return v;
}
}
RVAdapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
//...implementation...
public void removeItem(int position) {
persons.remove(position);
notifyItemRemoved(position);
}
}
To use the ItemTouchHelper, you will need the appcompat-v7:22.2.0 dependency and above defined in your app gradle file.
I haven't use SwipeableRecyclerView before so I cannot really say much. I have a problem same as you before. I solve it by handling onTouch event of the base container of fragment (such as LinearLayout,RelativeLayout) and it work for me. Why don't you try this solution and get back to us
For the use case that you are describing, I don't think that ViewPager is the class that you want to use to get your swipe action. It seems to me that the combination of CoordinatorLayout and SwipeDismissBehavior is more appropriate.
EDIT:
See my solution below:
Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
Activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CardView cardView = (CardView) findViewById(R.id.cardView);
SwipeDismissBehavior<CardView> behavior = new SwipeDismissBehavior();
behavior.setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_START_TO_END);
behavior.setListener(new SwipeDismissBehavior.OnDismissListener() {
#Override
public void onDismiss(View view) {
finish(); // close activity if desired
}
#Override
public void onDragStateChanged(int state) {
}
});
((CoordinatorLayout.LayoutParams) cardView.getLayoutParams()).setBehavior(behavior);
}
}
Also, here are some examples of using the CoordinatorLayout:
How to use SwipeDismissBehavior.OnDismissListener on RecyclerView
CoordinatorLayout using the ViewPager's RecyclerView
https://lab.getbase.com/introduction-to-coordinator-layout-on-android/
http://android-developers.blogspot.co.uk/2015/05/android-design-support-library.html
I haven't been able to find many examples using SwipeDismissBehavior specifically, but the concepts are similar to the links above.
Alternatively, you may also be able to follow the suggestions of a similar post:
Android swipe layout to dismiss to get the results you desire.
Hope this helps.

ViewPager in inner fragment, not showing up, not visible

Im using an ActionBar, which loads different Fragments. This is done within a FragmentActivity class. One of the Fragent should have a ViewPager holding different Fragments.
I dont get any error anymore now, but the ViewPager and the PagerTitleStrip and all the Fragents inside the ViewPager are not shown up at all. The other Fragments from the ActionBar working properly. Im using all classes from the Support-Package.
I rdid read a lot of posts here, but I couldnt find it out yet.
In my ActivityClass derived from FragmentAcivity, I use the Listener:
SettingsActiviy.java
protected class SettingsTabsListener implements ActionBar.TabListener {
private Fragment fragment;
public SettingsTabsListener(Fragment fragment) {
this.fragment = fragment;
Log.e("SettingsTabListener","Contructor Fragment is " + fragment);
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction xaction=fragMgr.beginTransaction();
// Dont know if we really need that...
if (fragment instanceof SettingsActivityOverviewFragment) {
if (fragment == null) {
fragment = SettingsActivityOverviewFragment.newInstance(appWidgetId);
}
}
xaction.replace(R.id.FragmentPlaceholder, (Fragment)fragment);
xaction.commit();
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction xaction=fragMgr.beginTransaction();
xaction.remove(fragment);
xaction.commit();
}
SettingsActivityOverviewFragment.java
public class SettingsActivityOverviewFragment extends Fragment {
private static final Field sChildFragmentManagerField;
ViewPager viewPager;
PagerAdapter pagerAdapter;
public static final SettingsActivityOverviewFragment newInstance(int appWidgetId){
SettingsActivityOverviewFragment f = new SettingsActivityOverviewFragment();
Bundle bdl = new Bundle(1);
bdl.putInt("appWidgetId", appWidgetId);
f.setArguments(bdl);
return f;
}
/* this is a fix caused by googles nullpointer, until detach-method */
static {
Field f = null;
try {
f = Fragment.class.getDeclaredField("mChildFragmentManager");
f.setAccessible(true);
} catch (NoSuchFieldException e) {
}
sChildFragmentManagerField = f;
}
#Override
public void onDetach() {
super.onDetach();
if (sChildFragmentManagerField != null) {
try {
sChildFragmentManagerField.set(this, null);
} catch (Exception e) {
}
}
}
/* end of fix */
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.settings_frag_overview, container, false);
viewPager=(ViewPager)result.findViewById(R.id.overview_pager);
Log.e("SettingsActivityOverviewFragment","viewPager content is " + viewPager + ", " + viewPager.getHeight());
pagerAdapter = buildAdapter();
new SetAdapterTask().execute();
return(result);
}
private PagerAdapter buildAdapter() {
return(new SettingsOverviewPagerAdapter(getActivity(), getChildFragmentManager()));
}
public void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
}
private class SetAdapterTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
if(pagerAdapter != null) viewPager.setAdapter(pagerAdapter);
}
}
}
SettingsOverviewPagerAdapter.java
public class SettingsOverviewPagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
public SettingsOverviewPagerAdapter(Context ctxt, FragmentManager mgr) {
super(mgr);
this.ctxt=ctxt;
}
#Override
public int getCount() {
Log.i("SettingsOverviewPagerAdapter","getCount returns 10");
return(10);
}
#Override
public Fragment getItem(int position) {
return(EditorFragment.newInstance(position));
}
#Override
public String getPageTitle(int position) {
return(EditorFragment.getTitle(ctxt, position));
}
}
EditorFragment.java
public class EditorFragment extends Fragment {
private static final String KEY_POSITION = "position";
static EditorFragment newInstance(int position) {
EditorFragment frag = new EditorFragment();
Bundle args = new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return (frag);
}
static String getTitle(Context ctxt, int position) {
return (String.format("ctest", position + 1));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.editor, container, false);
EditText editor = (EditText) result.findViewById(R.id.editor);
int position = getArguments().getInt(KEY_POSITION, -1);
editor.setHint(getTitle(getActivity(), position));
return (result);
}
}
SettingsFragOverview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/overview_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTitleStrip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"/>
</android.support.v4.view.ViewPager>
EditorFragment.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/editor"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textMultiLine"
android:gravity="left|top"
/>
This typically occurs when:
Using an inner fragment as parent of ViewPager
Parent container has a scrollview in it.

Update ListFragment after asynctask

I have two listfragment and one fragment in my application. I show you first fragment.
The application starts, Asynctask retrieves data and put them in arrayNews.
I think the problem is the update of listview or adapter in listfragment that does not refresh.
If I change the phone's orientation => listfragment (+ listview) appears correctly.
If I go to fragment 3 (fragment in 2 and 3 in memory), then come back on fragment 1 => it works correctly.
Sorry for my english ^^
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static ArrayList<Data> arrayNews = new ArrayList<Data>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> listeFragments = new Vector<Fragment>();
listeFragments.add(Fragment.instantiate(this, ActualiteFragment.class.getName()));
listeFragments.add(Fragment.instantiate(this, DossierFragment.class.getName()));
listeFragments.add(Fragment.instantiate(this, ForumFragment.class.getName()));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), listeFragments);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
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));
}
if (arrayDossier.size() == 0 && arrayDossier.size() == 0)
{
chargement_donnees();
}
}
public void chargement_donnees()
{
AsyncTaskChargement chargNews = new AsyncTaskChargement();
chargNews.execute();
}
public class AsyncTaskChargement extends AsyncTask<Void, Integer, Void>
{
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Chargement des données ...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0)
{
arrayNews = ContainerData_news.getFeeds();
return null;
}
#Override
protected void onPostExecute(Void result)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_refresh:
chargement_donnees();
return true;
default:
return false;
}
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
List<Fragment> listeFragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> listeFragments)
{
super(fm);
this.listeFragments = listeFragments;
}
#Override
public Fragment getItem(int position)
{
return listeFragments.get(position);
}
#Override
public int getCount()
{
return listeFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
switch (position)
{
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
public static class ActualiteFragment extends ListFragment
{
public ActualiteFragment()
{
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setListAdapter(new AdapterListe(getActivity(), arrayNews));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.listfragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
...
}
}
}
I found an easy way to update such list
Steps would be.:
1. declare onCreateView in ListFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.TheLayoutContainingAListView, container, false);
return view;
}
TheLayoutContainingAListView.xml should contain only a listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
The android:id must be "#android:id/list" . however you may try other things.. I didn't..
2. In onPostExecute of your AsyncTask (Asynctask should be in MainActivity), do everything that you want to do.. i.e. declare an adapter, and setAdapter
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
lv = (ListView) findViewById(android.R.id.list);
CustomAdapter adapt = new CustomAdapter(MainActivity.this,
android.R.id.list, fetch); //You can use ArrayAdapter.. i wanted a custom one
lv.setAdapter(adapt);
showFragment(YOUR Fragment, false);
super.onPostExecute(result);
}
showFragment is just a function i used to show a particular fragment and hide all others.. you can easily achieve it by FragmentTransaction show() and hide() methods.
Use youradapter.notifyDataSetChanged(); in onPostExecute to force a redraw of your list.

Categories

Resources