what should I change? because I find so many errors if I change it to Fragment .. check out my code and help me fix it please
this is the package:
package com.example.ashraf.myapplication;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.widget.TextView;
and this is my class:
public class machinemessage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static tab.PlaceholderFragment newInstance(int sectionNumber) {
tab.PlaceholderFragment fragment = new tab.PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return tab.PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
I recommend you to step by step copy the code of your Activity into a Fragment. See this Stackoverflow answer to get instructions in how to convert an Activity to a Fragment.
i have been working on app (Question Answer based) . I have included view pager to swipe the image but it's only swiping same image .
code of class which call a class (where view pager is included in activity)
package com.example.joshiyogesh.puzzle;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class ExerciseOneQuestionList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_one_question_list);
}
public void questionOne(View view) {
Intent intent = new Intent(getApplicationContext(),ExerciseOneQuestions.class);
intent.putExtra("question_index",0);
startActivity(intent);
}
}
ExerciseOneQuestion.java
package com.example.joshiyogesh.puzzle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ExerciseOneQuestions extends AppCompatActivity {
ViewPager viewPager;
public int questionIndexReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_one_questions);
questionIndexReceive = getIntent().getIntExtra("question_index",1);
// questionIndexReceive =Integer.parseInt(getIntent().getStringExtra("question_index"));
viewPager = (ViewPager)findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
pager Adapter class
package com.example.joshiyogesh.puzzle;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
position = new ExerciseOneQuestions().questionIndexReceive;
Fragments fragments = new Fragments();
Bundle bundle = new Bundle();
bundle.putInt("question_no",position);
fragments.setArguments(bundle);
return fragments;
}
#Override
public int getCount() {
return 2;
}
}
fragments class
public class Fragments extends Fragment {
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater , ViewGroup container ,
Bundle savedInstanceState){
int [] image_index = {R.drawable.eightypageanswer1,R.drawable.eightypageanswer8};
Bundle bundle = getArguments();
int message = bundle.getInt("question_no");
View rootView = inflater.inflate(R.layout.fragments,container,false);
imageView = (ImageView) rootView.findViewById(R.id.imageQuestions);
imageView.setImageResource(image_index[message]);
return rootView;
}
}
for testing purpose I have considered only two images in integer, But its always swiping same image i.e first image.
instead of changing "question_index" in ExerciseOneQuestionList.java
here ...
public void questionOne(View view) {
Intent intent = new Intent(getApplicationContext(),ExerciseOneQuestions.class);
intent.putExtra("question_index",0);
startActivity(intent);
}
couldn't understand why its always showing same image ?
It seems that problem is in line
position = new ExerciseOneQuestions().questionIndexReceive;
It seems that position is always set on the same number.
I really dont know what you are doing with this " new ExerciseOneQuestions().questionIndexReceive;" line. But in standard way you should have make two fragments then add these fragments to your adapter. Rest of thing will be done by adapter , following rough code may help you :
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position); // Which Fragment should be dislpayed by the viewpager for the given position
}
#Override
public int getCount() {
return mFragments.size();
}
}
Make two fragments object in class add them in adapter by calling addFragment method and then setadapter.
I'm new beginner using Android studio I have currently watched a couple tutorials on setting up a basic swipe view which generates up to 3 all which replicate the original page known in my code as page_fragment_layout.xml. I want to take this a step further a be able to link different pages containing a range of content. In this case I want to be able to link my Activity_main.xml and page_fragment_layout.xml together by swipe. I have added my code so far I would be most appreciative of any input.
MainActivity.java
package socialdeveloper.swipecard;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager());
viewPager.setAdapter(swipeAdapter);
}
}
PageFragment.java
package socialdeveloper.swipecard;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class PageFragment extends android.support.v4.app.Fragment {
TextView textView;
public PageFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.page_fragment_layout,container,false);
textView = (TextView)view.findViewById(R.id.TestText);
Bundle bundle = getArguments();
String message = Integer.toString(bundle.getInt("count"));
textView.setText("This is the "+message+ "Swipe View Page...");
return view;
}
}
SwipeAdapter.java
package socialdeveloper.swipecard;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Hadleigh on 07/12/2015.
*/
public class SwipeAdapter extends FragmentStatePagerAdapter {
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle bundle = new Bundle();
int i = 0;
bundle.putInt("count",i+1);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
in your SwipeAdapter.java use this
` public Fragment getItem(int position) {
Fragment fragment = null;//Creates a fragment variable to hold the fragment class i create and make it a null so i can catch the error
if (position == 0) {
fragment = new PUT_THE_TITLE_OF_YOUR_ACTIVITY_YOU_WANT_TO_USE();//Calls the fragment.
}
if (position == 1) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment;
}
if (position == 2) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment.
}
return fragment;
}`
in the getItem() method to call other fragments or activities.
I am just starting to learn how to program, so sorry if this is a weird or dumb question.
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors located here.
Here is the code with the two thingies:
package com.example.ryanfolz.gridgame;
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
public class ScreenSlideActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//invalidateOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
menu.findItem(R.id.action_previous).setEnabled(mPager.getCurrentItem() > 0);
// Add either a "next" or "finish" button to the action bar, depending on which page
// is currently selected.
MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
? R.string.action_finish
: R.string.action_next);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_previous:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
The fragment is here
package com.example.ryanfolz.gridgame;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ScreenSlidePageFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
ViewGroup rootView;
private int mPageNumber;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
if(mPageNumber == 1){
rootView = (ViewGroup) inflater
.inflate(R.layout.test, container, false);
((TextView) rootView.findViewById(R.id.test)).setText("Hello");
}else {
rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_screen_slide_page, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.title_template_step, mPageNumber + 1));
}
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
}
Delete these line from your import
import android.app.FragmentManager;
import android.app.Fragment;
When your IDE ask for which class to import, you should choose these classes from support package instead, like this:
android.support.v4.app.FragmentStatePagerAdapter;
Instead of using getFragmentManager(), you should call getSupportFragmentManager()
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors
If you check the example properly they have imported
import android.support.v4.app.FragmentManager;
and not
import android.app.FragmentManager;
And also they have used
getSupportFragmentManager()
and not
getFragmentManager()
This changes is required because you are using the android support library for your fragment.
In your ScreenSlideActivity file, change
import android.app.FragmentManager;
to
import android.support.v4.app.FragmentManager;
And for ScreenSlidePageFragment, change this line
import android.app.Fragment;
into this
import android.support.v4.app.Fragment;
At last. Change all
getFragmentManager()
to
getSupportFragmentManager()
As a lot of people have been doing so far, I'm implementing the FragmentTabsPager into my app, which is using ActionBarSherlock 4.0. However, I'm lost.
Fragments, and all of Google's little ideas, plans and methods surrounding it, are confusing me. If anyone could take a look at my code and walk me through this, providing help in making it work, I would thank them a thousand times :D.
I have another project with a sort-of beginning for a ViewPager, but the Tabs just mix better, especially with them being in the ActionBar on landscape and tablets.
My code is all zipped up and ready to go over here:
http://dl.dropbox.com/u/21807195/Antonius%20College%202.zip
Thanks in advance!
I will show you my code that has a ViewPager, TabListener, and system of Fragments linked to each tab. It implements ABS, but as of yet, still crashes on Gingerbread and lower (works beautifully on ICS, though):
import java.util.ArrayList;
import library.DatabaseHandler;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
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);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
Log.v(TAG, (String)bar.getTabAt(0).getText());
}
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();
}
public int getCount() {
return mTabs.size();
}
public SherlockFragment getItem(int position) {
TabInfo info = mTabs.get(position);
return (SherlockFragment)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) {
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);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
}
And here is what one fragment looks like:
package com.davekelley.polling;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MilitaryFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.militaryfragment, container, false);
}
}
My last note would that my code still has one other issue: individual fragments do not always reload their interface after the user press back (which results in removing the entire app from the screen, regardless which tab/fragment they are on, because I have no backStack). So that's what I'm working through now. I think once I have that sorted, I'll try to figure out why I still don't have Gingerbread execution functioning properly. Either way, I hope looking through this code helps you out.
Here is a fragment with some onClickListeners:
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class LoginFragment extends SherlockFragment {
Button loginButton;
Button registerButton;
Polling activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.loginfragment, container, false);
return v;
}
public void onResume() {
super.onResume();
Log.d("Econ", "onresume");
loginButton = (Button) getActivity().findViewById(R.id.loginButton);
loginButton.setOnClickListener(loginListener);
registerButton = (Button) getActivity().findViewById(R.id.registerButton);
registerButton.setOnClickListener(registerListener);
}
public OnClickListener loginListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(loginButton.getText().toString() == "Log Out") {
activity.loginReport(2);
loginButton.setText(R.string.login);
//Remove user from dB sqllite when I know how
}
else {
Log.v("LoginF", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Logging in...");
LoginTask loginTask = new LoginTask((Polling) getActivity(), progressDialog);
loginTask.execute();
}
}
};
public OnClickListener registerListener = new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Register", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Registering new user...");
RegisterTask registerTask = new RegisterTask((Polling) getActivity(), progressDialog);
registerTask.execute();
}
};
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (Polling) activity;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onStart() {
super.onStart();
Log.d("Econ", "onstart");
}
public void onPause() {
super.onPause();Log.d("Econ", "onpause");
}
public void onStop() {
super.onStop();
Log.d("Econ", "onstop");
}
public void onDestroyView() {
super.onDestroyView();
Log.d("Econ", "ondestroyview");
}
public void onDestroy() {
super.onDestroy();
Log.d("Econ", "ondestroy");
}
public void onDetach() {
super.onDetach();
Log.d("Econ", "ondetach");
}
}
The loginTask objects that you see are actually classes that extend ASyncTask - they handle connecting to my server and registering/logging in.
I thought it would be helpful to add in one bit more of code. This is another one of my fragments, like LoginFragment, but it inflates a UI a little differently. Eventually, what you see in the while loop below, will head into an ASyncTask to acquire each question from the server, rather than the dummy string array you see:
public class EconFragment extends SherlockFragment {
private TableLayout questionContainer;
int pos = 0;
private String[] titles = {"The first title ", "hallo1","hallo2", "hallo3",
"hallo4", "hallo5","hallo6", "hallo7","hallo8", "hallo9"};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v("Econ", "onCreateView");
View v = inflater.inflate(R.layout.econfragment, container, false);
questionContainer = (TableLayout) v.findViewById(R.id.questionContainer);
//bs
int leftMargin=5;
int topMargin=5;
int rightMargin=5;
int bottomMargin=5;
while (pos < 10) {
View question = inflater.inflate(R.layout.question, null);
question.setId(pos);
TextView title = (TextView) question.findViewById(R.id.questionTextView);
title.setText(titles[pos]);
Button charts = (Button) question.findViewById(R.id.chartsButton);
charts.setId(pos);
charts.setOnClickListener(chartsListener);
TableRow tr = (TableRow) question;
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
trParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(trParams);
Log.v("econ", "while loop");
questionContainer.addView(tr);
pos++;
}
pos = 0;
return v;
}
I have ported the FragmentTabsPager Activity and associated Fragments from "Support4Demos" (Android Support library sample) to use ActionBarSherlock and true ActionBar Tabs. The sample includes an Activity that uses both a ViewPager and Tabs to switch between Fragments. The Fragments contain three kinds of ListViews. I've tested it from ICS down to Eclair (2.1). You can browse or download the code at http://code.google.com/p/sherlock-demo/.