Android click listener - android

java i am having trouble with the switch statement part of the code. it doesn't seem to take me to the page which is been clicked on. Only the dashboard shows and each layout has already been created help please
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class home extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
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.dashboard:
Toast.makeText(getApplicationContext(), "Inbox Selected", Toast.LENGTH_SHORT).show();
Dashboard fragment = new Dashboard();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(), "Profile Selected", Toast.LENGTH_SHORT).show();
new Profile();
return true;
case R.id.logs:
Toast.makeText(getApplicationContext(), "Logs Selected", Toast.LENGTH_SHORT).show();
new Logs();
return true;
case R.id.statements:
Toast.makeText(getApplicationContext(), "Statements Selected", Toast.LENGTH_SHORT).show();
new Statements();
return true;
case R.id.timeline:
Toast.makeText(getApplicationContext(), "TImeline Selected", Toast.LENGTH_SHORT).show();
new Timeline();
return true;
case R.id.settings:
Toast.makeText(getApplicationContext(), "Settings Selected", Toast.LENGTH_SHORT).show();
new Settings();
return true;
case R.id.logout:
Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#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 onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"home Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://www.arkounting.com.ng.finark/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"home Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://www.arkounting.com.ng.finark/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}

I think this is how your switch statement should look like:
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
Fragment fragment = null;
case R.id.dashboard:
Toast.makeText(getApplicationContext(), "Inbox Selected", Toast.LENGTH_SHORT).show();
fragment = new Dashboard();
break;
case R.id.profile:
Toast.makeText(getApplicationContext(), "Profile Selected", Toast.LENGTH_SHORT).show();
fragment = new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(), "Logs Selected", Toast.LENGTH_SHORT).show();
fragment = new Logs();
return true;
case R.id.statements:
Toast.makeText(getApplicationContext(), "Statements Selected", Toast.LENGTH_SHORT).show();
fragment = new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(), "TImeline Selected", Toast.LENGTH_SHORT).show();
fragment = new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(), "Settings Selected", Toast.LENGTH_SHORT).show();
fragment = new Settings();
return true;
case R.id.logout:
Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
break;
if (fragment != null) {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commit();
return true;
} else {
return true;
}
}

Related

WebView Error on Navigation View with Fragment

I am making a simple application but getting error, here is my
MainActivity.java
package com.example.intawebapp.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.intawebapp.R;
import com.example.intawebapp.fragment.HomeFragment;
import com.example.intawebapp.fragment.NotificationsFragment;
import com.example.intawebapp.fragment.SettingsFragment;
import com.example.intawebapp.other.CircleTransform;
import com.example.intawebapp.fragment.PortalFragment;
import com.example.intawebapp.fragment.ESSFragment;
public class MainActivity extends AppCompatActivity {
WebView myWebView;
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtWebsite;
private Toolbar toolbar;
private FloatingActionButton fab;
// urls to load navigation header background image
// and profile image
private static final String urlNavHeaderBg = "http://example.com/nav-menu-header-bg.jpg";
private static final String urlProfileImg = "http://example.com/prof";
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
private static final String TAG_HOME = "home";
private static final String TAG_PORTAL = "portal";
private static final String TAG_ESS = "ess";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.website);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
myWebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// name, website
txtName.setText("My Name");
txtWebsite.setText("www.example.com");
// loading header background image
Glide.with(this).load(urlNavHeaderBg)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavHeaderBg);
// Loading profile image
Glide.with(this).load(urlProfileImg)
.crossFade()
.thumbnail(0.5f)
.bitmapTransform(new CircleTransform(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfile);
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
// show or hide the fab button
toggleFab();
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// portal
PortalFragment portalFragment = new PortalFragment();
return portalFragment;
case 2:
// ESS fragment
ESSFragment essFragment = new ESSFragment();
return essFragment;
case 3:
// notifications fragment
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 4:
// settings fragment
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
myWebView.loadUrl(url);
return true;
}
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_portal:
navItemIndex = 1;
CURRENT_TAG = TAG_PORTAL;
break;
case R.id.nav_ess:
navItemIndex = 2;
CURRENT_TAG = TAG_ESS;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_exit:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, ExitActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
//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);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// show menu only when home fragment is selected
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
// when fragment is notifications, load the menu created for notifications
if (navItemIndex == 3) {
getMenuInflater().inflate(R.menu.notifications, 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_logout) {
Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
return true;
}
// user is in notifications fragment
// and selected 'Mark all as Read'
if (id == R.id.action_mark_all_read) {
Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show();
}
// user is in notifications fragment
// and selected 'Clear All'
if (id == R.id.action_clear_notifications) {
Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
and this is my AboutUsActivity
package com.example.intawebapp.activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.intawebapp.R;
public class AboutUsActivity extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public AboutUsActivity() {
// Required empty public constructor
}
public static AboutUsActivity newInstance(String param1, String param2) {
AboutUsActivity fragment = new AboutUsActivity();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_about_us, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
I am getting this error when I choose About from the menu
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.intawebapp, PID: 8170
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.intawebapp/com.example.intawebapp.activity.AboutUsActivity}: java.lang.ClassCastException: com.example.intawebapp.activity.AboutUsActivity cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.ClassCastException: com.example.intawebapp.activity.AboutUsActivity cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Application terminated.
I need help to solve this problem. Thanks

how to go back to previous fragment when hardware back button is pressed

i am begineer in android development , i would like to configure hardware backbutton to go back to previous fragment and the fragment titles should also change according to the current fragment ,
here is my Main activity source :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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.action_settings) {
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 MicrosoftDskFragment();
title = "Microsoft Dsk";
break;
case 2:
fragment = new GoogleDskFragment();
title = "Google Dsk";
break;
case 3:
fragment = new AppleDskFragment();
title = "Apple Dsk";
break;
case 4:
fragment = new OthersDskFragment();
title = "Others Dsk";
break;
case 5:
fragment = new AboutUSFragment();
title = "About US";
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.addToBackStack(null).commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
plz hel me in fixing this .
You are adding the transaction to the backstack, so all you should need in order to get back to the previous one should be:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackstack(null, 0);
You may also consider adding an id for each fragment and passing it when calling
fragmentTransaction.addToBackStack(null).commit();
instead of the null. This way, you will be able to do this:
fragmentTransaction.addToBackStack(myFragmentId).commit();
//Later on...
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackstack(myFragmentId, 0);
To go back to a specific fragment, not just the last one :-)
every time when you add a fragment just add addToBackStack() method before commit and then in your activity on back pressed try this
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 1) {
goToExitApplication(
getResources().getString(R.string.close_app), true);
} else {
String title = getSupportFragmentManager().getBackStackEntryAt(count - 2).getName();
getSupportFragmentManager().popBackStack();
getSupportActionBar().setTitle(title);
}
}
I have used this in my code:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ){
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
To push the Fragment I used:
MyFragment_Items myf = new MyFragment_Items();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_layout, myf);
transaction.addToBackStack(null);
transaction.commit();
I pushed the fragment here and popped it back onBackPressed.
It will Surely work for you If there is any Fragment on the back stack of current fragment , popBackStackImmediate() works..
#Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() > 0){
getFragmentManager().popBackStackImmediate();
}
else{
super.onBackPressed();
}
}

Navigation drawer Fragment Issue

Hi i have this problem with my navigation drawer. The drawer opens fine but i am having problems with the onClickListener. if an item on the drawer is clicked on it doesnt show the related layout instaed a black page shows. Please help
home.java
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
public class home extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
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.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
Dashboard fragment = new Dashboard();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
return true; }
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#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);
}
}
You're not switching fragments correctly in your case statements. You're only instantiating a new Fragment class and not doing anything with it. You need to do something like this:
Fragment fragment;
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
fragment = new Dashboard();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
fragment = new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
fragment = new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
fragment = new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
fragment = new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
fragment = new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
This way you're instantiating a fragment with a proper Fragment class each time, and at the end, replacing the frame with that particular fragment.
Digresion: It is recommended that you use newInstance to get the fragments and not the constructor. This is known as the Singleton design pattern.

Fragment + swipe + drawermenu

I realized my "swipe " project between two fragments that works. I also have my project with my walking drawer menu. I try to link the two but following this assembly code , which contains my MainActivity my menu must become / be as a fragment. So many functions change language / writing .
there a easy idea of my plan
Here is my code MainActivity :
package thyroid.com.thyroidmenu;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.view.Menu;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends Fragment {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public GoogleApiClient client;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.connection:
setContentView(R.layout.activity_mainlogin);
Intent myIntent = new Intent(MainActivity.this, login.class);
startActivity(myIntent);
drawerLayout.closeDrawers();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.trash:
Toast.makeText(getApplicationContext(), "Trash", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.logout:
finish();
}
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView) header.findViewById(R.id.tv_email);
tv_email.setText("thyroid.mobileapp#gmail.com");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://thyroid.com.thyroidmenu/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://thyroid.com.thyroidmenu/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View MainActivity = inflater.inflate(R.layout.activity_main, container, false);
((TextView)MainActivity.findViewById(R.id.textView)).setText("iOS");
return MainActivity;
}}
And here are the errors that are just bad writing :
MY ERRORS
How do I change my setContentView / getApplicationContext / findViewById ... etc to fit in a fragment ?
Do I have to make my process with fragments to realize this little montage (see picture 1) ? The fragments will seem practical and me in any case very useful later ...
Thanks ;)
Try by getActivity().function_name() i.e. functions you have mentioned in your question , in your fragment. But that is not the right way. You can follow up the instructions given here for a drawer layout.
http://slidenerd.com/2015/07/22/android-design-support-library/
There what I obtained after the modifications :
package thyroid.com.thyroidmenu;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.view.Menu;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public GoogleApiClient client;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.connection:
setContentView(R.layout.activity_mainlogin);
Intent myIntent = new Intent(MainActivity.this, login.class);
startActivity(myIntent);
drawerLayout.closeDrawers();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.trash:
Toast.makeText(getApplicationContext(), "Trash", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.logout:
}
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView) header.findViewById(R.id.tv_email);
tv_email.setText("thyroid.mobileapp#gmail.com");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://thyroid.com.thyroidmenu/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://thyroid.com.thyroidmenu/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
The code which realise the swipe :
package thyroid.com.thyroidmenu;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragment for Android Tab
return new Windows();
case 1:
//Fragment for Ios Tab
return new MainActivity();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3; //No of Tabs
}
}
And the errors are :
there
As I dont use "fragment" for my toolbarmenu/drawermenu it can't works.
I should maybe try to separate the menu is an other class and then call it in the fragment. but how ?... ;)
Your MainActivty is extending Fragment replace Fragment by AppCompactActivity. And delete your onCreateView method placed at bottom of your class there is no need of that method. If you need below line of code:
((TextView)MainActivity.findViewById(R.id.textView)).setText("iOS");
mentioned in your onCreateView method then you can move this line of code to onCreate method. But you have to it write as follows in onCreate method:
((TextView)findViewById(R.id.textView)).setText("iOS");
Nothing else line of code is required from onCreateView method so delete that method.

App crashes in Fragment Listview

I have a navigation drawer and a fragment listview that uses ArrayAdapter. The app crashes at the current build. The part that I'm not sure is MyListAdapter, where super(getActivity(), R.Layout...). Can someone please help me with this? I've spent much time in trying to fix this.
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class FavouritesFragment extends ListFragment {
private List<Food> foodList = new ArrayList<Food>();
public FavouritesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
populateFoodList();
populateListView();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_favourites, container, false);
}
private void populateFoodList() {
foodList.add(new Food("Large Fries", 4.50, R.drawable.fries));
foodList.add(new Food("Small Fries", 4.50, R.drawable.fries));
foodList.add(new Food("Hamburger", 4.50, R.drawable.hamb));
foodList.add(new Food("Cheese Burger", 4.50, R.drawable.hamb));
foodList.add(new Food("Cheese Bacon Burger", 4.50, R.drawable.hamb));
foodList.add(new Food("Crispy Chicken Burger", 4.50, R.drawable.hamb));
foodList.add(new Food("Large Poutine", 4.50, R.drawable.poutine));
foodList.add(new Food("Small Poutine", 4.50, R.drawable.poutine));
}
private void populateListView() {
ArrayAdapter<Food> adapter = new MyListAdapter();
ListView list = (ListView) getActivity().findViewById(R.id.favouritesListView);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Food> {
public MyListAdapter() {
super(getActivity(), R.layout.item_view, foodList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getActivity().getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Food selectedFood = foodList.get(position);
ImageView imageView = (ImageView) getActivity().findViewById(R.id.item_imgFood);
imageView.setImageResource(selectedFood.getIconID());
return itemView;
// return super.getView(position, convertView, parent);
}
}
}
This is my MainActivity
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting fragment
MainMenu fragment = new MainMenu();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
MainMenu fragment = new MainMenu();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
FavouritesFragment fragment = new FavouritesFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.hrak109.happytimescafe/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.hrak109.happytimescafe/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}

Categories

Resources