I have this class:
public class MainActivity extends ActionBarActivity implements TabListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab TestTab = actionBar.newTab().setText("The test");
ActionBar.Tab chatTab = actionBar.newTab().setText("Chat");
TestTab.setTabListener(this);
chatTab.setTabListener(this);
actionBar.addTab(TestTab);
actionBar.addTab(chatTab);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater actionMenue = getMenuInflater();
actionMenue.inflate(R.menu.main_activity_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.mapIcon) {
Intent displayTheMap = new Intent(this, Map.class);
startActivity(displayTheMap);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
public void showTheMap(View mainView){
Intent displayTheMap = new Intent(this, Map.class);
startActivity(displayTheMap);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
As you can see I have placed 2 tabs under the action bar. Now everything looks just fine, but, how do I execute a pair of code, when a tab is clicked? I mean, it is clear that I have to write my code here:
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
But how do I know wich tab is selected? Can someone give me a clue, because as a beginner, it is seems hard to understand. I know that I'm missing a small part here.
Use the below code
Please us the below code.
#Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
int position = tab.getPosition();
switch(position){
case 0:
//code for test
break;
case 1:
//code for chat
break;
}
}
you can try this :
public class MainActivity extends TabActivity {
static TabHost mytabs;
mytabs = getTabHost();
mytabs.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
Log.i("***Selected Tab", "Im currently in tab with index::" + mytabs.getCurrentTab());
}
});
Generally I would solve this like in the official docs. Here is a link
What is suggested there is to implement a separate TabListener like this:
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}
And then add tabs like this:
Tab tab = actionBar.newTab()
.setText(R.string.artist)
.setTabListener(new TabListener<ArtistFragment>(this, "artist", ArtistFragment.class));
The class you give the listener in the constructor determines the class of the Fragment which will be opened if the tab is selected.
try this code
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(tab.getText().equals("The test"){
//the test tab is selected
}
else if(tab.getText().equals("Chat"){
// the chat tab is selected
}
}
Related
I have a FragmentActivity in my android application.
I use a viewPager to insert tabs in the activity. So I have this code. It works.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_clienti);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String datas= extras.getString("Cliente");
if (datas!= null) {
System.out.println("pippo");
}
}
TabAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("Scheda Cliente").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Conto Cliente").setTabListener(tabListener));
apriConnessioneDB();
}
This is the class FragmentStatePagerAdapter
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragement for Android Tab
return new infoCliente();
case 1:
//Fragment for Ios Tab
return new infoCliente();
case 2:
//Fragment for Windows Tab
return new infoCliente();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
This is the class Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_infocliente, container, false);
if(savedInstanceState!=null){
//String tmp = savedInstanceState.getString("myKey");
//TextView mTabHost = (TextView) findViewById(android.R.id.labelRagioneSociale);
System.out.println("PIPPPPPPPPPPPPPPPPPPPPPP");
}
TextView btn=(TextView) view.findViewById(R.id.labelRagioneSociale5);
btn.setText("pippo");
return view;
}
Now I want to know How I can pass a parameter to infoCliente class.
In the onCreate method of first class I have this:
String datas= extras.getString("Cliente");
I want pass this parameter to fragment class.
Bundle bundle = new Bundle();
bundle.putInt("battery", bat);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();
Then in onCreate() method of the fragment:
Bundle bundle=getArguments(); int mLabel = bundle.getInt("battery",0);
Define an interface in your Fragment, for example
public interface FragmentCallback {
onSomethingHappend(String param);
}
Implement the interface in your Activity.
Then, when you want to call the callback, do something like this:
FragmentCallback callback = (FragmentCallback) getActivity();
callback.onSomethingHappened(string);
I am using Tab Activity in my android app, and I want to change the first tab that appears when I open my app, to be the last tab,but that the order of tabs will stay the same (swipe right to get to the first tab).
So in order to change the layout direction I added to the manifest
android:supportsRtl="true"
And to my Main Activity
android:layoutDirection="rtl"
What should I add / Change ?
Thank you very much
Edit: This is my Page Adapter Code:
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
//
return new Tab1Fragment();
case 1:
//
return new Tab2Fragment();
case 2:
//
return new Tab3Fragment();
case 3:
//
return new Tab4Fragment();
case 4:
//
return new Tab5Fragment();
}
return null;
}
And The Main Activity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Tab1", "Tab2", "Tab3","Tab4","Tab5" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public static boolean isRTL(Locale locale) {
final int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0));
return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT ||
directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
}
Use this to know if you are on RTL:
public static boolean isRTL(Locale locale) {
final int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0));
return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT ||
directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
}
Than just select the appropriate tab at the beginning.
like:
Locale current = getResources().getConfiguration().locale;
if(isRTL(current)) {
getActionBar().setSelectedNavigationItem(4);
}`else {
getActionBar().setSelectedNavigationItem(0);
}
I have 3 class
Main Class
Fragment (Pager)
Fragment Adapter
but, in fragment, there's problem, anybody can help me ??
public class AttractionFragment extends Fragment implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Solo", "Karanganyar", "Sukoharjo" };
public AttractionFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_attraction, container, false);
// Initilization
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
actionBar = getActivity().getActionBar();
//This my problem
mAdapter = new TabsPagerAdapter(getFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
return rootView;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
and this my adapter class
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new SoloAttractionFragment();
case 1:
// Games fragment activity
return new KaranganyarAttractionFragment();
case 2:
// Movies fragment activity
return new SukoharjoAttractionFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
You are using FragmentStatePagerAdapter`.
http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html
You may also want to check
Does the Android ICS API have a native equivalent to ViewPager support lib?
You need to change a lot of things.
In Activity
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_view);
AttractionFragment newFragment = new AttractionFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
AttractionFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar.Tab;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AttractionFragment extends Fragment implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Solo", "Karanganyar", "Sukoharjo","Sragen","Boyolali","Klaten","Wonogiri" };
public AttractionFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag2, container, false);
// Initilization
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
//This my problem
mAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(AttractionFragment.this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
return rootView;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
TabsPageAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
public TabsPagerAdapter(android.support.v4.app.FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int index) {
Fragment fragment = null;
switch (index) {
case 0:
// Top Rated fragment activity
fragment =new SoloAttractionFragment();
case 1:
fragment = new KaranganyarAttractionFragment();
case 2:
// Movies fragment activity
fragment = new SukoharjoAttractionFragment();
}
return fragment ;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
Snap
Please try to change
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
with
public TabsPagerAdapter(android.app.FragmentManager.FragmentManager fm) {
super(fm);
}
Try not to use support fragment manager.
No it won't give error, as i have tried with below sample code.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class MainActivity extends FragmentStatePagerAdapter {
public MainActivity(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
return null;
}
#Override
public int getCount() {
return 0;
}
}
DESCRIPTION::
There is a ActionBarTab(3-tab) setup, We are linking three fragments
for each Action-Tab, Each fragment contains a listview
Whenever we are clicking Tab, we are sorting data.
In onTabReselect i am calling sort function using interface method,
without error it executes but its not refreshing the listview
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Toast.makeText(this, DosUtils.ExecuteDOSCommand(), Toast.LENGTH_SHORT);
// Initialize
FindMyBuffetApplicationCls.initFindMyBuffetApplicationCls(MainActivity.this);
setContentView(R.layout.main_activity);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab RatingTab = actionbar.newTab().setText(FindMyBuffetConstants.TAB_NAME_RATING);
ActionBar.Tab PriceTab = actionbar.newTab().setText(FindMyBuffetConstants.SORT_BY_PRICE);
ActionBar.Tab DistanceTab = actionbar.newTab().setText(FindMyBuffetConstants.SORT_BY_DISTANCE);
Fragment SortRestFragmentByRating = new SortRestaurantRating();
Fragment SortRestFragmentByPrice = new SortRestaurantByPrice();
Fragment SortRestFragmentByDistance = new SortRestaurantByDistance();
RatingTab.setTabListener(new MyTabsListener(SortRestFragmentByRating));
PriceTab.setTabListener(new MyTabsListener(SortRestFragmentByPrice));
DistanceTab.setTabListener(new MyTabsListener(SortRestFragmentByDistance));
actionbar.addTab(RatingTab);
actionbar.addTab(PriceTab);
actionbar.addTab(DistanceTab);
FindMyBuffetApplicationCls.comm = (Communicator) new SortRestaurantByPrice();
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
if(tab.getText().toString()==FindMyBuffetConstants.TAB_NAME_RATING){
if(FindMyBuffetApplicationCls.isRatingOrderByDesc==false){
FindMyBuffetApplicationCls.isRatingOrderByDesc=true;
}
else {
FindMyBuffetApplicationCls.isRatingOrderByDesc=false;
}
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_PRICE){
if(FindMyBuffetApplicationCls.isPriceOrderByDesc==false){
FindMyBuffetApplicationCls.isPriceOrderByDesc=true;
}
else {
FindMyBuffetApplicationCls.isPriceOrderByDesc=false;
}
FindMyBuffetApplicationCls.comm.RefreshFragment();
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_DISTANCE){
if(FindMyBuffetApplicationCls.isDistanceOrderByDesc==false){
FindMyBuffetApplicationCls.isDistanceOrderByDesc=true;
}
else {
FindMyBuffetApplicationCls.isDistanceOrderByDesc=false;
}
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.main_container, fragment);
if(tab.getText().toString()==FindMyBuffetConstants.TAB_NAME_RATING){
if(FindMyBuffetApplicationCls.isRatingOrderByDesc==false)
FindMyBuffetApplicationCls.isRatingOrderByDesc=true;
else
FindMyBuffetApplicationCls.isRatingOrderByDesc=false;
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_PRICE){
if(FindMyBuffetApplicationCls.isPriceOrderByDesc==false)
FindMyBuffetApplicationCls.isPriceOrderByDesc=true;
else
FindMyBuffetApplicationCls.isPriceOrderByDesc=false;
}
if(tab.getText().toString()==FindMyBuffetConstants.SORT_BY_DISTANCE){
if(FindMyBuffetApplicationCls.isDistanceOrderByDesc==false)
FindMyBuffetApplicationCls.isDistanceOrderByDesc=true;
else
FindMyBuffetApplicationCls.isDistanceOrderByDesc=false;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
Log.i("TEST TAB",tab.getText().toString());
}
}
SortRestaurantByPrice.java
public class SortRestaurantByPrice extends Fragment implements Communicator{
// Declaration
ListView xmlFragmentListView;
SortRestaurantListViewAdapter listViewAdapter;
View layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.sort_restaurant_by_price, container,false);
xmlFragmentListView = ((ListView) layout.findViewById(R.id.sortrestaurantbypricelistview));
return layout;
}
#Override
public void onDestroyView() {
super.onDestroyView();
//layout = null; // now cleaning up!
}
private void SortRestaurantList(String strSortBy)
throws Exception, TransformerConfigurationException,
TransformerException, FindMyBuffetException {
// Process the Main Screen Data
List<RestaurantDetails> lstRest = null;
lstRest = SAXXMLParser.parse(xmlInputStream);
SortRestaurantListViewAdapter listViewAdapter = new SortRestaurantListViewAdapter(lstRest);
xmlFragmentListView.setAdapter(listViewAdapter);
}
#Override
public void RefreshFragment() {
// TODO Auto-generated method stub
Log.i("hELLO", "refresh requested. Try to reload data for this fragment...");
SortRestaurantList("Price");
}
}
Communicator.java
public interface Communicator {
public void RefreshFragment();
}
Please call notifyDataChanged method on your list in the sortRestaurantList method.
private void SortRestaurantList(String strSortBy)
throws Exception, TransformerConfigurationException,
TransformerException, FindMyBuffetException {
// Process the Main Screen Data
List<RestaurantDetails> lstRest = null;
lstRest = SAXXMLParser.parse(xmlInputStream);
SortRestaurantListViewAdapter listViewAdapter = new SortRestaurantListViewAdapter(lstRest);
xmlFragmentListView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged(); // call this on Adapter
}
Infact move the adapter code in the onCreateView method. Only modify (sort) your List lstRest in the SortRestaurant method and after that call the notifyDataSetChanged method.
i have an actionbar with two tabs and an tablistener which handles the fragments. Now i want with a ViewPager the possibility to Swipe to also switch the tabs.
I tried the solution stated here:
Android, How to mix ActionBar.Tab + View Pager + ListFragment
But it gives an conflicts with Android.app.Fragments and the Support Package Fragments.
The App is for >4.0 so i dont need the support fragments.
public class MainActivity extends Activity{
....
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//viewpager
mViewPager = new ViewPager(this);
setContentView(mViewPager);
Doesnt work:
//TabsAdapter tabsAdapter = new TabsAdapter(this,mViewPager);
// Tab tab1 = actionBar.newTab().setText("Tab1");
// Tab tab2 = actionBar.newTab().setText("Tab2");
// tabsAdapter.addTab(tab1, Tab1Fragment.class, null);
// tabsAdapter.addTab(tab2, Tab2Fragment.class, null);
Alternative:
//viewpager
mViewPager = new ViewPager(this);
setContentView(mViewPager);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
super.onPageSelected(position);
getActionBar().setSelectedNavigationItem(position);
}
});
tab_1 = actionBar.newTab().setText("Tab1");
tab_1
.setTabListener(new TabListener<Tab1Fragment>(
this, "Tab1", Tab1Fragment.class,mViewPager));
actionBar.addTab(tab_1);
tab_2 = actionBar.newTab().setText("Tab2");
tab_2
.setTabListener(new TabListener<Tab2Fragment>(
this, "Tab2", Tab2Fragment.class,mViewPager));
actionBar.addTab(tab_2);
/**
* TabListener
* #param <T>
*/
private static class TabListener<T extends Fragment> implements ActionBar.TabListener
{
private Fragment mFragment;
private Activity mActivity;
private final String mTag;
private final Class<T> mClass;
private ViewPager vp;
public TabListener(Activity activity, String tag, Class<T> clz, ViewPager vp) {
mActivity = activity;
mTag = tag;
mClass = clz;
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
this.vp = vp;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(android.R.id.content, mFragment, mTag);
} else {
if (mFragment.isDetached()) {
ft.attach(mFragment);
}
}
vp.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
In the Fragments classes i have statements like:
Bundle args = new Bundle();
args.putString("name", atn.getName());
args.putLong("aid", atn.getId());
AFragment f = new AFragment();
f.setArguments(args);
f.show(getFragmentManager(), "tag");
FragmentManager fragmentManager =mActivity.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment f = fragmentManager.findFragmentByTag("Tab1");
if (f != null) {
fragmentTransaction.detach(f);
fragmentTransaction.attach(f);
}
fragmentTransaction.replace(android.R.id.content, f);
fragmentTransaction. commitAllowingStateLoss();
which are not compatible with the other Fragment type (import android.support.v4.app.Fragment;). How can i easily add the swipe gesture? Selection on Tabs works perfectly.
EDIT:
With support package 13 the view pager worked but the content isnt refreshed. I use FragmentStatePagerAdapter so the Fragments should be removed and added again but instead it takes the same fragment without new creation. Also Viewpage named teh Fragments like
android:switcher... can i name them on my own?
import android.support.v13.app.FragmentStatePagerAdapter;
public class TabsAdapter extends FragmentStatePagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private Fragment mFragment;
private Activity mActivity;
private String mTag;
private final List<Fragment> fragments = new ArrayList<Fragment>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
private final String name;
TabInfo(Class<?> _class, Bundle _args,String name) {
clss = _class;
args = _args;
this.name=name;
}
}
public TabsAdapter(Activity activity, ViewPager pager) {
super(activity.getFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
mActivity = activity;
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args,tab.getText()+"");
tab.setTag(info.name);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
// return super.getItemPosition(object);
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
Fragment fr = Fragment.instantiate(mContext, info.clss.getName(), info.args);
//
// //addFragment (fr, position);
return fr;
}
public void addFragment(Fragment f, int location) {
if (fragments.size() == 0)
fragments.add(f);
else
fragments.add(location, f);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i).name == tag) {
updateDataSet(i);
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void updateDataSet(int pos)
{
//Let's update the dataset for the selected genre
Fragment fragment =
(mActivity.getFragmentManager().findFragmentByTag(
"android:switcher:"+ mViewPager.getId()+":"+pos));
//TabFragment fragment = (TabFragment) getItem(pos);
if(fragment != null) // could be null if not instantiated yet
{
if(fragment.getView() != null)
{
// no need to call if fragment's onDestroyView()
//has since been called.
if(fragment instanceof Tab1Fragment){
((Tab1Fragment) fragment).refresh();
}
else if(fragment instanceof Tab2Fragment){
( (Tab2Fragment) fragment).refresh();
}
}
}
}
Try using the build it Tab Activity template, create an example and extract the code you want from there. I created a tabs based app, but I used the default options and customized those to fit my needs.
Check this open source proyect https://github.com/dkim0419/SoundRecorder
they use one activity with a viewPager and some fragments.
Also the use PagerSlidingTabStrip for page indicator.
Take a look it's very easy how they implemented it.