i have a main class that hold a actionbarsherlock with tabs and viewpager
here is it:
public class HSG_Handball extends SherlockFragmentActivity
{
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
TextView tabCenter;
TextView tabText;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Alle Spiele"), Spiele.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Tabelle"), Tabelle.class, null);
}
public static class TabsAdapter extends FragmentPagerAdapter 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>();
static final class TabInfo
{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args)
{
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager)
{
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args)
{
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount()
{
return mTabs.size();
}
#Override
public Fragment getItem(int position)
{
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageSelected(int position)
{
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state)
{
}
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++)
{
if (mTabs.get(i) == tag)
{
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
}
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
SubMenu subMenu1 = menu.addSubMenu("Aktive");
subMenu1.add("Herren 1");
subMenu1.add("Herren 2");
subMenu1.add("Herren 3");
subMenu1.add("Damen 1");
subMenu1.add("Damen 2");
MenuItem subMenu1Item = subMenu1.getItem();
subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
SubMenu subMenu2 = menu.addSubMenu("Jugend");
subMenu2.add("männl. A");
subMenu2.add("weibl. A");
subMenu2.add("männl. B1");
subMenu2.add("männl. B2");
subMenu2.add("männl. C");
subMenu2.add("männl. D");
subMenu2.add("E-Jugend");
MenuItem subMenu2Item = subMenu2.getItem();
subMenu2Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(!item.getTitle().toString().equals("Active") || !item.getTitle().toString().equals("Jugend"))
{
new Spiele().FormatiereSpieleSeite(item.getTitle().toString());
}
return super.onOptionsItemSelected(item);
}
}
the second class (Spiele) is a listfragment with a custom base adapter.
The class looks so:
public class Spiele extends ListFragment
{
String ligaId = "0";
SpieleAdapterFuerCustomList adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.spiele, container, false);
List<String> dateAndSchiri = new ArrayList<String>();
dateAndSchiri.add("DATUM · Schiri 1 : Schiri 2");
dateAndSchiri.add("DATUM · Schiri 1 : Schiri 2");
dateAndSchiri.add("DATUM · Schiri 1 : Schiri 2");
List<String> heim = new ArrayList<String>();
heim.add("HSG Nieder-Roden");
heim.add("SG Bruchköbel");
heim.add("LOL Idiotenklupp");
List<String> gast = new ArrayList<String>();
gast.add("KG Wallau");
gast.add("DJ G4bby");
gast.add("Hanzup Motherf*ckers");
adapter = new SpieleAdapterFuerCustomList(getActivity(), dateAndSchiri, heim, gast);
setListAdapter(adapter);
return view;
}
public void FormatiereSpieleSeite(String mannschaft)
{
// aktive
if(mannschaft.equals("Herren 1"))
ligaId = "X0";
if(mannschaft.equals("Herren 2"))
ligaId = "00151350asd0";
if(mannschaft.equals("Herren 3"))
ligaId = "00151asdad000000000000000001000";
if(mannschaft.equals("Damen 1"))
ligaId = "001513asdad0000000007000";
if(mannschaft.equals("Damen 2"))
ligaId = "0015135asd0000000000003000";
// jugend
if(mannschaft.equals("männl. A"))
ligaId = "0015135asdasd0000000000001000";
if(mannschaft.equals("weibl. A"))
ligaId = "";
if(mannschaft.equals("männl. B1"))
ligaId = "001513asdasd0000000000000002000";
if(mannschaft.equals("männl. B2"))
ligaId = "00151350asd05502000000000000001000";
if(mannschaft.equals("männl. C"))
ligaId = "0015asdasd503000000000000001000";
if(mannschaft.equals("männl. D"))
ligaId = "001513504501asdsad0000001000";
if(mannschaft.equals("E-Jugend"))
ligaId = "0015135asdasd000000000003000";
System.out.println(ligaId + "Das ist liga");
List<String> dateAndSchiri = new ArrayList<String>();
dateAndSchiri.add("DATUM as Schiri 2");
dateAndSchiri.add("DATUMasas Schisdfsdfri 2");
dateAndSchiri.add("DATUMasas Schirsdfsfi 2");
List<String> heim = new ArrayList<String>();
heim.add("HSG Nieder-sdfRoden");
heim.add("SG Brucsdfhköbel");
heim.add("LOL Idiosdfsdftenklupp");
List<String> gast = new ArrayList<String>();
gast.add("KG Walsdfsflau");
gast.add("DJ G4sdfsfbby");
gast.add("Hanzusdfsfp Motherf*ckers");
adapter = new SpieleAdapterFuerCustomList(getActivity(), dateAndSchiri, heim, gast);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
All is ok and run fine.
On the "main"-class. The class that holds the viewpager and tabsactionbar have menus. If the user click on one of them it must load a new ListFragment. Or a new BaseAdapter(?).
I want that the ListFragment (class: Spiele) is updatet.
But how can i do that?
How update my ListFragment?
Why this ArrayList with TabInfo? Why not use an ArrayList with Fragments directly. And not in the adapter but in the Activity itself?
In this case you could do something like this:
1.
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args)
{
tab.setTabListener(this);
Fragment f = Fragment.instantiate(mContext, clss.getName(), args);
mFragments.add(f);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
2.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(!item.getTitle().toString().equals("Active") || !item.getTitle().toString().equals("Jugend"))
{
Fragment f = mFragments.get(getSupportActionBar().getSelectedTab().getPosition());
((Spiele)f).FormatiereSpieleSeite(item.getTitle().toString());
}
return true;
}
If I understand you correctly all you want to do is change the adapter. Right?
The solution is easyer than i think.
These https://stackoverflow.com/a/7393477/1231245 have helped me to find the FragmentTag from the first Fragment in ViewPager.
I can easilie create and set the adapter in the onOptionsItemSelected method.
Here is it:
List<String> dateAndSchiri = new ArrayList<String>();
dateAndSchiri.add.....
List<String> heim = new ArrayList<String>();
heim.add.....
List<String> gast = new ArrayList<String>();
gast.add.....
SpieleAdapterFuerCustomList adapter = new SpieleAdapterFuerCustomList(getBaseContext(), dateAndSchiri, heim, gast);
Spiele articleFrag = (Spiele) getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.pager+":0");
articleFrag.setListAdapter(adapter);
you can create a new adapter with different ArrayList's with different click on menu...
Related
i have a problem on android eclipse with fragments in a viewpager. When an home activity starts i show an actionbar tabs and first fragment on the screen. When i swipe to next fragment and then back to first fragment, first fragment contents are still on the screen. But on the other hand if a swipe 2 times to right and go back first fragment, its contents are lost and blank screen is shown. My codes are below. How to retain each fragment content either it is shown or is visible ? any help is appreciated. Thanx in advance.
HomeActivity.java
public class HomeActivity extends FragmentActivity implements TabListener {
private String[] menuItems = null;
private ActionBar bar = null;
private ViewPager viewPager = null;
private TabsAdapter tabsAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setPageMargin(10);
menuItems = getResources().getStringArray(R.array.menuTitles);
bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabsAdapter = new TabsAdapter(this, viewPager);
for (int i = 0; i < menuItems.length; i++) {
switch (i) {
case 0:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NewsFeedActivity.class, null);
break;
case 1:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NotificationActivity.class, null);
break;
case 2:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NewsFeedActivity.class, null);
break;
case 3:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NotificationActivity.class, null);
break;
case 4:
tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
NewsFeedActivity.class, null);
break;
default:
break;
}
}
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
// Restore selected tab
int saved = savedInstanceState.getInt("tab", 0);
if (saved != getActionBar().getSelectedNavigationIndex())
getActionBar().setSelectedNavigationItem(saved);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public static class TabsAdapter extends FragmentPagerAdapter 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>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mContext, "Reselected!", Toast.LENGTH_SHORT).show();
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mContext, "gokay!", Toast.LENGTH_SHORT).show();
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(),
info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
}
NewsFeedActivity.java
public class NewsFeedActivity extends Fragment {
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
private ArrayList<String> xmlList = null;
private XMLParser parser = null;
private String xml = "";
private Document doc = null;
private NodeList nl = null;
private View view = null;
private Element e = null;
private ListView listNewsFeed = null;
private static Bundle args = null;
private static NewsFeedActivity newsFeed = null;
private ArrayAdapter<String> adapter = null;
public static NewsFeedActivity newInstance(int page, String title) {
newsFeed = new NewsFeedActivity();
args = new Bundle();
args.putInt("Page", page);
args.putString("newsFeed", title);
newsFeed.setArguments(args);
return newsFeed;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_news_feed, container, false);
if (getActivity().getActionBar().getSelectedTab().getPosition() == 0) {
new NewsFeeder().execute("");
}
return view;
}
private class NewsFeeder extends AsyncTask<String, String, String> {
private ProgressDialog mProgressDialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Haber kaynağı yenileniyor..");
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
xmlList = new ArrayList<String>();
try {
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL); // getting XML
Log.i("gokay", xml);
doc = parser.getDomElement(xml); // getting DOM element
nl = doc.getElementsByTagName(KEY_ITEM);
return null;
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
Log.e("gokay", e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mProgressDialog.dismiss();
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
xmlList.add(parser.getValue(e, KEY_ID));
xmlList.add(parser.getValue(e, KEY_NAME));
xmlList.add("Rs." + parser.getValue(e, KEY_COST));
xmlList.add(parser.getValue(e, KEY_DESC));
}
listNewsFeed = (ListView) view.findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, xmlList);
listNewsFeed.setAdapter(adapter);
// onFoodMenuItemsDBAddFinished();
}
}
}
try using
setRetainInstance(true);
in oncreate() fragment
I have create an app the layout have three tab in Android 2.3. Each tab has one fragment, and in each fragment, there has a list view. All the data show in list view is from internet, the data always change, so I want to reload the data every time when I watch that fragment. For example, I am watching the "tab1" now, when I click "tab2" the data in "tab2" will reload, and when I click back to "tab1" the data in "tab1" will also reload again. I tried
ft.detach(frg);
ft.attach(frg);
ft.commit();
but always have errors.
Here is my codes.
MainActivity
public class MainActivity extends ActionBarActivity {
private ViewPager pager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = new ViewPager(this);
pager.setId(R.id.pager);
setContentView(pager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), pager);
mTabsAdapter.addTab(bar.newTab().setText("tab1"), Tab1.class, null);
mTabsAdapter.addTab(bar.newTab().setText("tab2"), Tab2.class, null);
mTabsAdapter.addTab(bar.newTab().setText("tab3"), Tab3.class, null);
}
}
Tab1
public class Tab1 extends ListFragment{
private String result;
protected ArrayAdapter listAdapter;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/sample.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
items.clear();
Thread t = new Thread(new sendPostRunnable());
t.start();
listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter);
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "Name: "+jobject.getString("name")+"\n";
temp += "Email: "+jobject.getString("email");
items.add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
listAdapter.notifyDataSetChanged();
}
});
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
TabsAdapter
public class TabsAdapter extends FragmentPagerAdapter implements TabListener, OnPageChangeListener{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final String TAG = "";
static final class TabInfo{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args){
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ActionBar bar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = bar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(Tab tab, Class<?> clss, Bundle args){
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i = 0; i<mTabs.size(); i++){
if (mTabs.get(i) == tag){
mViewPager.setCurrentItem(i);
}
}
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
Impelement some interface like OnMyRefreshListener in your fragment and then:
public void onPageSelected(int position) {
((OnMyRefreshListener)pagerViewAdapter.getItem()).onMyRefresh();
}
I am facing same problem in my previous app.
No more changes just add one line in your MainActivity.java
viewPager.setOffscreenPageLimit();
if you have a three tab then put viewPager.setOffscreenPageLimit(3);.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list_tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(4);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
Document
I have create a listview in a fragment in a tab in Android 2.3. I want to change the data in listview when I click the tab. For example, in "tab1" I can see "1,2,3" in listview, then I click to "tab2" and click back to "tab1", the listview change to show "a,b,c". I have create a refresh() method, and call it in onPageSelected, but it always got NullPointerException.
Here is my code:
List_View
public class List_View extends ListFragment{
protected ArrayAdapter listAdapter;
private ArrayList<String> items = new ArrayList<String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
items.add("1");
items.add("2");
items.add("3");
listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter);
return rootView;
}
public void refresh(){
items.clear();
listAdapter.notifyDataSetChanged();
items.add("a");
items.add("b");
items.add("c");
listAdapter.notifyDataSetChanged();
}
}
TabsAdapter
public class TabsAdapter extends FragmentStatePagerAdapter implements TabListener, OnPageChangeListener{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final String TAG = "";
private List_View list_view;
static final class TabInfo{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args){
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ActionBar bar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = bar;
mViewPager = pager;
mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(Tab tab, Class<?> clss, Bundle args){
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
list_view.refresh();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i = 0; i<mTabs.size(); i++){
if (mTabs.get(i) == tag){
mViewPager.setCurrentItem(i);
}
}
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
I have create a refresh() method, and call it in onPageSelected, but
it always got NullPointerException
You have
private List_View list_view;
And you have
list_view.refresh();
But i don't see any code that initialized list_view.
Fragment to Fragment communication is done through the associated Activity.
http://developer.android.com/training/basics/fragments/communicating.html
So use a interface as a callback to the activity from fragment in tab2 and then communicate to List_View and change the list accordingly.
I have a fragment activity with TabHost and ViewPager inside it.
There are two tabs for the activity: the List tab and the Map tab.
On the List tab I've got list of my data (some institutions) and on the Map tab (using Google Maps API) I am displaying that institutions on the map with markers.
When activity is opened default tab is List. Swiping from right to left, or selecting Map tab brings me to the Map with markers.
The problem is, when I'm selecting the List tab again I've got a black content in stead of ListView and it's items. However, when from the List tab I select the Map tab again, Map shows correctly.
Here is activity source:
public class Institutions extends FragmentActivity {
public static final int TAB_LIST = 0;
public static final int TAB_MAP = 1;
private TabHost mTabHost;
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.institutions);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(1);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
View v = createTab(TAB_LIST);
mTabsAdapter.addTab(mTabHost.newTabSpec("list").setIndicator(v),
InstitutionList.class, null);
v = createTab(TAB_MAP);
mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator(v),
InstitutionMap.class, null);
TextView activity_title = (TextView) findViewById(R.id.activity_title);
activity_title.setText(getIntent().getStringExtra(
Institution.INSTITUTION_TITLE));
}
private View createTab(int type) {
View v = getLayoutInflater().inflate(R.layout.tab, null);
TextView label = (TextView) v.findViewById(R.id.label);
ImageView icon = (ImageView) v.findViewById(R.id.icon);
icon.setVisibility(View.GONE);
icon.getLayoutParams().width = 1;
icon.getLayoutParams().height = 1;
switch (type) {
case TAB_LIST:
label.setText(getString(R.string.list_title));
break;
case TAB_MAP:
label.setText(getString(R.string.map_title));
break;
default:
break;
}
return v;
}
}
Here is the source for TabsAdapter:
public class TabsAdapter extends FragmentStatePagerAdapter implements
TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<? extends Fragment> clss;
private final Bundle args;
private Tab tab;
TabInfo(Class<? extends Fragment> _class, Bundle _args) {
clss = _class;
args = _args;
tab = null;
}
}
static class TabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public TabFactory(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost,
ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, Class<? extends Fragment> clss,
Bundle args) {
tabSpec.setContent(new TabFactory(mContext));
TabInfo info = new TabInfo(clss, args);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
if (info.tab == null) {
info.tab = (Tab) Fragment.instantiate(mContext,
info.clss.getName(), info.args);
}
return info.tab;
}
#Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
for (int i = 0; i < getCount(); i++) {
if (i == position)
continue;
Tab t = mTabs.get(i).tab;
if (t != null) {
t.onTabUnselected();
}
}
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Hey, I am trying to convert my existing App using Tabhost and Activities to a Action Bar based App with fragments. In this process a ran into the issue to implement Expandable Lists.
I haven´t found any simple example in the internet on how to implement this Expandable List. As ExpandableListActivity has no counterpart for fragments I think I need to use and extend ListFragment but as I am quite new to android I haven´t got any clue how. :)
I would be glad if someone could shed some light on how to use an expandable list with fragments.
Thanks.
Attached is also a snippet of my existing code.
Fragment 1 with two spinners already
public class Configurator_Fragment extends SherlockListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
}
final View v = inflater.inflate(R.layout.configurator_layout,
container, false);
final Spinner spinner = (Spinner) v
.findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity(), R.array.array1,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Spinner spinner2 = (Spinner) v.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
getActivity(), R.array.array2,
android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
return v;
}
}
FragmentActivity
public class TabActivity extends SherlockFragmentActivity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_navigation);
if (savedInstanceState == null) {
Fragment newFragment = new Configurator_Fragment();
Fragment newFragment2 = new SecondFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.pager, newFragment, "First");
ft.add(R.id.pager, newFragment2, "Second");
ft.commit();
}
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getSupportActionBar().newTab().setText("Fragment 1");
ActionBar.Tab tab2 = getSupportActionBar().newTab().setText("Fragment 2");
mViewPager = (ViewPager)findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager);
mTabsAdapter.addTab(tab1, Configurator_Fragment.class, null);
mTabsAdapter.addTab(tab2, SecondFragment.class, null);
if (savedInstanceState != null) {
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt("index"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("index", getSupportActionBar().getSelectedNavigationIndex());
}
public static class TabsAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ActionBar mBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private FragmentTransaction mCurTransaction = null;
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ActionBar bar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mBar = bar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<? extends Fragment> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
A couple disclaimers first...
1) I haven't used ABS, so I'm not sure what changes that would make.
2) My ExpandableListView is backed by a database, not arrays. I say this becasue it looks like you are using arrays. I post this anyway in the hopes it might still provide you with some direction.
That said, I've done it simply by extending Fragment.
public class EventListFragment extends Fragment {
private AttendanceDB mDbHelper;
public static Cursor mGroupsCursor;
private MyExpandableListAdapter mAdapter;
private String mGroup;
private String mChild;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.explistfragment, container, false);
header = (TextView) v.findViewById(R.id.header1);
header.setText(R.string.event_header);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle extras = getIntent().getExtras();
mGroup = extras.getString("Group");
mChild = extras.getString("Child");
mDbHelper = new AttendanceDB(getActivity());
mDbHelper.open();
fillData(mGroup, mChild);
}
private void fillData(String group, String child) {
ExpandableListView lv;
mGroupsCursor = mDbHelper.fetchGroup(group);
getActivity().startManagingCursor(mGroupsCursor);
mGroupsCursor.moveToFirst();
lv = (ExpandableListView) getActivity().findViewById(R.id.explist);
mAdapter = new MyExpandableListAdapter(mGroupsCursor, getActivity(),
R.layout.explistlayout,
R.layout.explistlayout1,
new String[] { "_id" },
new int[] { android.R.id.text1 },
new String[] { child },
new int[] { android.R.id.text1 });
lv.setAdapter(mAdapter);
}
public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
public MyExpandableListAdapter(Cursor cursor, Context context,
int groupLayout, int childLayout, String[] groupFrom,
int[] groupTo, String[] childrenFrom, int[] childrenTo) {
super(context, cursor, groupLayout, groupFrom, groupTo,
childLayout, childrenFrom, childrenTo);
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
Cursor childCursor = mDbHelper.fetchChildren(mGroup, groupCursor
.getString(groupCursor
.getColumnIndex(AttendanceDB.EVENT_ROWID)));
getActivity().startManagingCursor(childCursor);
childCursor.moveToFirst();
return childCursor;
}
}
}