Intent From fragment to Second Tab - android

I have tab layout in android with viewpager in my Main Activity. I have three Tab with three Fragment. And in first fragment i have button i want to intent on second tab from that button on click. how to intent please help me.
Here is my Code
public class MainActivity extends AppCompatActivity {
//Declaring All The Variables Needed
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("first", "str1");
//str1 = intent.getStringExtra("first");
Toast.makeText(MainActivity.this, "" + name, Toast.LENGTH_SHORT).show();
toolbar = (Toolbar) findViewById(R.id.toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
FragmentManager manager = getSupportFragmentManager();
ViewPagerAdapter adapter = new ViewPagerAdapter(manager);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setTabsFromPagerAdapter(adapter);
tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.drawable.tab_selector));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
setSupportActionBar(toolbar);
final FloatingActionMenu floatingActionsMenu=(FloatingActionMenu) findViewById(R.id.material_design_android_floating_action_menu);
final FloatingActionButton floatingActionButton1=(FloatingActionButton)findViewById(R.id.material_design_floating_action_menu_item1);
floatingActionButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Table", Toast.LENGTH_SHORT).show();
viewPager.setCurrentItem(0);
floatingActionsMenu.close(true);
}
});
FloatingActionButton floatingActionButton2=(FloatingActionButton)findViewById(R.id.material_design_floating_action_menu_item2);
floatingActionButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Order", Toast.LENGTH_SHORT).show();
viewPager.setCurrentItem(1);
floatingActionsMenu.close(true);
}
});
FloatingActionButton floatingActionButton3=(FloatingActionButton)findViewById(R.id.material_design_floating_action_menu_item3);
floatingActionButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Logout", Toast.LENGTH_SHORT).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.main, 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) {
Intent tologin=new Intent(MainActivity.this,LoginPage.class);
startActivity(tologin);
return true;
}
return super.onOptionsItemSelected(item);
}
}

All the fragments are within the same ViewPager and you just want to go one to another fragment you can do like this...
The view pager is in Activity but the Button is inside Fragment so you need to do this create this method inside your activity
public void navigateFragment(int position){
viewPager.setCurrentItem(position, true);
}
and call inside your OnClickListener method of fragment:
((MainActivity)getActivity()).navigateFragment(POSITION_YOU_WANNA_SELECT);
Hope this will help you.

Recommended approach : you can implement a listener in second fragment and create reference in first fragment.
after onclick of a button from 1st fragment call method of listener which is defined in second fragment.
Second approach : you can maintain a static data from 1st fragment and on click just load 2nd fragment and access that static data.

Related

Sign up activity crashes when triggered using a button

I have created a login activity which is the launcher activity. My login page has two buttons Signin or Signup. Signup button triggers another activity named Main2Activity which is a tabbed activity but it keeps crashing. Any help would be appreciated. Here's Main2Activity :
public class Main2Activity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
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);
tabLayout.setupWithViewPager(mViewPager);
//Student Sign up button clicked
Button StdSignUp = (Button)findViewById(R.id.stdsignup);
StdSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent HomePage = new Intent(Main2Activity.this,MainActivity.class);
startActivity(HomePage);
}
});
//Teacher Sign up button clicked
Button TSignUp = (Button)findViewById(R.id.tsignup);
TSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent HomePage = new Intent(Main2Activity.this, MainActivity.class);
startActivity(HomePage);
}
});
}
#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 {#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) {
switch (position)
{
case 0:
StudentSignup ss = new StudentSignup();
return ss;
case 1:
TeacherSignup ts = new TeacherSignup();
return ts;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Student Account";
case 1:
return "Teacher Account";
}
return null;
}
}
}
Here's the button that triggers the Main2Activity in the Login Acvivity's onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
});
Button mEmailSignUpButton = (Button) findViewById(R.id.Signupbtn);
mEmailSignUpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent Signup = new Intent(LoginActivity.this, Main2Activity.class);
startActivity(Signup);//this starts sign up page activity named main2activity
}
});
}
You need to add your new Activity to AndroidManifest.xml. For example:
<activity
android:name=".Main2Activity"
android:label="#string/title_main2_activity"/>

Android ViewPager refresh when swipe

My fragment is not refreshing when I swipe back, so I want to know how I can refresh it when I swipe it back. I have seen many different answers online, but I don't why they don't work in my situation. It would be highly appreciated if someone could help me out, thanks.
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
tabLayout.setupWithViewPager(mViewPager);
}
#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_main, 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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Profile tab1 = new Profile();
return tab1;
case 1:
Puzzles tab2 = new Puzzles();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile";
case 1:
return "Puzzles";
}
return null;
}
}
}
I have tried setOffscreenPageLimit(0), detach attach fragment in onTabSelected, using FragmentStatePagerAdapter, notifyDataSetChanged(), and even
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this doesn't work too. So I hope someone could help.
If you want to refresh the data in a particular Fragment, you have to do 2 things,
Store the updated data into Activity
Show the updated data in onResume() in that particular Fragment
If you want your data to be saved even after killing the app, store it in SharedPreference. Hope it helps!
On your fragment class add this.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Try adapter.notifyDataSetChanged or something like passing the new(updated) data to adapter from here.
}
}
Hope it helps.

Not able to call TablayoutActivity from AppcombatActivity

I want to call my tablayout activity , when user clicked on Item Menu from Action View Item ,
But I am getting error :
06-15 14:17:01.604: E/AndroidRuntime(1365): java.lang.NoClassDefFoundError: Failed resolution of: Linfo/muscle/reboot/activity/Wrk_plan_gain;
Here is my Main activity from where I am calling Tab layout Activity .
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
public MainActivity() {
// Required empty public constructor
}
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
SharedPreferences pref;
String diet_saved;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = this.getPreferences(1);
diet_saved=pref.getString("diettype", "main");
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#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_main, 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.workout_menu) {
startActivity(new Intent(MainActivity.this, Wrk_plan_gain.class));
finish();
return true;
}
/*if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
*/
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new KnowYourBodyFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new YourResultFragment();
title = getString(R.string.title_messages);
break;
case 3:
fragment = new YourMacroResultFragment();
title = getString(R.string.title_macro);
break;
case 4:
fragment = new DietPlanFragment();
title = getString(R.string.title_Diet);
break;
case 5:
title = getString(R.string.title_Exit);
finish();
break;
default:
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
and I am trying call this Activity
public class Wrk_plan_gain extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
public Wrk_plan_gain() {
// Required empty public constructor
}
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wrk_plan_layout_gain);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Also it will every much help full I f I can call this activity from Nav drawer Item ..
I am not able to get it work , in both cases .

ViewPager always starts from 0th position

I have a RecyclerView in a Fragment which is in a ViewPager hosted in an Activity. There's two Activities in this project MainActivity which lists items and DetailActivity which shows details about the item chosen in the first activity.
When I move from DetailsActivity to MainActivity I am always take to ViewPager Fragment position 0 which is the first Fragment. How can I restore the fragment position?
Bundle is always empty when I move from DetailActivity to MainActivity.
Here is the full code of the app.
MainActivity
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private static final String LOG = MainActivity.class.getSimpleName();
private static final String VIEWPAGER_POSITION = "currentItem";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titles);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
if (savedInstanceState != null) {
int pos = savedInstanceState.getInt(VIEWPAGER_POSITION, 0);
Log.d(LOG, "onCreate pos: " + pos);
mViewPager.setCurrentItem(pos);
} else {
Log.d(LOG, "onCreate savedInstanceState is null");
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PopularFragment(), getResources().getString(R.string.popularity));
adapter.addFragment(new RatingFragment(), getResources().getString(R.string.rating));
adapter.addFragment(new FavoriteFragment().newInstance(), getResources().getString(R.string.favorite));
viewPager.setAdapter(adapter);
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#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_main, 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);
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
int pos = mViewPager.getCurrentItem();
Log.d(LOG, "onSaveInstanceState pos: " + pos);
bundle.putInt(VIEWPAGER_POSITION, mViewPager.getCurrentItem());
}
}
Thanks.
I am shooting, when you go back from DetailActivity, look for Bundle in
this.getIntent().getExtras().getInt(VIEWPAGER_POSITION, 0)
UPDATE:
if you need persist your current position in for example SharedPreferences in onPause and retrieve it in onResume. like:
private static String MY_PAGER_TAG = "tag_of_shared_vp_position";
public void onPause(){
super.onPause();
int pos = getCurrentViewPagerPosition();//custom function, implement it by //yourself
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(MY_PAGER_TAG, pos);
editor.commit();
}
public void onResume(){
super.onResume();
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int pos = sharedPref.getInt(MY_PAGER_TAG,0);
setUpViewPagerOnPosition(pos);
}
I noticed that if I pressed the physical back button the ViewPager and RecyclerView were properly restored. So I wanted a way to set up button behavior same as onBackPressed(). Answer to which has already been posted in the question Make the “up” button behave like the “back” button on Android.
I made following changes in DetailActivity and my code started working just fine.
#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();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

NavigationDrawer not show the view

I have a Navigation Drawer with Navigation View, there are four tabs, one of them is a fragment, which includes ViewPager, ie is a host for the other fragments. Everything works fine, but when switched from fragment with ViewPager any other fragment of NavigationDrawer shows nothing. Checked logs, onCreate, onCreateView these fragments are called, but why does not display... Who knows why?
NavigationDrawer
public class NavigationDrawerHost extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
//буду использовать эту активность как хост под все фрагменты, чтобы верно работал мой drawer!
public static String WHERE_FROM = NavigationDrawerHost.class.getSimpleName();
public static Toolbar toolbar;
public static ProgressBar progressBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
private int navItemId;
private static final String NAV_ITEM_ID = "NAV_ITEM_ID";
private TextView userFirstNameTextView, userLastNameTextView;
private ImageView userPhotoImageView;
private VKAccessToken access_token; //токен это информация о правах доступа
private VKApiUser user; //текущий пользователь
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer_host);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find the toolbar view inside the activity layout
toolbar = (Toolbar) findViewById(R.id.toolbar);
// Set a Toolbar to replace the ActionBar.
setSupportActionBar(toolbar);
//setTitle(R.string.drawer_menu_posts);
// load saved navigation state if present
if (null == savedInstanceState) {
navItemId = R.id.posts_fragment;
} else {
navItemId = savedInstanceState.getInt(NAV_ITEM_ID);
}
// Find our drawer view
navigationView = (NavigationView) findViewById(R.id.nvView);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(navItemId).setChecked(true);
// если хотим добавить какие-то элементы в наш header,
// то нужно добавить их в layout, а затем инициализировать нижеприведенным способом
// Inflate the header view at runtime
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
userFirstNameTextView = (TextView) headerLayout.findViewById(R.id.user_first_name);
userLastNameTextView = (TextView) headerLayout.findViewById(R.id.user_last_name);
userPhotoImageView = (ImageView) headerLayout.findViewById(R.id.user_photo);
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
// Tie DrawerLayout events to the ActionBarToggle
drawer.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectItem(navItemId);
}
#Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(NAV_ITEM_ID, navItemId);
}
// Menu icons are inflated just as they were with actionbar
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_exit:
//quitDialog();
VKSdk.logout();
finish();
return true;
default:
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(final int itemId) {
// perform the actual navigation logic, updating the main content fragment etc
// Create a new fragment and specify the planet to show based on position
Fragment fragment = null;
Class fragmentClass = null;
switch (itemId) {
case R.id.posts_fragment:
fragmentClass = PostsFragment.class;
fragment = new PostsFragment();
break;
case R.id.albums_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.friends_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.likes_fragment:
fragmentClass = LikesFragment.class;
fragment = new LikesFragment();
break;
/*default:
fragmentClass = PostsFragment.class;*/
}
/*try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}*/
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
drawer.closeDrawers();
}
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// update highlighted item in the navigation menu
item.setChecked(true);
setTitle(item.getTitle());
navItemId = item.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
drawer.closeDrawer(GravityCompat.START);
selectItem(item.getItemId());
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
quitDialog();
} else {
getSupportFragmentManager().popBackStack();
}
}
private void quitDialog() {
AlertDialog.Builder quitDialog = new AlertDialog.Builder(this);
quitDialog.setTitle("Вы хотите выйти?");
quitDialog.setPositiveButton("Да", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//стираем БД
Delete.tables(PostTable.class, PictureTable.class, PostTableMyLikes.class, PictureTableMyLikes.class);
FlowManager.getDatabase(WallDatabase.DB_NAME).reset(NavigationDrawerHost.this);
FlowManager.getDatabase(WallDatabaseMyLikes.DB_NAME).reset(NavigationDrawerHost.this);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
quitDialog.setNegativeButton("Нет",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
quitDialog.show();
}
}
ViewPager host for fragments, which needs to display through ViewPager
//этот фрагмент является хостом для MyLikesFragment и FriendLikesFragment, так же тут содержатся табы
public class LikesFragment extends Fragment {
public static String WHERE_FROM_FRIENDS_LIKES = LikesFragment.class.getSimpleName() + "_FRIENDSLIKES";
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.likes_fragment, container, false);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Мои лайки"));
tabLayout.addTab(tabLayout.newTab().setText("Лайки друзей"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setAdapter(new LikesPagerAdapter(getChildFragmentManager()));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return v;
}
public static class LikesPagerAdapter extends FragmentPagerAdapter {
public LikesPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
//сделано так, чтобы передавать те аргументы, от которых будет зависеть функционал фрагмента
#Override
public Fragment getItem(int position) {
return (position == 0) ? new MyLikesPostsFragment() : new PostsFragment();
}
#Override
public CharSequence getPageTitle(int position) {
return (position == 0) ? "Мои лайки" : "Лайки друзей";
}
}
}
P.S. And after going to the same fragment ViewPager select several items in drawer, this should not be
The problem was that I called adapter.notifyDataSetChanged() in the main thread and onPostExecute() in AsyncTask. My carelessness...

Categories

Resources