android reset/reload fragment data - android

I use a ViewPager to create 3 Fragments on Activity_1, this is the ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment1 tab1 = new Fragment1();
return tab1;
case 1:
Fragment2 tab2 = new Fragment2();
return tab2;
case 2:
Fragment3 tab3 = new Fragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
This is Activity_1 which holds all Fragments, and automatically shows Fragment_1 when Activity_1 is opened :
public class Activity1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
tab_layout.addTab(tab_layout.newTab().setText("Frag1"));
tab_layout.addTab(tab_layout.newTab().setText("Frag2"));
tab_layout.addTab(tab_layout.newTab().setText("Frag3"));
final ViewPager view_pager = (ViewPager) findViewById(R.id.viewpager);
final ViewPagerAdapter adapter = new ViewPagerAdapter
(getSupportFragmentManager(), tab_layout.getTabCount());
view_pager.setAdapter(adapter);
view_pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab_layout));
tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
view_pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
Every Fragment can go to Activity_2.
Fragment_3 holds data that can be edited on Activity_2.
My Problem:
When edit data from Activity_2 and back to Activity_1 using the back button,
data in Fragment_3 is still old, not changed with the edited data from Activity_2.
But when close Activity_1 and open it again, data in Fragment_3 is changed.
I think I need reset or reload Fragment_3 when I come back to Activity_1 from Activity_2, but I don't know how.
update,
this is Activity_2:
public class Activity2 extends AppCompatActivity {
TextView tv_id;
String id;
TextView tv_d;
Button bt_add, bt_remove;
String str_find;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent i = getIntent();
id = i.getStringExtra("id");
tv_id = (TextView)findViewById(R.id.tv_DetailId);
tv_id.setText(id);
tv_d = (TextView)findViewById(R.id.tv_Detail);
bt_add = (Button)findViewById(R.id.bt_detail_add);
bt_remove = (Button)findViewById(R.id.bt_detail_remove);
str_find = "example";
try {
final File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
xml_root = text.toString();
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] data1 = new byte[1024];
while ( -1 != (len = in.read(data1)) ){
if(new String(data1, 0, len).contains(str_find)){
bt_add.setVisibility(View.GONE);
tv_d.setText("yes");
bt_remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//something to edit data on Test.txt
}
});
}
else {
bt_remove.setVisibility(View.GONE);
tv_d.setText("no");
bt_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//something to edit data on Test.txt
}
});
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

in your onResume() method you can have a condition check
view_pager.setCurrentItem(last_frag);
where last_frag is a global integer whose value you set everytime in on page change listener.
this will refresh your fragment.
In your Activity1.java
make the following changes
private ViewPager view_pager; will be your global variable
and remove final ViewPager during initialization.
Make it like this in onCreate() Method
view_pager = (ViewPager) findViewById(R.id.viewpager);
private int last_frag = 0; will be your global variable in Activity1.java
#Override
public void onTabSelected(TabLayout.Tab tab) {
view_pager.setCurrentItem(tab.getPosition());
last_frag = tab.getPosition();
}

Related

How to provide listeners for different fragment in a viewpager from a button in activity

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;
}
}

slider a pager from onBackPressed

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.

ViewPager Fragments And CircleIndicator Re-Create Itself

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?

How to re create the fragment in viewpager

I have a viewpager with 5 tabs , each tab is fragment showing different data to user , each fragment have recycleview inside itself , and i need to re insert updated data into the recyclerview when user change the tab, and I need to update the view
Every time I swipe to a tab, a new instance of the fragment in that tab needs to load so that data will be updated.
I have tried:
1- I used FragmentStatePagerAdapter (nothing happens)
2- I Override getItemPosition method to return PagerAdapter.POSITION_NONE; (nothing happens)
3- setOffscreenPageLimit(0) (Nothing happens)
4- refresh function inside each fragment to be called onTabSelected
(gives nullPointerException)
How can i recreate fragment from scratch each time user change the tab
i really need to know.
I have been struggling with this problem for a week with no progress. I appreciate any help, be it a hint, a comment, a suggestion.
Let me know what code should I post, Thanks.
Edit:
my codes:
MainActivity:
public class Sefaresh_activity3 extends AppCompatActivity implements Serializable, Sefaresh3_interface {
Context context;
Toolbar mtoolbar;
private List<Food> food_list = new ArrayList<>();
MyPagerAdapter adapter;
Custom_TabLayout mTabLayout;
ViewPager mpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sefaresh_activity3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
}
context = this;
sqlHelper = new SqlHelper(this);
setupTabs();
private void setupTabs() {
mtoolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mtoolbar);
SpannableString s = new SpannableString(getTitle());
s.setSpan(new TypefaceSpan(this, "IRAN Sans Bold.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setTitle(s);
try {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} catch (Exception e) {
L.m("something is wrong in toolbar section");
}
adapter = new MyPagerAdapter(getSupportFragmentManager());
mTabLayout = (Custom_TabLayout) findViewById(R.id.tab_layout);
mpager = (ViewPager) findViewById(R.id.viewpager);
mpager.setAdapter(adapter);
mTabLayout.setTabsFromPagerAdapter(adapter);
mTabLayout.setupWithViewPager(mpager);
mpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
L.m("tab selected" + tab.getPosition());
mpager.setCurrentItem(tab.getPosition());
// Sefaresh3_fragment all_fragment = (Sefaresh3_fragment) adapter.getFragment_all();
// sefaresh3_fragment.onRefresh();
// Sefaresh3_fragment sefaresh3_fragment = (Sefaresh3_fragment) adapter.fragment_all;
// adapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
// public ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
Fragment fragment_all;
Fragment fragment_pizza;
Fragment fragment_sandwich;
Fragment fragment_salad;
Fragment fragment_coca;
public Fragment getFragment_coca() {
return fragment_coca;
}
public Fragment getFragment_all() {
return fragment_all;
}
public Fragment getFragment_pizza() {
return fragment_pizza;
}
public Fragment getFragment_sandwich() {
return fragment_sandwich;
}
public Fragment getFragment_salad() {
return fragment_salad;
}
String[] tabs = {
"products",
"new products",
"featured",
"star",
"star2"
};
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
public MyPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.sefaresh3_tabs);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int num) {
Fragment fragment = null;
orders = new Orders();
orders.setOrders(all_orders);
switch (num) {
case 0:
// fragment_all = Sefaresh3_fragment.newInstance("all", "");
// return new Sefaresh3_fragment().newInstance("all","");
return Sefaresh3_fragment.newInstance("all","");
case 1:
fragment_pizza = Sefaresh3_fragment.newInstance("pizza", "");
return fragment_pizza;
case 2:
fragment_sandwich = Sefaresh3_fragment.newInstance("sandwich", "");
return fragment_sandwich;
case 3:
fragment_salad = Sefaresh3_fragment.newInstance("salad", "");
return fragment_salad;
case 4:
fragment_coca = Sefaresh3_fragment.newInstance("coca", "");
return fragment_coca;
default:
return fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 5;
}
}
thanks for everybody suggestions , after one week struggling with this problem I found the solution.
I tried several methods but finally I just found the solution.
I used Broadcast receiver to tell the fragment update the list , and every time I need to update the fragments to update the data list , I call the broadcaster. its awesome and it works well
If anyone had the same problem I will be happy to help him :) thanks.

Open fragment from a fragment in android

I have a Activity extending to FragmentActivity which has 4 fragments. I now want to open fragment2 on button click which is present in fragment1.
In short I want to switch from fragment1 to fragment 2 on button click.
My code is:
public class SampleActivity extends FragmentActivity{
static ViewPager mViewPager;
PagingAdapter TabAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new PagingAdapter(getSupportFragmentManager(), this);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(TabAdapter);
}
public class PagingAdapter extends FragmentPagerAdapter {
private Context context;
public PagingAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0:
return context.getString(R.string.page_tab_1);
case 1:
return context.getString(R.string.page_tab_2);
case 2:
return context.getString(R.string.page_tab_3);
case 3:
return context.getString(R.string.page_tab_4);
}
return "Fragment " + (position + 1);
}
}
public class Fragment1 extends Fragment{
Button btn_close = (Button) mydeals.findViewById(R.id.btn_close);
btn_all.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Needs to open fragment2 here.
});
}
I have tried shifting using id but fragment4 is opening by the below code
ViewPager viewpager = DealsActivity.mViewPager;
viewpager.setCurrentItem(getId());
In your Fragment1 layout, add the attribute android:onClick="buttonClickMethod" in your Button definition. Then in your activity, add the following method :
public void buttonClickMethod(View v) {
// some code to execute after button click
// ....
// You can open fragment 2 here, like this :
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.LAYOUT_ID_FOR_FRAGMENT2, FRAGMENT2);
ft.commit();
}
Note that the name of that method is the same one defined in android:onClick attribute.

Categories

Resources