How can I add a large profile picture to my navigation drawer? - java

So, a couple of days ago I started working on my very first app. It's an app with a navigation drawer where users can set some website shortcuts to be displayed in the navigation drawer. If a user clicks on a website it opens in a webview. Really nothing fancy, but it's a concept I came up with to train my Android knowledge.
I finished the basics of this app this morning with some help, but now I want to add a large profile picture to the navigation drawer. (You can see it here on the left: http://www.droid-life.com/wp-content/uploads/2013/12/new-foursquare.jpg)
I understand that I should add an <ImageView> to the navigation drawer, but every time I try that the log keeps saying I have junk in my XML...
Below you can find the code I already wrote. I hope you guys can help me...
Main.java
package test.webviewapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Main
extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks
{
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
// we need a class level references to some objects to be able to modify the
// target address outside of onCreate()
private WebView myWebView;
private ActionBar actionBar;
private ProgressDialog progressDialog;
// keep the pair of String arrays of site names and addresses
private String[] siteNames;
private String[] siteAddresses;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// grab the needed website arrays
siteNames = getResources().getStringArray(R.array.site_names);
siteAddresses = getResources().getStringArray(R.array.site_addresses);
// set up WebView. initial page load comes from NavDrawerFragment attach
myWebView = (WebView) findViewById(R.id.main_webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// when a page has finished loading dismiss any progress dialog
if (progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
String javascript="javascript:"+
"document.getElementById('menu-toggle').css('display','none');";
myWebView.evaluateJavascript(javascript, null);
}
});
// Set up the drawer.
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int siteIndex)
{
// user selected page load
Log.d(TAG, "(onNavSelect) received index: " + siteIndex);
loadWebPage(siteIndex);
}
public void onSectionAttached(int siteIndex)
{
// initial page load. not user selected.
loadWebPage(siteIndex);
}
public void restoreActionBar()
{
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
private void loadWebPage(int siteIndex)
{
// lets show a progress indicator instead of a blank screen
if (progressDialog == null)
{
initProgressDialog();
}
progressDialog.show();
// load the page
Log.d(TAG, "(loadWebPage) Loading page: " + siteNames[siteIndex] + "("
+ siteAddresses[siteIndex] + ")");
mTitle = siteNames[siteIndex];
if (actionBar == null)
{
restoreActionBar();
}
else
{
actionBar.setTitle(mTitle);
}
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl(siteAddresses[siteIndex]);
myWebView.loadUrl(siteAddresses[siteIndex]);
// progressDialog gets dismissed above in WebViewclient declaration
}
private void initProgressDialog()
{
progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setMessage(getString(R.string.page_load_progress_message));
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
if (!mNavigationDrawerFragment.isDrawerOpen())
{
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.global, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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.
if (actionBar == null)
{
restoreActionBar();
}
else
{
}
int id = item.getItemId();
if (id == R.id.action_settings)
{
myWebView.loadUrl(settingsview);
myWebView.loadUrl(settingsview);
actionBar.setTitle("Settings");
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment
extends Fragment
{
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SELECTED_SITE_INDEX = "selected_site_index";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int siteIndex)
{
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SELECTED_SITE_INDEX, siteIndex);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment()
{}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
// Here is where you can define the default page you want loaded
// or if you want to save/restore the last page viewed etc.
((Main) activity)
.onSectionAttached(getArguments().getInt(ARG_SELECTED_SITE_INDEX));
}
}
}
NavigationDrawerFragment.java
package test.webviewapp;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Fragment used for managing interactions for and presentation of a
* navigation drawer. See the <a href=
* "https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"
* > design guidelines</a> for a complete explanation of the behaviors
* implemented here.
*/
public class NavigationDrawerFragment
extends Fragment
implements AdapterView.OnItemClickListener
{
private String[] siteNames;
private static final String TAG = "NavDrawerFrag";
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until
* the user manually expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment()
{}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null)
{
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
// too early to select an item
//selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
selectItem(mCurrentSelectedPosition);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
siteNames = getActivity().getResources().getStringArray(R.array.site_names);
Log.d(TAG, "number of sites loaded: " + siteNames.length);
mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer,
container,
false);
// neater to implement OnItemClickListener and define onClick() later
mDrawerListView.setOnItemClickListener(this);
String[] siteNames = getActivity().getResources().getStringArray(R.array.site_names);
mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1, android.R.id.text1, siteNames));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen()
{
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation
* drawer interactions.
*
* #param fragmentId
* The android:id of this fragment in its activity's layout.
* #param drawerLayout
* The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout)
{
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,
R.drawable.ic_drawer, R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
{
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
if (!isAdded())
{
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
if (!isAdded())
{
return;
}
if (!mUserLearnedDrawer)
{
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState)
{
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable()
{
#Override
public void run()
{
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int siteIndex)
{
mCurrentSelectedPosition = siteIndex;
if (mDrawerListView != null)
{
Log.d(TAG, "(select) list ok");
mDrawerListView.setItemChecked(siteIndex, true);
}
if (mDrawerLayout != null)
{
Log.d(TAG, "(select) drawer ok");
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null)
{
Log.d(TAG, "(select) callback...");
mCallbacks.onNavigationDrawerItemSelected(siteIndex);
}
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
mCallbacks = (NavigationDrawerCallbacks) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach()
{
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen())
{
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (mDrawerToggle.onOptionsItemSelected(item))
{
//fragment = new PlanetFragment();
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to
* show the global app 'context', rather than just what's in the current
* screen.
*/
private void showGlobalContextActionBar()
{
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar()
{
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.i(TAG, "(Click) index: " + position);
Log.i(TAG, "(Click) site: " + siteNames[position]);
selectItem(position);
}
/**
* Callbacks interface that all activities using this fragment must
* implement.
*/
public static interface NavigationDrawerCallbacks
{
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<fragment
android:id="#+id/navigation_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="test.webdrawerapp.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main$PlaceholderFragment">
</RelativeLayout>
fragment_navigation_drawer.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#000"
tools:context=".NavigationDrawerFragment" />

From working with you on this app before I was able to make some tweaks for you.
What had to be done was to add new Views to fragment_navigation_drawer.xml and change the NavigationDrawerFragment to match up and include the changes.
Layout
<?xml version="1.0" encoding="utf-8"?>
<!-- the root view is now a LinearLayout, all other Views are children of this -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#cccc"
android:orientation="vertical">
<!-- a separate section to go above the list -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:orientation="horizontal">
<!-- your image, you can set it later (see NavDrawerFrag) -->
<ImageView
android:id="#+id/nav_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:src="#android:drawable/ic_menu_myplaces"/>
<!-- a bit of test or a title to go with it -->
<TextView
android:id="#+id/nav_text"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Default text"/>
</LinearLayout>
<!-- some divider thing -->
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:padding="20dp"
android:background="#000000"/>
<!-- your ListView is now a child View -->
<ListView
android:id="#+id/nav_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"/>
</LinearLayout>
Fragment
// new class level members
private ImageView mDrawerImage;
private TextView mDrawerText;
// change the View inflation and extract the new child views
// also modifying the ListView to now be a child instead of the root View
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
// need site names for list
siteNames = getActivity().getResources().getStringArray(R.array.site_names);
Log.d(TAG, "number of sites loaded: " + siteNames.length);
// inflate the parent view (the entire layout)
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
// now grab the separate child views from inside it
mDrawerListView = (ListView) view.findViewById(R.id.nav_listView);
mDrawerImage = (ImageView) view.findViewById(R.id.nav_image);
mDrawerText = (TextView) view.findViewById(R.id.nav_text);
// configure the Views
mDrawerText.setText("Give it a name/title");
//mDrawerImage.setImageURI(...); // set your ImageView however you want, I just gave it one in XML
mDrawerListView.setOnItemClickListener(this);
mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1, android.R.id.text1, siteNames));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
// and return the inflated view up the stack
return view;
}

Related

onOptionsItemSelected() method not get called on Fragment

I have an AppCompatActivity and some Fragments. The back button on the action bar not works on in AboutFragment.
The Activity has no menu inflated, while the Fragment only has a back button in the action bar.
Fragment menu is visible, but the back button doesn't react at all when tapped.
The AboutFragment is getting showed on clicking the info icon from the actionbar.
While clicking on the i icon, the bellow method works inside MainActivity.
#Override
public void onInfoSelected() {
abf = (AboutFragment) getSupportFragmentManager().findFragmentByTag(ABOUT_FRAGMENT_TAG);
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// ft.hide(pf);
//ft.hide(cf);
ft.hide(tlf);
ft.show(abf);
ft.addToBackStack(null);
ft.commit();
}
then the back button inside AboutFragment doesn't call onOptionsItemSelected() method inside the Fragment.
When debugging, I can see that both onCreateOptionsMenu() for Fragment and Activity get called, but when tapping buttons no onOptionsItemSelected() gets called, neither from Activity nor from Fragment.
its been two days I am searching and googling, nothing worked for me.
any help would be appriciated.
Activity Java code
package me.declangao.jiasazsales.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import me.declangao.jiasazsales.R;
import me.declangao.jiasazsales.model.Post;
public class MainActivity extends AppCompatActivity implements
RecyclerViewFragment.PostListListener, PostFragment.PostListener,
TabLayoutFragment.TabLayoutListener, SearchResultFragment.SearchResultListener,
CommentFragment.CommentListener,AboutFragment.AboutListener {
private static final String TAG = MainActivity.class.getSimpleName();
public static final String TAB_LAYOUT_FRAGMENT_TAG = "TabLayoutFragment";
public static final String POST_FRAGMENT_TAG = "PostFragment";
public static final String COMMENT_FRAGMENT_TAG = "CommentFragment";
public static final String ABOUT_FRAGMENT_TAG = "AboutFragment";
private FragmentManager fm = null;
private TabLayoutFragment tlf;
private PostFragment pf;
private CommentFragment cf;
private SearchResultFragment srf;
private AboutFragment abf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
// Setup fragments
tlf = new TabLayoutFragment();
pf = new PostFragment();
cf = new CommentFragment();
srf = new SearchResultFragment();
abf=new AboutFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(android.R.id.content, abf, ABOUT_FRAGMENT_TAG);
ft.add(android.R.id.content, pf, POST_FRAGMENT_TAG);
ft.add(android.R.id.content, cf, COMMENT_FRAGMENT_TAG);
ft.add(android.R.id.content, tlf, TAB_LAYOUT_FRAGMENT_TAG);
ft.hide(pf);
ft.hide(cf);
ft.hide(abf);
ft.show(tlf);
ft.commit();
}
/**
* Invoked when a post in the list is selected
*
* #param post Selected Post object
*/
#Override
public void onPostSelected(Post post, boolean isSearch) {
// Find the fragment in order to set it up later
pf = (PostFragment) getSupportFragmentManager().findFragmentByTag(POST_FRAGMENT_TAG);
// Set necessary arguments
Bundle args = new Bundle();
args.putInt("id", post.getId());
args.putString("title", post.getTitle());
args.putString("date", post.getDate());
args.putString("author", post.getAuthor());
args.putString("content", post.getContent());
args.putString("url", post.getUrl());
//args.putString("thumbnailUrl", post.getThumbnailUrl());
args.putString("featuredImage", post.getFeaturedImageUrl());
// Configure PostFragment to display the right post
pf.setUIArguments(args);
// Show the fragment
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
if (!isSearch) { // Hide TabLayoutFragment if this is not search result
ft.hide(tlf);
} else { // Otherwise, hide the search result, ie. SearchResultFragment.
ft.hide(srf);
}
ft.show(pf);
ft.addToBackStack(null);
ft.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//do something here like
Log.e("menu Test","rom Main activity");
int backStackEntryCount
=getSupportFragmentManager().getBackStackEntryCount();
if (backStackEntryCount > 0) {
getSupportFragmentManager().popBackStack();
}
return true;
}
return false;
}
/**
* Invoked when a search query is submitted
*
* #param query Selected Post object
*/
#Override
public void onSearchSubmitted(String query) {
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// Send query to fragment using factory method
srf = SearchResultFragment.newInstance(query);
ft.add(android.R.id.content, srf);
ft.hide(tlf);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onInfoSelected() {
abf = (AboutFragment) getSupportFragmentManager().findFragmentByTag(ABOUT_FRAGMENT_TAG);
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// ft.hide(pf);
//ft.hide(cf);
ft.hide(tlf);
ft.show(abf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Invoked when comment menu is selected
*
* #param id ID of the article, assigned by WordPress
*/
#Override
public void onCommentSelected(int id) {
cf = (CommentFragment) getSupportFragmentManager().findFragmentByTag(COMMENT_FRAGMENT_TAG);
Bundle args = new Bundle();
args.putInt("id", id);
// Setup CommentFragment to display the right comments page
cf.setUIArguments(args);
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
ft.hide(pf);
//ft.hide(abf);
ft.show(cf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Intercept back button event, reset ActionBar if necessary
*/
#Override
public void onBackPressed() {
resetActionBarIfApplicable();
super.onBackPressed();
}
/**
* Simulate a back button press when home is selected
*/
#Override
public void onHomePressed() {
resetActionBarIfApplicable();
fm.popBackStack();
}
/**
* Reset TabLayoutFragment's ActionBar if necessary
*/
private void resetActionBarIfApplicable() {
Log.d(TAG, "SearchResultFragment is visible: " + srf.isHidden());
if (srf.isVisible()) {
tlf.resetActionBar();
}
}
// Commented out coz we will let fragments handle their own Options Menus
/*
#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);
//Log.e("Erroraaa","aaaaa");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("menu","activity: action home has clicked");
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return false;
}
return super.onOptionsItemSelected(item);
}
*/
}
AboutFragment
package me.declangao.jiasazsales.app;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import me.declangao.jiasazsales.R;
/**
* Fragment to display a Info about Jiasaz company.
* Activities that contain this fragment must implement the
* {#link AboutFragment.AboutListener} interface
* to handle interaction events.
*/
public class AboutFragment extends Fragment {
private AboutListener mListener;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.setHasOptionsMenu(true);
}
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Log.e("Menu:created","Menu");
//
//// super.onCreateOptionsMenu(menu, inflater);
//// menu.clear();
// inflater.inflate(R.menu.menu_post, menu);
// super.onCreateOptionsMenu(menu, inflater);
// }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("Menu:selected","Menu");
if (item.getItemId() == android.R.id.home) {
mListener.onHomePressed();
}
return false;
}
public AboutFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.about_layout, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((MainActivity) getActivity()).setSupportActionBar(toolbar);
((MainActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity) getActivity()).getSupportActionBar().setTitle( "www.Jiasaz.com");
Log.e("Menu: fragment created","onCreaate()");
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (AboutListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement AboutListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface AboutListener {
void onHomePressed();
//void onInfoSelected();
}
}
and this is my AboutFragment xml code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
android:layoutDirection="rtl"
android:textDirection="rtl"
tools:context="me.declangao.jiasazsales.app.AboutFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:layoutDirection="rtl"
android:textDirection="rtl"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:padding="15dp"
android:orientation="vertical">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:text="ئه‌م ئاپه‌ له‌لایه‌ن كۆمپانیای جیاساز دروست كراوه‌"
android:textAppearance="#style/TextAppearance.AppCompat.Light.SearchResult.Title" />
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="214dp"
android:src="#drawable/jiasazlogo" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:text="كۆمپانیای جیاساز بۆ خزمه‌تگوزاری و چاره‌سه‌ری ته‌كنه‌لۆجی، دروستكردنی وێبسایت و ئاپی مۆبایل و سیسته‌می دام و ده‌زگاكان و ماركێته‌كان"
android:textAppearance="#style/TextAppearance.AppCompat.Light.SearchResult.Title" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="all"
android:clickable="true"
android:text="#string/link"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
You can set an instance of OnMenuItemClickListener directly on the Toolbar. Remember that you should not use Activity.setSupportActionBar(Toolbar).
public class AboutFragment extends Fragment {
// ...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.about_layout, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_about_fragment);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.some_menu) {
// do sth...
return true; // event is handled.
}
return false;
}
});
// ...
}
// ...
}
.
UPDATE 21/11/2018:
To enable back button for a stand alone Toolbar, set its default icon in xml file using app:navigationIcon="?attr/homeAsUpIndicator":
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:layoutDirection="rtl"
android:textDirection="rtl"
app:navigationIcon="?attr/homeAsUpIndicator" />
Then set a listener for it
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// back button is pressed
mListener.onHomePressed();
}
});
You described everything properly, those are limitations of the platform. To workaround it you need to use onOptionsItemSelected()
in MainActivity, insert there code that you already use in another method:
abf = (AboutFragment) getSupportFragmentManager().findFragmentByTag(ABOUT_FRAGMENT_TAG);
then as you have the fragment you can invoke some method from the fragment and possibly get return value to know if the back is handled or not and if something more needs to be done...
You can use onPrepareOptionsMenu(Menu menu) in you fragment class for listening to you action bar menus...
#Override
public void onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
// to get an item of menu from action bar you can do it like...
// this below line will find an item of menu with id action_search...
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
// like this you can find other menu items
// another example is
MenuItem infoMenuItem = menu.findItem(R.id.action_info);
}
I'm using search view in my fragment class practically for searching...
First reason is that you have'nt properly implemented onCreateOptionsMenu() and onOptionsItemSelected() #Override methods in Activity so uncomment that Activity can also call their respective super methods.
Second reason is that your onCreateOptionsMenu() code is commented which needs not to be. Important thing is that super super.onCreateOptionsMenu(menu, inflater); must be called to draw the menu of the Fragment
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
And also change change onOptionsItemSelected() in Fragment to this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("Menu:selected","Menu");
if (item.getItemId() == android.R.id.home) {
mListener.onHomePressed();
return true;
}else{
return super.onOptionsItemSelected(item);
}
}
And now in Activity change your onCreateOptionsMenu() to this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
and onOptionsItemSelected() to this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}

RuntimeException on newly created NavDrawer

So, I'm a newbie with Android app development, and I'm getting the following error on a newly create Navigation Drawer activity (Incoming Stack trace):
04-01 16:50:52.113 8917-8917/pt.bluecover.wearable3d E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{pt.bluecover.wearable3d/pt.bluecover.wearable3d.DrawerActivity}: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:274)
at android.app.Activity.setContentView(Activity.java:1881)
at pt.bluecover.wearable3d.DrawerActivity.onCreate(DrawerActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
at android.app.ActivityThread.access$600(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:153) 
at android.app.ActivityThread.main(ActivityThread.java:5297) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at pt.bluecover.wearable3d.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:101)
at android.app.Fragment.performCreateView(Fragment.java:1695)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:861)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1137)
at android.app.Activity.onCreateView(Activity.java:4735)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:274) 
at android.app.Activity.setContentView(Activity.java:1881) 
at pt.bluecover.wearable3d.DrawerActivity.onCreate(DrawerActivity.java:37) 
at android.app.Activity.performCreate(Activity.java:5122) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
at android.app.ActivityThread.access$600(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:153) 
at android.app.ActivityThread.main(ActivityThread.java:5297) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method) 
I also have the following classes referenced in the trace:
package pt.bluecover.wearable3d;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class DrawerActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_drawer, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((DrawerActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
And this one:
package pt.bluecover.wearable3d;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.drawer_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
Both where auto-generated by adding a Navigation Drawer Activity to the project and haven't been modified yet...
EDIT: activity_drawer.xml code here:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pt.bluecover.wearable3d.DrawerActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment
android:id="#+id/navigation_drawer"
android:name="pt.bluecover.wearable3d.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/drawer_drawer" />
</android.support.v4.widget.DrawerLayout>
Not sure why you need a themed context for an Adapter, but this section is throwing a NullPointerException.
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
Try using getActivity() instead of getActionBar().getThemedContext() because getActionBar() will return null if you aren't using a theme in styles.xml that contains an ActionBar for the parent Activity.
In code...
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActivity(), ...
Make sure you are not using Theme.AppCompat.Light.NoActionBar. To be able to get the action bar you should have it in the theme.
android:Theme.Light
will do. In your styles.xml use this for the Theme that you are using for the activity in AndroidManifest.xml
<style name="AppTheme" parent="android:Theme.Light">

Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference NullPointer [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Having a few run-time issues with a navigation drawer i'm trying to test out...
The error I get is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.suzan.parentmeetme/com.example.suzan.parentmeetme.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at com.example.suzan.parentmeetme.NavigationDrawerFragment.setUp(NavigationDrawerFragment.java:138)
at com.example.suzan.parentmeetme.MainActivity.onCreate(MainActivity.java:35)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
12-30 21:45:47.250 27145-27145/? I/Process: Sending signal. PID: 27145 SIG: 9
I have a couple of java files:
MainActivity.java
package com.example.suzan.parentmeetme;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
// This navigation drawer frag will be responsible for the actions and behaviour of
// the navigation drawer
private NavigationDrawerFragment mNavigationDrawerFragment;
// Keeps track of the last screen we were on by storing the title name
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)getFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Initialise the navigation drawer
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new SettingsFragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}
public void onSectionAttached(int number)
{
switch (number)
{
case 1:
mTitle = getString(R.string.title_section1);
break;
}
}
public void restoreActionBar()
{
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
if (!mNavigationDrawerFragment.isDrawerOpen())
{
// only display actions relevant to this screen
getMenuInflater().inflate(R.menu.sample, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here.
// Action bar will handle clicks on home/up
// button, so long as parent activity is specified
// in AndroidManifest.xml
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment
{
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java
package com.example.suzan.parentmeetme;
/**
* Created by Suzan on 30/12/2015.
*/
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myParentView = inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView = (ListView) myParentView.findViewById(R.id.listview);
// the listview is the id you gave to you listview in xml
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
And I've got a few XML files:
activity_main.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.suzan.parentmeetme.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
fragment_navigation_layout.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#cccc"
android:id="#+id/listview"
tools:context=".NavigationDrawerFragment" />
Could anyone figure out what I might be doing wrong? Been staring at this for hours and seriously can't work it out.....
Thanks!
Make sure you have referenced
public class MainActivity extends ActionBarActivity {
...
}
and change
ActionBar bar = getActionBar();
to
ActionBar bar =getActivity().getSupportActionBar();
Reference
http://developer.android.com/guide/topics/ui/actionbar.html
First change your class extension
public class MainActivity extends AppCompatActivity{
And then get your support action bar adding the following code to the 'onCreateView' method
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

How to link two xml pages in Android app when a button is clicked?

I am making a simple app in which on home page, a button is placed. When the button is clicked, it must display a new page (xml in layout). How to do that ..
My app contains in src directory, There are two java files.
1. Activity2
2. Main_activity
and two xml files in layout:
1. fragment_main.xml
2. Activity.xml
I want that when i click "Technical button", it should display Activity.xml page from layout..
My codes:
Main_Activity.java
package com.example.vit;
import java.util.Locale;
import android.util.Log;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void onClick(View v)
{
Intent intent = new Intent (v.getContext(),Activity.class);
startActivityForResult (intent,0);
}
}
2.Activity2.java
package com.example.vit;
import android.app.Activity;
public class Activity2 extends Activity
public void onCreate(Bundle, savedInstanceState)
{
{
super.onCreate(savedInstanceState);
setContentView(R.layout.Activity);
}
}
3. fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.vit.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="31dp"
android:onClick="doSomething"
android:text="Technical" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Non Technical" />
</LinearLayout>
Activity.xml
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your request is being processed"
android:textAppearance="?android:attr/textAppearanceLarge" />
Intent intent = new Intent(this, ActivityTwo.class);
this.startActivity ( intent );
Note : #Don already provided a correct answer, but (sorry) lack of information. Accept his answer, i only help to add some informations (which is quite long if i put in comment)
In Android, a page/screen in your apps refer to the subclass of Activity. An Activity always have a xml layout.
So, if you want to change from one layout (or screen/page) to others, you should change the Activity, with the help of Intent class. This will automatically change the layout (as your question refer) because an Activity has a layout.
No offense, but i suggest you to search some videos/books/tutorials. I suggest Commonsware's book which is free (the old version, but still the best book in my opinion) :
http://commonsware.com/Android/4-2-free
all is going right but u have to include the following code
Intent intent = new Intent(this, ActivityTwo.class);
this.startActivity ( intent );

webView cannot be resolved & cannot make a static reference to the non-static method findViewById(int) from the type Activity

MainActivity.java code
package com.themeister.feed.it;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
View webView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
WebView wv = (WebView)rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.stackoverflow.com");
return rootView;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1"
android:orientation="vertical">
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.9"/>
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.1"
style="?android:attr/progressBarStyleHorizontal"/>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
</LinearLayout>
What I'm trying to do is for testing purpose load up http://www.stackoverflow.com in my app and navigate on the website. The following code returns two errors:
"Cannot make a static reference to the non-static method findViewById(int) from the type Activity MainActivity.java /Feed.it/src/com/themeister/feed/it line 168 Java Problem"
and
"webView cannot be resolved MainActivity.java /Feed.it/src/com/themeister/feed/it line 169 Java Problem"
Any help I can get is appreciated
You have this
WebView wv = (WebView)findViewById(R.id.webView);
in fragment. findViewById is a method of your activity class.
I suggest you have webview in your fragment xml and use the below
WebView wv = (WebView)rootView.findViewById(R.id.webView);
Edit
Replace
WebView wv = (WebView)rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.stackoverflow.com");
BY
WebView wv = (WebView)rootView.findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://www.stackoverflow.com");

Categories