I want to create a list view under different tabs. This is what i did for FragmentA class.
public class FragmentA extends ListFragment {
String [] names = {"Theo","Theo","Theo","Theo","Theo"};
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1,names);
setListAdapter(adapter);
}
}
I am creating a sample listview into the onActivityCreated method. Finally for the Tabs I am using the following code.
public class MainActivity extends ActionBarActivity implements TabListener {
ActionBar actionBar;
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(new MyAdapter(getSupportFragmentManager()));
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
actionBar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
ActionBar.Tab tab1=actionBar.newTab();
tab1.setText("Tab 1");
tab1.setTabListener(this);
ActionBar.Tab tab2=actionBar.newTab();
tab2.setText("Tab 2");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionBar.newTab();
tab3.setText("Tab 3");
tab3.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
pager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
Fragment fragment = null;
if(arg0==0){
fragment = new FragmentA();
}
if(arg0==1){
fragment = new FragmentB();
}
if(arg0==2){
fragment = new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
The compiler doesn't let me to run the app as it gives me the following error..
Type mismatch: cannot convert from FragmentA to Fragment
Change type of fragment to fragmentA.
If I comment the setListAdapter(adapter) in the FragmentA class, everything is fine. Why is this happening?
change:
import android.app.ListFragment;
to
import android.support.v4.app.ListFragment;
you used ListFragmentfrom API level 11 but you must used ListFragment from support library in order to work with viewpager. because it is FragmentManager also comes from support library(getSupportFragmentManager) so it dose not understand any fragment from other than its own library.
Related
i have five columns in my database and five tabs that each column corresponds to each tab
now i want to add tabs to actionbar just if the corresponding column was not empty
so how i should condition tabs to be shown or not depends on their corresponding columns
i used this strategy to condition tabs and it worked but unfortunately the name of tabs are not correct :
public class Content extends FragmentActivity implements ActionBar.TabListener {
private Gcontent g;
private String g_name;
private String g_family;
private String g_about;
private String g_age;
private String g_father;
private ActionBar actionBar;
private ViewPager viewPager;
private TabsPagerAdapter tabsAdapter = new TabsPagerAdapter(getSupportFragmentManager());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pc_content);
g = (Gcontent) getIntent().getExtras().get("CurrMember");
g_name = g.getGname();
g_family = g.getGfamily();
g_about = g.getGabout();
g_age = g.getGstory();
g_father = g.getGfather();
viewPager = (ViewPager) findViewById(R.id.tabs_container);
viewPager.setAdapter(tabsAdapter);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setHomeButtonEnabled(false);
if(!(g_name.equals("empty"))){
actionBar.addTab(
actionBar.newTab().
setText("first tab").
setTabListener(this)
);
}
if(!(g_family.equals("empty"))){
actionBar.addTab(
actionBar.newTab().
setText("second tab").
setTabListener(this)
);
}
if(!(g_about.equals("empty"))){
actionBar.addTab(
actionBar.newTab().
setText("third tab").
setTabListener(this)
);
}
if(!(g_age.equals("empty"))){
actionBar.addTab(
actionBar.newTab().
setText("fourth tab").
setTabListener(this)
);
}
if(!(g_father.equals("empty"))){
actionBar.addTab(
actionBar.newTab().
setText("fifth tab").
setTabListener(this)
);
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
viewPager.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}
and this is my pager adapter :
public class TabsPagerAdapter extends FragmentPagerAdapter {
int count;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch(index){
case 0 :
return new FragmentFirst();
case 1 :
return new FragmentSecond();
case 2 :
return new FragmentThird();
case 3 :
return new FragmentFourth();
case 4 :
return new FragmentFifth();
}
return null;
}
#Override
public int getCount() {
return 5;
}
}
My App is a fragment have viewpager to change tab with fragmentA and fragmentB.
After I change another fragment by drawlayout.
I back to the first fragment.
The fragmentA and fragmentB doesn't link with the viewpager.
I think it's about Fragment cyclelife questions.
But I can't figure out the answer.
Please help me.Thanks.
(My English is not very well.Please use simple word.Thanks)
public class Fragment_Viewpager extends Fragment implements TabListener{
private View v;
ViewPager viewPager;
ActionBar actionBar;
ActionBar.Tab tab1;
ActionBar.Tab tab2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v= inflater.inflate(R.layout.fragment_viewpager, container, false);
viewPager=(ViewPager)v.findViewById(R.id.pager);
Log.w("Step1","inviewPager");
viewPager.setAdapter(new MyAdapter(getFragmentManager()));
Log.w("Step2","inviewPager");
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO 自動產生的方法 Stub
actionBar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO 自動產生的方法 Stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO 自動產生的方法 Stub
}
});
Log.w("Step7","inviewPager");
Log.w("Step8","inviewPager");
return v;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO 自動產生的方法 Stub
}
class MyAdapter extends FragmentPagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
Log.w("in","Fragment-2");
}
#Override
public Fragment getItem(int arg0) {
// TODO 自動產生的方法 Stub
Log.w("in","Fragment-1");
Fragment fragment = null;
Log.w("in","Fragment000");
if(arg0==0)
{
Log.w("in","FragmentA");
fragment = new FragmentA();
}
if(arg0==1)
{
Log.w("in","FragmentB");
fragment = new FragmentB();
}
return fragment;
}
#Override
public int getCount() {
// TODO 自動產生的方法 Stub
return 2;
}
}
#Override
public void onStop() {
super.onPause();
Log.w("in","inStop");
}
#Override
public void onPause() {
super.onPause();
getActivity().getActionBar().removeAllTabs();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
Log.w("in","onPause");
onDetach();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.w("in","onDestroy");
}
#Override
public void onResume() {
super.onResume();
Log.w("in","onResume");
}
#Override
public void onStart() {
Log.w("Step3","inviewPager");
actionBar = getActivity().getActionBar();
Log.w("Step4","inviewPager");
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Log.w("Step5","inviewPager");
tab1=actionBar.newTab();
tab2=actionBar.newTab();
Log.w("Step6","inviewPager");
tab1.setText("Tab 1");
tab1.setTabListener(this);
tab2.setText("Tab 2");
tab2.setTabListener(this);
actionBar.addTab(tab1);
Log.w("in","onStart2");
actionBar.addTab(tab2);
super.onStart();
}
}
I have navigational drawer and fragment for each drawer item. Now Under each fragment we have created multiple fragments using FragmentPagerAdapter.
I've 3 drawer items as Home, Group and Feedback. Under Home, there are 2 fragments i.e My Profile and Logged
so i've created a swipeable tabs for My Profile and Logged and these two fragments are under home item. Now i've to do some network calls in both the fragments(My Profile, Logged) but how to identify which fragment is active on FragmentPagerAdapter? Is it possible to stop adapter to create fragments in advance.
HomeFragment
DrawerModel model = new DrawerModel();
LoggedFragment loggedFrag = new LoggedFragment();
loggedFrag.setTargetFragment(loggedFrag, 0);
model.setFragment(loggedFrag);
dFragments.add(model);
model = new DrawerModel();
model.setDrawerTitle(getString(R.string.profile_tab_title));
model.setFragment(new ProfileFragment());
dFragments.add(model);
Bundle bundle = new Bundle();
bundle.putSerializable("fragments", dFragments);
fragment = new DrawerFragment();
fragment.setArguments(bundle);
navigateFragment(fragment);
DrawerFragment
public class DrawerFragment extends Fragment {
private FragmentAdapter pagerAdapter;
private ViewPager mViewPager;
private ArrayList<DrawerModel> fList;
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fList = (ArrayList<DrawerModel>) getArguments().getSerializable(
"fragments");
View v = inflater.inflate(R.layout.swipe_tabs, container, false);
pagerAdapter = new FragmentAdapter(getChildFragmentManager(), fList);
mViewPager = (ViewPager) v.findViewById(R.id.pager);
mViewPager.setAdapter(pagerAdapter);
return v;
}
}
FragmentAdapter
public class FragmentAdapter extends FragmentStatePagerAdapter {
private int TOTAL_TABS = 0;
private ArrayList<DrawerModel> fragmentList;
private SparseArray<Fragment> mPageReference = new SparseArray<Fragment>();
public FragmentAdapter(FragmentManager fm, ArrayList<DrawerModel> fList) {
super(fm);
// TODO Auto-generated constructor stub
TOTAL_TABS = fList.size();
fragmentList = fList;
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
return fragmentList.get(position).getDrawerFragment();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return TOTAL_TABS;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
Fragment fragment = (Fragment) super.instantiateItem(container,
position);
mPageReference.put(position, fragment);
Log.d("FragmentAdapter - OnCreate", mPageReference.size() + "");
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return fragmentList.get(position).getDrawerTitle();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
mPageReference.remove(position);
Log.d("FragmentAdapter - onDestroy", mPageReference.size() + "");
super.destroyItem(container, position, object);
}
public Fragment getFragment(int key) {
return mPageReference.get(key);
}
}
Logged Fragment
public class LoggedFragment extends Fragment implements OnClickListener {
TextView tHeader, tEmail, tvPhone;
SharedPreferences sp;
ImageView ivAds;
String bannerUrl = null;
private Handler handler = new Handler();
private static final String TAG = "LoggedFragment";
private void addListeners() {
// TODO Auto-generated method stub
ivAds.setOnClickListener(this);
}
Runnable updateImage = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (Utility.checkConnectivity(getActivity()))
new ImageTask((Home_Activity) getActivity(), "Logged")
.execute();
handler.postDelayed(this, Utility.AD_DURATION);
}
};
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
if (handler != null)
handler.post(updateImage);
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (handler != null)
handler.removeCallbacks(updateImage);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.logged_in, container, false);
bindComponents(v);
addListeners();
return v;
}
private void bindComponents(View v) {
// TODO Auto-generated method stub
ivAds = (ImageView) v.findViewById(R.id.ivLoggedAds);
}
public void updateBanner(Bitmap bitmap, String url) {
ivAds.setImageBitmap(bitmap);
bannerUrl = url;
}
}
Call to update fragment method
Fragment fragment = activity.getSupportFragmentManager()
.findFragmentById(R.id.content_frame)
.getTargetFragment();
if (fragment instanceof LoggedFragment) {
LoggedFragment logged = (LoggedFragment) fragment;
logged.updateBanner(result, parameter[1]);
} else
Log.d(TAG, "No Logged Fragment Found");
Now under logged and my profile fragment i need to fetch some data dynamically as soon fragment is visible to user but unable to do so?
Any ideas/suggestions is highly appreciated.
use below code to find your fragment,
FragmentAdapter pa = (FragmentAdapter)viewPager.getAdapter();
pa.getFragment(viewPager.getCurrentItem()).updateBanner();
the code select current visible fragment you can change it to other one by
pa.getFragment(index of other fragment).updateBanner();
you must cast pa.getFragment(viewPager.getCurrentItem()) to what fragment you want for example if at that position it is logged change it to below:
((LoggedFragment)pa.getFragment(viewPager.getCurrentItem()) )
I would say you have two differnt options.
Option one: Use setTargetFragment() and getTargetFragment() so you get a reference to that fragment you need.
Option two: Use the FragmentManager simply get that Fragment you need from the FragmentManager and call that methods you defined on your Fragment.
I am using options menu in action bar tabs,view pager and nested fragments, when i switch from fragmentA to fragmentB using tabs menu items are working fine, but when i try to swith using view pager option items are getting invisble in fragments.
public class RTHomeTabFragment extends Fragment implements TabListener,OnBackButtonPressInterfaceForFragment{
public ActionBarActivity parentActivity;
private ActionBar actionBar;
ViewPager mViewPager;
public static int currentPage;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RTMessagingUtils.log(getClass().getName(), "onCreateView");
View view = inflater.inflate(R.layout.viewpager_tabs, container,false);
parentActivity = (ActionBarActivity) getActivity();
actionBar = parentActivity.getSupportActionBar();
mViewPager = (ViewPager) view.findViewById(R.id.pager);
/* actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);*/
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setCustomView(null);
actionBar.removeAllTabs();
List<Fragment> fragments = getFragments();
pagerAdapter adapter = new pagerAdapter(getChildFragmentManager(), getFragments());
mViewPager.setAdapter(adapter);
currentPage=mViewPager.getCurrentItem();
Log.d("TestFragments", "currentPage======"+currentPage);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
currentPage=mViewPager.getCurrentItem();
Log.d("TestFragments", "currentPage======"+currentPage);
}
});
for (int i = 0; i < adapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(adapter.getPageTitle(i)).setTabListener(this));
}
return view;
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// add fragments here
fList.add(new Test1());
fList.add(new Test2());
fList.add(new Test3());
return fList;
}
class pagerAdapter extends FragmentPagerAdapter{
private List<Fragment> fragments;
public pagerAdapter(FragmentManager fm, List<Fragment> fragments){
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.db_jio_chat_chats).toUpperCase(l);
case 1:
return getString(R.string.db_jio_chat_groups).toUpperCase(l);
case 2:
return getString(R.string.db_jio_chat_contacts).toUpperCase(l);
/*case 3:
return getString(R.string.db_jio_chat_my_profile).toUpperCase(l);
case 4:
return getString(R.string.db_jio_chat_location).toUpperCase(l);
case 5:
return getString(R.string.db_jio_chat_about).toUpperCase(l);*/
}
return null;
}
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onResume() {
super.onResume();
RTMessagingUtils.log(getClass().getName(), "onResume");
}
#Override
public void onPause() {
super.onPause();
RTMessagingUtils.log(getClass().getName(), "onPause");
}
}
In your getItem method do this for testing :
#Override
public Fragment getItem(int position) {
if(position == 0)
return new Test1();
else
return new Test2();
}
and see if this works, I will find an explanation later if it works...
Hi I have a Swipe Tab Fragment Activity that contains Three Fragments. I created my own adapter that extends FragmentStatePageAdapter.
Now here I'll explain how each tab (Fragments) works.
In Tab 1 and Tab 2, I have a list with practically the same type, when I mean type, I mean they are Symptoms (fever, pain in the eyes, etc.).
Now Tab 3 serves as a tray. Whenever I select an item from the listview in either Tab 1 or Tab 2, I want to transfer that item to Tab 3 and remove that Item from the List where it was selected.
I have tried implementing an Interface but it didn't work for me since I added the fragments on the Main FragmentActivity through an Adapter. MY questions is
How can I communicate the three Fragments? Meaning how can I pass data between these fragment.
Now if you want to take a look at what I've done for now, here it is:
I depicted this as Tab 2 in my question
public class FragmentGeneralSymptoms extends ListFragment implements OnItemClickListener {
ArrayList<String> symptomList;
String name;
String selected;
Tray tray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_generalsymptoms, container,
false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
name = args.getString("key");
tray = (Tray) getActivity();
new LoadSymptoms().execute();
}
class LoadSymptoms extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
KnowledgeBaseHelper helper = new KnowledgeBaseHelper(getActivity());
ProfileHandler handler = new ProfileHandler(getActivity());
Profiles profile = handler.getProfile(name);
String age = profile.getAge() + "";
String gender = profile.getGender();
symptomList = helper.getSymptomList(name, age, gender);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
setListAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.general_list, symptomList));
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
selected = symptomList.get(arg2);
tray.respond(selected);
}
}
My Tab 3
public class FragmentTray extends ListFragment{
private ArrayList<String> selectedList;
public FragmentTray(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_tray, container, false);
}
public void addToTray(String symptom){
selectedList.add(symptom);
setListAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.general_list, selectedList));
}
public void removeSymptom(String string){
selectedList.remove(selectedList.indexOf(string));
}
}
My MainActivity which Extends FragmentActivity
public class MainActivity extends FragmentActivity implements TabListener, OnPageChangeListener, Tray {
private String selectedProfileName;
ActionBar actionBar;
ViewPager viewPager;
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.main_activity);
Bundle args = getIntent().getExtras();
selectedProfileName = args.getString("key_name");
viewPager = (ViewPager) findViewById(R.id.main_pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(this);
InitializeActionBar();
}
public void InitializeActionBar() {
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabBodyPart = actionBar.newTab();
tabBodyPart.setText("Body Parts");
tabBodyPart.setTabListener(MainActivity.this);
ActionBar.Tab tabGeneralSymptoms = actionBar.newTab();
tabGeneralSymptoms.setText("General Symptoms");
tabGeneralSymptoms.setTabListener(MainActivity.this);
ActionBar.Tab tabSelectedSymptoms = actionBar.newTab();
tabSelectedSymptoms.setText("Selected Symptoms");
tabSelectedSymptoms.setTabListener(MainActivity.this);
actionBar.addTab(tabBodyPart);
actionBar.addTab(tabGeneralSymptoms);
actionBar.addTab(tabSelectedSymptoms);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(tab.getPosition());
}
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
Fragment fragment = null;
Bundle bundle = new Bundle();
bundle.putString("key", selectedProfileName);
if (arg0 == 0) {
fragment = new FragmentBodyPart();
fragment.setArguments(bundle);
}
if (arg0 == 1) {
fragment = new FragmentGeneralSymptoms();
fragment.setArguments(bundle);
}
if (arg0 == 2) {
fragment = new FragmentTray();
}
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
actionBar.setSelectedNavigationItem(arg0);
}
#Override
public void respond(String string) {
// TODO Auto-generated method stub
FragmentTray frag2 = new FragmentTray();
frag2.addToTray(string);
}
}
Finally my Interface
public interface Tray {
public void respond(String string);
}
what I usually do is:
1.- Define the interface. It's done, fine.
2.- Your FragmentGeneralSymptoms must have an initializated listener. Yuou're that but you forgot to set the listener in the class.
public class FragmentGeneralSymptoms extends ListFragment implements OnItemClickListener {
ArrayList<String> symptomList;
String name;
String selected;
Tray tray;
(your code)
public void setTrayListener(Tray listener)
{
tray = listener;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
selected = symptomList.get(arg2);
if(tray != null)
{
symptomList.remove(selected); // if you want to remove this element from this list
tray.respond(selected);
}
} }
3.- Your FragmentTray class must implement the interface:
public class FragmentTray extends ListFragment implements Tray{
private ArrayList<String> selectedList;
public FragmentTray(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_tray, container, false);
}
public void addToTray(String symptom){
selectedList.add(symptom);
setListAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.general_list, selectedList));
}
public void removeSymptom(String string){
selectedList.remove(selectedList.indexOf(string));
}
public void respond(String name)
{
// do stuffs!!!!
selectedList.add(new Symtom(name)); // for example
System.out.println("Inside the respond method respond in FragmentTray class");
}
}
4.- And last but not least. When you build the fragments you must register the listener:
class MyAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragmentList;
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
fragmentList = new ArrayList<Fragment>();
Fragment fragmentBodyPart = new FragmentBodyPart();
Fragment fragmentTray = new FragmentTray();
Fragment fragmentGeneralSymptoms = new FragmentGeneraSymptoms();
// this is important*********************************
fragmentGeneraSmptoms.setTrayListener(fragmentTray);
fragmentList.add(fragmentBodyPart);
fragmentList.add(fragmentGeneralSymptoms);
fragmentList.add(fragmentTray);
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
Fragment fragment = null;
Bundle bundle = new Bundle();
bundle.putString("key", selectedProfileName);
if (arg0 == 0) {
fragment = (Fragment) fragmentList.get(0);
fragment.setArguments(bundle);
}
if (arg0 == 1) {
fragment = (Fragment) fragmentList.get(1);
fragment.setArguments(bundle);
}
if (arg0 == 2) {
fragment = (Fragment) fragmentList.get(2);
}
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragmentList.size();
}
}
I hope that it helps.