Get tab position outside its class - java

I have a calendar application. I am using ActionBarSherlock and Tabs. I have also implemented Options Menus in the Action Bar. I want one Menu Item in the Action Bar to behave differently when the tabs are selected.
How do I get the tab position in the onOptionsItemSelected(MenuItem item) method so based on that I can code the menu item accordingly?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab Tab1 = bar.newTab();
ActionBar.Tab Tab2 = bar.newTab();
Tab1.setText("Tab1");
Tab2.setText("Tab2");
Tab1.setTabListener(new MyTabListener());
Tab2.setTabListener(new MyTabListener());
bar.addTab(Tab1);
bar.addTab(Tab2);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
newActivity = new Intent(this, Main.class);
newActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(newActivity);
return true;
case R.id.menu_today_date:
//if condition here based on tabs selected
CalendarFragment frag = new CalendarFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(android.R.id.content, frag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
return true;
case R.id.menu_prefs:
newActivity = new Intent(this, Settings.class);
startActivityForResult(newActivity, requestCode);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class MyTabListener implements ActionBar.TabListener
{
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
CalendarFragment frag = new CalendarFragment();
ft.replace(android.R.id.content, frag);
}
else
{
ConverterFragment frag = new ConverterFragment();
ft.replace(android.R.id.content, frag);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}

I couldn't get the tab position, but this is how I ended up doing it:
private int tabSelected = 0;
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
tabSelected = 0;
CalendarFragment frag = new CalendarFragment();
ft.replace(android.R.id.content, frag);
}
else
{
tabSelected = 1;
ConverterFragment frag = new ConverterFragment();
ft.replace(android.R.id.content, frag);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId())
case R.id.menu_today_date:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (tabSelected == 0){
CalendarFragment frag = new CalendarFragment();
ft.replace(android.R.id.content, frag);
}
else {
ConverterFragment frag = new ConverterFragment();
ft.replace(android.R.id.content, frag);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
default:
return super.onOptionsItemSelected(item);
}
}

Related

Bottom navigation not working. How to resolve this issue?

I have made the code to do that it loads fragment on clicking the items in the bottom navigation but when I click on it they don't work. I tried many times to check whats the problem even though Android Studio couldn't find it bu the app isn't working. I don't know whats the issue.
My main activity -
public class MainActivity extends AppCompatActivity {
BottomNavigationView btm_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Chats());
fragmentTransaction.commit();
btm_view = findViewById(R.id.bottom_view);
btm_view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.camera) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Camera());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.chats) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Chats());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.status) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Status());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.calls) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Calls());
fragmentTransaction.commit();
} else if (item.getItemId() == R.id.settings) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.container, new Settings());
fragmentTransaction.commit();
}
return false;
}
});
}
}
one of my fragments -
public class Chats extends Fragment {
public Chats() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_chats, container, false);
}
}
Try this way
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.chats:
openFragment(Chat.newInstance());
return true;
case R.id.camera:
openFragment(Camera.newInstance());
return true;
case R.id.status:
openFragment(Status.newInstance("", ""));
return true;
}
return false;
}
};
At first use replace(R.id.container, fragment) instead of add.
Optimise Code
Utilise setOnNavigationItemSelectedListener. Try this way
Set a listener that will be notified when a bottom navigation item is
selected.
btm_view.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
openFragment(Camera.newInstance());
}
public void openFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
openFragment(Camera.newInstance());
return true;
case R.id.chats:
openFragment(Chats.newInstance());
return true;
case R.id.status:
openFragment(Status.newInstance());
return true;
case R.id.calls:
openFragment(Calls.newInstance());
return true;
case R.id.settings:
openFragment(Settings.newInstance());
return true;
}
return false;
}
};
}
Your Chats Fragment will be
public class Chats extends Fragment {
public Chats() {
// Required empty public constructor
}
public static Chats newInstance() {
Chats fragment = new Chats();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chats, container, false);
}
}

When I click the bottom navigation item more times the fragment loading again

This is my code I have created a bottom navigation view and I am connected the items to fragment separately. When I click the the navigation item more time the fragment load again again.
I don't know what is the problem here.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment SelectedFragment=null;
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.commit();
switch (item.getItemId()) {
case R.id.navigation_home:
setTitle("Playing11");
HomeFragment fragment = new HomeFragment();
ft.replace(R.id.fragment_container, fragment);
return true;
case R.id.navigation_dashboard:
HomeFragment1 fragment1 = new HomeFragment1();
ft.replace(R.id.fragment_container, fragment1);
return true;
case R.id.navigation_notifications:
setTitle("Safe11");
HomeFragment2 fragment2 = new HomeFragment2();
ft.replace(R.id.fragment_container, fragment2);
return true;
case R.id.navigation_notification:
setTitle("More");
HomeFragment3 fragment3 = new HomeFragment3();
ft.replace(R.id.fragment_container, fragment3);
return true;
}
return false;
}
};
}
Try to change your code like this:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.menu_home:
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction.replace(R.id.frameContentPlace, homeFragment, "HomeFragment").addToBackStack("HomeFragment");
break;
case R.id.menu_profile:
HomeFragment1 fragment1 = new HomeFragment1();
fragmentTransaction.replace(R.id.frameContentPlace, fragment1).addToBackStack("HomeFragment1");
break;
case R.id.menu_bookings:
HomeFragment2 fragment2 = new HomeFragment2();
fragmentTransaction.replace(R.id.frameContentPlace, fragment2).addToBackStack("HomeFragment2");
break;
}
fragmentTransaction.commit();
return true;
}
When you adding fragment use tag. So write
ft.replace(R.id.fragment_container, fragment, "MyFragment);
instead of
ft.replace(R.id.fragment_container, fragment);
And check if this fragment is visible for not loading this fragment again
switch (item.getItemId())
{
case R.id.navigation_home:
HomeFragment fragment = (HomeFragment)getFragmentManager().findFragmentByTag("MyFragment");
if (fragment != null && !fragment.isVisible())
{
setTitle("Playing11");
HomeFragment fragment = new HomeFragment();
ft.replace(R.id.fragment_container, fragment);
return true;
}
}

How to use onBackPressed in BottonNavigationView?

How can I use onBackPressed in BottonNavigationView to select an item? For example, if I press item 2 I go to fragment number 2, but when I push back, I go back to fragment number 1 and item 2 is still selected, item 1 is not selected which is the one corresponding to fragment 1 ...
This is my code
private BottomNavigationViewEx.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.mapa:
transaction.replace(R.id.content, new MapFragment());
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
case R.id.taxi:
transaction.replace(R.id.content, new TaxiFragment());
transaction.addToBackStack(null);
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
case R.id.help:
transaction.replace(R.id.content, new HelpFragment());
transaction.addToBackStack(null);
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
case R.id.go:
transaction.replace(R.id.content, new GoFragment());
transaction.addToBackStack(null);
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
}
return false;
}
};
}
UPDATE
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, new MapFragment()).commit();
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomViewBar);
bottomNavigationViewEx.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
bottomNavigationViewEx.setSelectedItemId(R.id.mapa);
MenuItem item = bottomNavigationViewEx.getMenu().getItem(0);
if (!item.isChecked()) item.setChecked(true);
}
private BottomNavigationViewEx.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.mapa:
transaction.replace(R.id.content, new MapFragment());
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
case R.id.taxi:
transaction.replace(R.id.content, new TaxiFragment());
transaction.addToBackStack(null);
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
case R.id.help:
transaction.replace(R.id.content, new HelpFragment());
transaction.addToBackStack(null);
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
case R.id.go:
transaction.replace(R.id.content, new GoFragment());
transaction.addToBackStack(null);
getSupportFragmentManager().popBackStack();
transaction.commit();
return true;
}
return false;
}
};
#Override
public void onBackPressed () {
if (mCurrentItem > 0) {
mCurrentItem--;
showFragment (mCurrentItem);
} else {
super.onBackPressed();
}
}
private void showFragment(int currentItem) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (currentItem) {
case 0:
transaction.replace(R.id.content, new MapFragment());
getSupportFragmentManager().popBackStack();
transaction.commit();
break;
case 1:
transaction.replace(R.id.content, new TaxiFragment());
getSupportFragmentManager().popBackStack();
transaction.commit();
break;
case 2:
transaction.replace(R.id.content, new HelpFragment());
getSupportFragmentManager().popBackStack();
transaction.commit();
break;
case 3:
transaction.replace(R.id.content, new GoFragment());
getSupportFragmentManager().popBackStack();
transaction.commit();
break;
}
}
}
I have this now, but I don't know if is correct
Keep a variable to denote which Fragment is your current. Inside onBackPressed, check what is the current Fragment, and decide where do you want to navigate to.
#Override
public void onBackPressed() {
if (mCurrentItem > 0) {
mCurrentItem--;
showFragment(mCurrentItem);
} else {
super.onBackPressed();
}
}
Your showFragment(mCurrentItem) can show different page based on the value, or however you'd like it to.
private void showFragment(int currentItem) {
switch (currentItem) {
case 0:
transaction.replace(R.id.content, new MapFragment());
getSupportFragmentManager().popBackStack();
transaction.commit();
break;
case 1:
...
}
}
Then inside your showFragment(currentItem) method, add this code to select the item on BottomNavigationView:
MenuItem item = mBottomNavigationView.getMenu().getItem(mCurrentItem);
if (!item.isChecked()) item.setChecked(true);
Solve my problem by adding this line inside the class of my corresponding fragment in the onCreateView method, so when pressing back the item is selected.
BottomNavigationViewEx navigation =
getActivity().findViewById(R.id.YourNavigationId);
Menu drawer_menu = navigation.getMenu();
MenuItem menuItem;
menuItem = drawer_menu.findItem(R.id.YourItemId);
if(!menuItem.isChecked())
{
menuItem.setChecked(true);
}

how to change Action bar icon to back arrow when open a fragment

I am trying to create an app. I want to change navigation drawer icon to back Arrow in Action Bar and when i open a fragment and go back to main activity when i click on back arrow in fragment Using the following code-
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
DrawerLayout mDrawerLayout;
ListView mDrawerList;
#SuppressWarnings("deprecation")
ActionBarDrawerToggle mDrawerToggle;
String mTitle="";
private final String TAG = this.getClass().getSimpleName();
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,NearbyPlace,FindMarker;
EditText editplace = null;
Button findbtn = null;
boolean firstRun = true;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for connectivity service
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Network is available ", Toast.LENGTH_SHORT).show();
AdView adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice("abc")
.build();
adView.loadAd(adRequest);
mFragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
else{
Toast.makeText(this, "Network is not available ", Toast.LENGTH_SHORT).show();
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
newFragment = new NetworkCheck();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
editplace = (EditText) findViewById(R.id.editplace);
findbtn = (Button) findViewById(R.id.findbtn);
setListnerOnWidget();
mTitle = (String) getTitle();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle( this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Select a menu");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
transaction.addToBackStack(null);
getActionBar().setTitle("IQWINER");
try
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
}
private void setListnerOnWidget() {
// TODO Auto-generated method stub
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = editplace.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
}
};
findbtn.setOnClickListener(listener);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
//for back button
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.START)){
mDrawerLayout.closeDrawer(Gravity.START);
}
else if(getFragmentManager().getBackStackEntryCount() > 1){
super.onBackPressed();
}
else{
if (exit){
finish(); // finish activity
}
else{
Toast.makeText(this, "Tap Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
}
I want to change navigation drawer icon to back arrow icon when i open a fragment and when i click on back arrow then go back to main activity from a fragment.
Thanks
Remove the below code :
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
transaction.addToBackStack(null);
getActionBar().setTitle("IQWINER");
try
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
and change it with below code:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.drawer_home:
txt_title.setText("Home");
Intent intent=new Intent(HomeActivity.this, HomeActivity.class);
startActivity(intent);
finish();
return true;
case R.id.drawer_artist:
txt_title.setText("Artists");
android.support.v4.app.FragmentManager fragmentManager=getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new ArtistsFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
case R.id.drawer_myplaylist:
txt_title.setText("My Playlists");
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new PlayListFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
Edit
xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:elevation="4dp"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/home">
//Your layout
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#drawable/bg_all"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:theme="#style/list_item_appearance"
app:menu="#menu/drawer_menu" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager()
.getBackStackEntryCount() > 0) {
getSupportActionBar()
.setDisplayHomeAsUpEnabled(true); // show
// back button
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
// show hamburger
getSupportActionBar()
.setDisplayHomeAsUpEnabled(false);
mDrawerToggle.syncState();
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout
.openDrawer(GravityCompat.START);
}
});
}
}
});
Use the following after mDrawerLayout.setDrawerListener(mDrawerToggle);

How To Make Tabs in Navigation Drawer

I create Navigation Drawer using fragments and Action Bar Tabs using Fragment. But when I compile it, I am having issue. My app unfortunately stop working. My code wasn't error, and I am so confused whats wrong?
MainActivity.java
public class MainActivity extends FragmentActivity {
// Within which the entire activity is enclosed
private DrawerLayout mDrawerLayout;
// ListView represents Navigation Drawer
private ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
// Title of the action bar
private String mTitle = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = "Sistem Pakar Ayam";
getActionBar().setTitle(mTitle);
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Sistem Pakar Ayam");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
// Currently selected river
mTitle = menuItems[position];
if (mTitle.equals("Beranda")){
FragmentHome fragmenthome = new FragmentHome();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmenthome);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Diagnosis")){
FragmentDiagnosis fragmentdiagnosis = new FragmentDiagnosis();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmentdiagnosis);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Data Penyakit")){
FragmentPenyakit fragmentpenyakit = new FragmentPenyakit();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmentpenyakit);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Bantuan")){
FragmentBantuan fragmentbantuan = new FragmentBantuan();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmentbantuan);
// Committing the transaction
ft.commit();
}
else if (mTitle.equals("Tentang")){
FragmentTentang fragmenttentang = new FragmentTentang();
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragmenttentang);
// Committing the transaction
ft.commit();
}
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
//Menampilkan Fragment Home yang Tampil Pertama Kali
FragmentHome fragmenthome = new FragmentHome();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragmenthome);
ft.commit();
getActionBar().setTitle("Beranda");
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.menu_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Apa kalian ingin Keluar?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton("Tidak", null)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
FragmentTentang.java
public class FragmentTentang extends Fragment {
ViewPager mViewPager;
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_fragment_tentang, container, false);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
final ActionBar actionBar = getActivity().getActionBar();
// Specify that tabs should be displayed in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i = 0; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Aplikasi" + (i + 1))
.setTabListener(tabListener));
}
for (int i = 1; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Pengembang" + (i + 1))
.setTabListener(tabListener));
}
for (int i = 2; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Coba" + (i + 1))
.setTabListener(tabListener));
}
}
}
I want my app like this image.
Tentang

Categories