I need to change the slides of my pager programmatically when backbutton is pressed in the wrapper activity, but when I call pager.setCurrentItem(1) inside the onBackPressed the application is being closed.
Code:
public class MainActivity extends FragmentActivity {
static final int NUM_ITEMS = 3;
static int fSelected = 1;
MyAdapter mAdapter;
ViewPager mPager;
// ADAPTER
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstFragment.init(position);
case 1:
return SecondFragment.init(position);
case 2:
return ThirdFragment.init(position);
default:
return null;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context mContext = getApplicationContext();
playAppearAnimation(mContext);
// ANIM
playAppearAnimation(getApplicationContext());
final ViewPager mPager = findViewById(R.id.pager);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
//disabilita lo scroll by touch0
mPager.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return false;
}
});
// BACK TO RETRIEVE PASSWORD
TextView button = (TextView)findViewById(R.id.lost_password);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
/*
button = (Button)findViewById(R.id.goto_last);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {+
mPager.setCurrentItem(NUM_ITEMS-1);
}
});*/
// ANIMAZIONE DEL RECUPERA PASSWORD
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
// NASCONDO LOST PASSWORD
View lostPassword = (TextView)findViewById(R.id.lost_password);
//Toast.makeText(getApplicationContext(),""+position, Toast.LENGTH_LONG).show();
//>> HIDE / UNHIDE lost password
switch(position){
case 0:
fSelected = 0;
lostPassword.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out));
break;
case 1:
fSelected = 1;
lostPassword.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in));
break;
case 2:
fSelected = 2;
lostPassword.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out));
break;
}
}
});
}
public void playAppearAnimation(Context context){
ImageView logo = findViewById(R.id.logo);
ImageView logotype = findViewById(R.id.logotype);
logo.startAnimation(AnimationUtils.loadAnimation(context, R.anim.logo_anim));
logotype.startAnimation(AnimationUtils.loadAnimation(context, R.anim.logo_anim));
com.ubris.design.test1.NonSwipeableViewPager pager = findViewById(R.id.pager);
pager.startAnimation(AnimationUtils.loadAnimation(context, R.anim.anim_fragments));
}
#Override
public void onBackPressed() {
mPager.setCurrentItem(0);
}
Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v4.view.ViewPager.setCurrentItem(int)' on a null
object reference
at com.ubris.design.test1.MainActivity.onBackPressed(MainActivity.java:155)
at android.app.Activity.onKeyUp(Activity.java:2826)
at android.view.KeyEvent.dispatch(KeyEvent.java:2766)
at android.app.Activity.dispatchKeyEvent(Activity.java:3146)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:353)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4742)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4713)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4249)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4302)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4268)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4395)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4276)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4452)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4249)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4302)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4268)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4276)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4249)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4302)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4268)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4428)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4589)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2512)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:2106)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:2097)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2487)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:356)
at android.os.Looper.loop(Looper.java:138)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)italic
Remove super.onBackPressed() from the code - that's what usually closes the app in such case.
UPD.: as you posted the code, the problem is clear now.
Change final ViewPager mPager = findViewById(R.id.pager); to mPager = findViewById(R.id.pager); to assign its value instead of creating local variable.
Related
I am trying to create a form using fragments in a viewpager which is a step by step process.
there are 6 fragments in the viewpager. a "Back" button and a "Next" button(in the activity).
I want to save the form when the user clicks the "Next" button.
To the Reference here is the code
The Adapter to load the Fragments
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
Fragment fragment;
public RegistrationPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
fragment = new PersonalDetailsFragment();
break;
case 1:
fragment = new AboutMeFragment();
break;
case 2:
fragment = new HoroscopeFragment();
break;
case 3:
fragment = new EducationFragment();
break;
case 4:
fragment = new FamilyFragment();
break;
case 5:
fragment = new ExpectationFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 6;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
There are two buttons in the activity(not in fragments)
public class FormActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "FormActivity";
AppCompatButton backButton, nextButton;
CustomViewPager viewpager;
Toolbar toolbar;
ApiInterface apiInterface;
RegistrationPagerAdapter adapter;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
initilizeToolbar();
}
#Override
protected void onRestart() {
super.onRestart();
}
private void initilizeToolbar() {
apiInterface = ApiClient.getClient(getApplicationContext()).create(ApiInterface.class);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
castComponents();
}
private void castComponents() {
viewpager = findViewById(R.id.viewPager);
backButton = findViewById(R.id.backButton);
nextButton = findViewById(R.id.nextButton);
nextButton.setOnClickListener(this);
backButton.setOnClickListener(this);
GetAllDetailsOfUser();
}
#Override
public void onResume() {
initilizeToolbar();
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
public void setViewPagerData(int status) {
FragmentManager fm = getSupportFragmentManager();
adapter = new RegistrationPagerAdapter(fm, 0);
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(status);
viewpager.setPagingEnabled(false);
}
public void GetAllDetailsOfUser() {
Call<AllProfileDetails> allDetails = apiInterface.allDetails(PrefUtils.getToken(this), PrefUtils.getID(this));
allDetails.enqueue(new Callback<AllProfileDetails>() {
#Override
public void onResponse(Call<AllProfileDetails> call, Response<AllProfileDetails> response) {
AllProfileDetails all = response.body();
if (all != null) {
if (all.getStatus()) {
Data data = all.getData();
setViewPagerData(data.getProfileCurrentStatus());
status = data.getProfileCurrentStatus();
}
}
}
public void onFailure(Call<AllProfileDetails> call, Throwable t) {
Crashlytics.log(t.getLocalizedMessage());
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
}
}
}
this is Code is Fine but here is the problem...
When i save the data in Fragment1 i.e "PersonalDetailsFragment", it moves to fragment2 i.e "AboutMeFragment"
again when i click on save button for "AboutMeFragment" it runs the method of "PersonalDetailsFragment" only
please note that i call the activity buttons in fragments as
getActivity().findViewById(R.id.backButton);
getActivity().findViewById(R.id.nextButton);
You should have a interface like OnSaveTapped.
public interface OnSaveTapped{
void onSaveTapped();
}
Then make the fragments implement the interface above, ex:
public class PersonalDetailsFragment extends Fragment implements OnSaveTapped{
public void onSaveTapped(){
//do your business code here to save data
}
}
Finally ,In the activity class:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
case R.id.button_save:
((OnSaveTapped)viewpager.getCurrentFragment()).onSaveTapped();
}
Don't forget to create new method named getCurrentFragment() to return current item (fragment) in RegistrationPagerAdapter.
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment;
/**other lines of code*/
public Fragment getCurrentFragment(){
return fragment;
}
}
In my application I use 2 fragments in one activity and I have A common
button for both fragments, and I use A ViewPager with SectionsPagerAdapter.
this code works fine with my LG g3, but on older devices the button listener is inactive on startup and the text on it is of the other fragment.
and also works well after swipe once between the fragments
the onCreate function code:`
sendButton = (Button) findViewById(R.id.send_button);
// 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);
// listener on page selected - for each fragment
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
setSendButton(position);
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
mViewPager.setCurrentItem(0);
setSendButton(0);
sendButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(sendMod == 0) {
setUnitConfigurationByte(getUnitConfigurationByte());
// setFlowSetPointByte(getFlowSetPointBytes())
writeConfiguration();
}
else
{
flowSetPointFragment.sendPPvCommand();
}
}
});
}
the pager class code:
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).
switch (position)
{
case 0: {
unitConfigurationFragment = new UnitConfigurationFragment();
setSendButton(0);
return unitConfigurationFragment;
}
case 1: {
flowSetPointFragment = new FlowSetPointFragment();
setSendButton(1);
return flowSetPointFragment;
}
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
setSendButton(0);
return "UNIT CONFIGURATION";
case 1:
setSendButton(1);
return "PULSE PER VOLUME";
}
return null;
}
}
and the setter to the button
public void setSendButton(int fragment) {
if (fragment == 0) {
sendButton.setText("send units");
sendMod = 0;
}
if (fragment == 1) {
sendButton.setText("send pulse per volume");
sendMod = 1;
}
}
EDIT: The OnClick listener:
sendButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(sendMod == 0) {
setUnitConfigurationByte(getUnitConfigurationByte());
// setFlowSetPointByte(getFlowSetPointBytes())
writeConfiguration();
}
else
{
flowSetPointFragment.sendPPvCommand();
}
}
});
THANK YOU ALL!!!
Good day, I'm having a problem regarding with viewPager and CircleIndicator.
Every time I switch to another Activity or press the
TAB hardware keyboard panel (the switching tab between apps), and go back
to WelcomeActivity.java it re-create itself - circleDots and the items in the fragments (re-create fragments).
And also if I press the TAB hardware keyboard in the panel, and re-enter my app, it will not allow me to go back directly, it splash white then disappeared .
And if I click the icon to go back to my app, it re-create the fragments. Can you help me with this?
Here my code: WelcomeActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_page);
//Function Call
assignWidgetId();
//ViewPager for text AppIntro
mViewPager = (ViewPager) findViewById(R.id.viewpager_welcome_msg);
circlePageIndicator = (CirclePageIndicator) findViewById(R.id.circle_indicator);
setUpViewPager(mViewPager);
circlePageIndicator.setViewPager(mViewPager);
runnable = new Runnable() {
#Override
public void run() {
int currentPage = 0;
if(currentPage == FRAGMENT_PAGE - 1){
currentPage = 0;
}
mViewPager.setCurrentItem(currentPage,true);
handler.postDelayed(runnable,DELAY_TIME_CHANGE_SLIDE);
}
};
swipeTimer = new Timer();
try{
mVideoView = (VideoView) findViewById(R.id.yayong_welcome_video);
mVideoView.setVideoURI(uri);
mediaPlayer.setVolume(0, 0);
mVideoView.start();
} catch (Exception e){
//mImageView.setVisibility(View.VISIBLE);
}
//IF ERROR VIDEO CANNOT BE PLAYED
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
//wait for 1 seconds
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
//mImageView.setVisibility(View.VISIBLE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
if (videoCompleted) {
mVideoView.start();
mediaPlayer.setVolume(0, 0);
}
return false;
}
});
//IF COMPLETE REPEAT AGAIN - SILENT
mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
videoCompleted = true;
mVideoView.start();
mediaPlayer.setVolume(0, 0);
}
});
}
public void assignWidgetId(){
btnSignIn = (Button) findViewById(R.id.signIn);
btnSignIn.setOnClickListener(this);
btnSignUp = (Button) findViewById(R.id.signUp);
btnSignUp.setOnClickListener(this);
textViewForgotPass = (TextView) findViewById(R.id.textViewForgotPassword);
textViewForgotPass.setOnClickListener(this);
//mImageView = (ImageView) findViewById(R.id.welcome_image_backup);
}
#Override
public void onClick(View v) {
switch (v.getId()){
//GO TO LOGIN ACTIVITY
case R.id.signIn:
Intent intentSignIn = new Intent(WelcomePageActivity.this,LoginActivity.class);
startActivity(intentSignIn);
finish();
break;
//GO TO REGISTER ACTIVITY
case R.id.signUp:
Intent intentSignUp = new Intent(WelcomePageActivity.this,RegisterActivity.class);
startActivity(intentSignUp);
finish();
break;
case R.id.textViewForgotPassword:
forgotPasswordDialog();
break;
}
}
public void setUpViewPager(ViewPager viewPager){
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragments(new Welcome_First_Fragment());
adapter.addFragments(new Welcome_Fragment_Second());
adapter.addFragments(new Welcome_Fragment_Third());
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter{
private static List<Fragment> mFragmentList = new ArrayList<>();
public Adapter(FragmentManager fragmentManager){
super(fragmentManager);
}
public void addFragments(Fragment fragment){
mFragmentList.add(fragment);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
WelcomeFragments.java
public class Welcome_First_Fragment extends Fragment {
RelativeLayout relativeLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View viewRoot = inflater.inflate(R.layout.welcome_fragment_first, container,false);
relativeLayout = (RelativeLayout) viewRoot.findViewById(R.id.welcome_about_first);
return viewRoot;
}
I'm using jake wharton viewpager circleIndicator
I solved this by using System.exit(0); every time I go back to this page, so that it will not re-create the items. I know this is not the best way. Is there any alternative way?
I can't figure out why swiping between my Fragments isn't working,
Here is my custom FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new PrearrivalPlan();
case 1:
return new PrimarySurvey();
case 2:
return new Vitals();
case 3:
return new SecondarySurvey();
case 4:
return new PrepareForTravel();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 5;
}
}
And here is my activity that uses it:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private CustomViewPager viewPager;
private TabsPagerAdapter tabsPagerAdapter;
private ActionBar actionBar;
private String[] tabTitles = {"Pre-arrival Plan", "Primary Survey", "Vitals", "Secondary Survey", "Prepare for Travel"};
private int totalTabs = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (CustomViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsPagerAdapter);
viewPager.setPagingEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setOffscreenPageLimit(totalTabs);
// Remove Android icon from Action Bar
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowHomeEnabled(false);
// Add tabs to Action Bar
for (String tab_name : tabTitles) {
SpannableString s = new SpannableString(tab_name);
s.setSpan(new TypefaceSpan("helveticaneuelight.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
actionBar.addTab(actionBar.newTab().setText(s).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void updateTabTitles(int tabNumber, int checkBoxesRemaining) {
String text = tabTitles[tabNumber] + "\n (" + checkBoxesRemaining + " unchecked)";
actionBar.getTabAt(tabNumber).setText(text);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
return true;
case R.id.complete:
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
goToReport();
break;
case DialogInterface.BUTTON_NEGATIVE:
// "No" button clicked, do nothing
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to complete the checklist?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToReport() {
Intent intent = new Intent(this, Report.class);
startActivity(intent);
}
};
could it be this viewPager.setPagingEnabled(false); method? Try taking that method out, or at least setting it to true.
In AppCompatActivity , I can add the code protected void onResume() to launch some function when UI is shown or restored.
Now I created a Tabbed Activity, I add the code protected void onResume() to PlaceholderFragmentOld class , and I hope the system do someting when the UI cleanup_delete_fragment_old is shown, but the system crash and return the following error.
android.support.v4.app.SuperNotCalledException: Fragment PlaceholderFragmentOld{40e55078 #0 id=0x7f0f0070 android:switcher:2131689584:0} did not call through to super.onResume()
PlaceholderFragmentOld.java
public class PlaceholderFragmentOld extends Fragment {
private AdView adView;
private SMSRange mSmsRange;
private View mView;
private Context mContext;
private Spinner spinnerRanger;
private CheckBox chIsWriteLog;
public PlaceholderFragmentOld() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleanup_delete_fragment_old, container, false);
mView=rootView;
mContext=rootView.getContext();
return rootView;
}
#Override
protected void onResume() {
DoSometing();
}
}
CleanupDelete.java
public class CleanupDelete extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cleanup_delete);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch(position){
case 0:
fragment = new PlaceholderFragmentOld();
break;
case 1:
fragment = new PlaceholderFragmentReduce();
break;
case 2:
fragment = new PlaceholderFragmentTrim();
break;
case 3:
fragment = new PlaceholderFragmentPerson();
break;
default:
throw new IllegalArgumentException("Invalid section number");
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.Tab_Old);
case 1:
return getString(R.string.Tab_Reduce);
case 2:
return getString(R.string.Tab_Trim);
case 3:
return getString(R.string.Tab_Person);
}
return null;
}
}
}
Yes, you can add onResume() to a Fragment.
The error your getting states:
SuperNotCalledException: PlaceholderFragmentOld did not call through to super.onResume()
You need to call super.onResume() as the first line in your onResume() method, otherwise the system will complain. Something like this would work
protected void onResume(){
super.onResume();
doSomething();
}