I have a activity call "Wallet" in which there in implementation of switch case in and having another activity that contain tablayout in which 1st tab named as "Mobile" and 2nd tab named as "Data".what I want from activity "Wallet" switch case in case0: i am passing Intent to another activity that contain tablayout want to open tab "Mobile" and on case 1: Intent want to open tab "Data".How can I do that please tell me.
code for Wallet switch:-
m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mMobileRecharges);
break;
case 1:
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mDataRecharge);
break;
case 2:
Intent m_Earning= new Intent(CMyWalletScreen.this,CWalletTransactionScreen.class);
startActivity(m_Earning);
break;
}
}
});
and code for TablayOut Activity :-
public class CRechargeMain extends AppCompatActivity {
View m_Main;
private ViewPager m_ViewPager;
private Toolbar m_ToolBar;
private String[]actonBar={"Mobile Recharge","Mobile Data Recharge"};
int iDoWhat;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recharge_main);
Intent intent = new Intent();
init();
}
public void init() {
m_ToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(m_ToolBar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
m_ToolBar.setTitle("Mobile Recharge");
TabLayout m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_TabLayout.addTab(m_TabLayout.newTab().setText("Mobile"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Data Card"));// add stories tab
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
CRechargePager m_oMobilePager = new CRechargePager
(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oMobilePager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
m_ToolBar.setTitle(actonBar[tab.getPosition()]);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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_wallet, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Check following your example
m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
mMobileRecharges.putExtra("tab_position",0);
startActivity(mMobileRecharges);
break;
case 1:
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
mDataRecharge.putExtra("tab_position",1);
startActivity(mDataRecharge);
break;
case 2:
Intent m_Earning= new Intent(CMyWalletScreen.this,CWalletTransactionScreen.class);
startActivity(m_Earning);
break;
}
}
});
// CRechargeMain Activity
Add one line in your code
m_TabLayout.getTabAt(getIntent().getIntExtra("tab_position", 0)).select()
public class CRechargeMain extends AppCompatActivity {
View m_Main;
private ViewPager m_ViewPager;
private Toolbar m_ToolBar;
private String[]actonBar={"Mobile Recharge","Mobile Data Recharge"};
int iDoWhat;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recharge_main);
Intent intent = new Intent();
init();
}
public void init() {
m_ToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(m_ToolBar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
m_ToolBar.setTitle("Mobile Recharge");
TabLayout m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_TabLayout.addTab(m_TabLayout.newTab().setText("Mobile"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Data Card"));// add stories tab
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
CRechargePager m_oMobilePager = new CRechargePager
(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oMobilePager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
m_ToolBar.setTitle(actonBar[tab.getPosition()]);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// Add this line in your code
m_TabLayout.getTabAt(getIntent().getIntExtra("tab_position", 0)).select();
}
#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_wallet, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
In Wallet Activity pass 0/1 from intent.
In CRechargeMain Just add following code.
//here tab index 0 or 1
m_TabLayout.getTabAt(0).select();
Related
Basically my project have to have different toolbars, one for each fragment switched by the bottom navigation bar.
The fragment toolbars items are clickable, when I long press, shows the title item etc, but they don't perform the action. For example, When I set to show a toast when click on that item, he'll not perform. Any Suggestion? Thanks.
public class FeedFragment extends Fragment {
public static final String TAG = "Tag Free";
DialogFragment mDialog;
FloatingActionButton fab;
RevealFrameLayout reveal;
FrameLayout frame;
private ConstraintLayout layoutDialog;
boolean isOpen = false;
public FeedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
/** Toolbar **/
Toolbar myToolbar = (Toolbar) view.findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(false);
// navigation bottom
fab = getActivity().findViewById(R.id.fab_button);
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pencil_black_24dp));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction().setCustomAnimations(R.anim.hold, R.anim.slide_down);
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = new PostDialog();
dialogFragment.show(ft, "dialog");
dialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogFragmentTheme);
}
});
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
return true;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
You are not chaining to the superclass in the activity methods.
Refactor your code as below :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
break;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
break;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
break;
}
return super.onOptionsItemSelected(item);
}
Hope now your code will work fine.
I have a tab fragments app. The problem is when I go into an activity inside my app and want going back to my tabs layout it returns without the tabs row layout. I can see only the specific fragment page without the row above (the tab's row) that makes me able to navigate between the tabs.
Do you know what can I do to solve it? How can I see the tab's row too?
Thanks for any help,
This is the first tab that I want to see back from the activity:
public class Tab1MyProfile extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_my_profile, container, false);
return rootView;
}
}
This is the activity that contains code to go back to the fragment tab:
public class GameLive extends AppCompatActivity implements RecognitionListener {
private Intent intent;
private Button mStopButton;
public void stopGame (View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to finish the game?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Tab1MyProfile fragment = new Tab1MyProfile();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_live);
mStopButton = (Button) findViewById(R.id.btnEndGame);
mStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopGame(view);
}
});
}
}
And this is the activity that contains all the tab's fragment:
public class StartActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
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_start, 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 {#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:
Tab1MyProfile tab1=new Tab1MyProfile();
return tab1;
case 1:
Tab2StartGame tab2=new Tab2StartGame();
return tab2;
case 2:
Tab3StatsArea tab3=new Tab3StatsArea();
return tab3;
case 3:
Tab4Settings tab4=new Tab4Settings();
return tab4;
}
return null;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "My profile";
case 1:
return "Start Game";
case 2:
return "Stats Area";
case 3:
return "Settings";
}
return null;
}
}
}
Thank again!
What if you replace everything inside the onClick method of the DialogInterface.OnClickListener with GameLive.this.finish();. This will close the GameLive activity on click and return you to the previous activity, which should be the one that contains the missing navigation bar.
I have a Activity named as Wallet and have a Activity named as CRechargeMain which adds two frgament named as "Mobile","Data";what I want in Wallet screen I have a Listview in which in case 0: when I click I want to go to CRechargeMain and show"Mobile" tab and in case 1 : when I click I want to go CRechareMain and open tab " data" .how can I do that
code for wallet:-
m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mMobileRecharges);
break;
case 1:
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mDataRecharge);
break;
case 2:
Intent m_Earning= new Intent(CMyWalletScreen.this,CWalletTransactionScreen.class);
startActivity(m_Earning);
break;
}
}
});
code for CRechargeMain:-
public class CRechargeMain extends AppCompatActivity {
View m_Main;
private ViewPager m_ViewPager;
private Toolbar m_ToolBar;
private String[]actonBar={"Mobile Recharge","Mobile Data Recharge"};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recharge_main);
init();
}
public void init() {
m_ToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(m_ToolBar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
m_ToolBar.setTitle("Mobile Recharge");
TabLayout m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_TabLayout.addTab(m_TabLayout.newTab().setText("Mobile"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Data Card"));// add stories tab
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
CRechargePager m_oMobilePager = new CRechargePager
(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oMobilePager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
m_ToolBar.setTitle(actonBar[tab.getPosition()]);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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_wallet, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use the same intent and select tab based on the intent argument in your activity.
As my assumption you are having two activity, activity1 contains list and activity2 contains fragments.from activity1 based on conditions you have to jump to activity2 (fragments).Just call as below
Intent i =New Intent(this,CRechargeMain.class);
i.putExtra("",0);
startActivity(i);
In Activty2 on create method based on conditions you have to set fragment to load.
FragmentManager FM = getFragmentManager();
FM.beginTransaction().replace(R.id.content_frame, detail).commit();
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
intent.putExtra("doWhat", 0);
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
intent.putExtra("doWhat", 1);
In your receiving activity:
int iDoWhat = intent.getIntExtra("doWhat", -1);
Then make your decision based on the value of iDoWhat.
int iDoWhat = getIntent().getIntExtra("doWhat",-1);
switch (iDoWhat) {
case -1:
//select tab 0
break;
case 0:
//select tab 0
break;
case 1:
//select tab 1
break;
}
You have to write the code for selecting the tab now you know which one.
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...
I have an activity that uses a fragmentpageradapter to create an ics style actionBar. Each page needs to update the actionBar though. Is there a way I can call onCreateOptionsMenu in my onPageSelected?
I've trimmed a lot of the code out from the example below for simplicity's sake.
public class ListFragmentViewPagerActivity extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread_view);
ViewPager pager = (ViewPager) findViewById(android.R.id.list);
pager.setAdapter(new ExamplePagerAdapter(getSupportFragmentManager()));
TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
indicator.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
});
}
public class ExamplePagerAdapter extends FragmentPagerAdapter implements TitleProvider{
public ExamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return URLS.size();
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ThreadFragment();
// set arguments here, if required
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public String getTitle(int pos) {
return TITLES.get(pos);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.thread_menu, menu);
if (type.equals("xda")) {
menu.removeItem(R.id.ss_view);
}
//This worked when I only needed to call it one time. I need to update this menu for each page in my viewPager though.
if (isFav) {
menu.getItem(2).setIcon(R.drawable.fav_ab);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.ss_view:
Intent ssi = new Intent(this, SSActivity.class);
ssi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle b = new Bundle();
ssi.putExtras(b);
startActivity(ssi);
break;
case R.id.restart:
break;
case R.id.fav_ab:
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
}
UPDATE
Calling invalidateOptionsMenu() in my onPageSelected() did the trick!
Use invalidateOptionsMenu() but make sure you wrap this in a trycatch if you are supporting anythign below 3.0, as this method does not exist and will crash!
If you want to update your menu on pre 3.0 devices, override the onPrepareOptionsMenu() as well, which will be called everytime the menu is opened.