I am Using Google maps activity in my android application which Implements Material Design, When I am trying to add the Google maps activity in Navigation 't Drawer the application shows an error "Incompatible Types - Required : android.support.v4.app.Fragment".
Here is my mainactivity.java
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.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import info.androidhive.materialdesign.R;
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private WebView myWebView;
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();
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 FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
case 3:
fragment = new ContactFragment();
title = getString(R.string.title_contact);
break;
case 4:
fragment=new HospitalMapsActivity();
title = "Detect Hospital";
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
I haven't seen your concrete implementatios, but I think that one (or all) of this classes are android.app.Fragment instead of android.support.v4.app.Fragment: HomeFragment, FriendsFragment, MessagesFragment or ContactFragment.
To solve your problem, your fragments must extends android.support.v4.app.Fragment
Related
This question already has an answer here:
How can i find last fragment in the mainActivity
(1 answer)
Closed 6 years ago.
I want to make my viewPager support Rtl ,and set the current item on the last fragment, but when I write this code in my MainActivity.java , I don't know how I can access the last fragment.
iViewPager.setCurrentItem();
this is my MainActivity.java where I define the viewPager
package com.example.imajid.grid2.activities;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.imajid.grid2.R;
import com.example.imajid.grid2.adapters.PagerAdapter;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------- set toolbar
Toolbar iToolbar = (Toolbar) findViewById(R.id.xmlToolbar);
setSupportActionBar(iToolbar);
//------------------------------ initialize toolbar
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.menu);
actionBar.setDisplayHomeAsUpEnabled(true);
//**************************** find tablayout *****************************//
TabLayout iTabLayout = (TabLayout) findViewById(R.id.xmlTabLayout);
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//******************************* Array list for sending titles *********************************//
ArrayList<String> viewPagersTitle = new ArrayList<String>();
viewPagersTitle.add("صفحه اصلی");
viewPagersTitle.add("فیلم");
viewPagersTitle.add("آهنگ");
//******************************* find view pager in xml *****************************//
ViewPager iViewPager = (ViewPager) findViewById(R.id.xmlViewPager);
//************************************** Rtlizer view pager ************************************
====>iViewPager.setCurrentItem();
//************************************** find adapter for view pager *******************************//
PagerAdapter viewPagerAdapter = new PagerAdapter(getSupportFragmentManager() , iTabLayout.getTabCount() , viewPagersTitle);
//************************************ set adapter for view pager *******************************//
iViewPager.setAdapter(viewPagerAdapter);
//*********************************** setup tablayout to view pager********************************//
iTabLayout.setupWithViewPager(iViewPager);
mDrawerLayout = (DrawerLayout) findViewById(R.id.xmlDrawerLayoutRoot);
//-------------------------------------- find navigation view
NavigationView navigationView = (NavigationView)findViewById(R.id.xmlNavigation);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this , menuItem.getTitle() , Toast.LENGTH_SHORT).show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
//onoptionItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
String btnName = null;
switch (itemId){
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_setting:
btnName = "Setting";
break;
case R.id.menu_compass:
btnName = "Compass";
break;
case R.id.menu_help:
btnName = "Help";
break;
}
Toast.makeText(MainActivity.this , "You clicked at " + btnName , Toast.LENGTH_SHORT).show();
return true;
}
}
and this is my view pager adapter
package com.example.imajid.grid2.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.example.imajid.grid2.fragments.TabFragment1;
import com.example.imajid.grid2.fragments.TabFragment2;
import com.example.imajid.grid2.fragments.TabFragment3;
import java.util.ArrayList;
/**
* Created by imajid on 12/8/2015.
*/
public class PagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<String> titles;
int numOfTabs;
public PagerAdapter(FragmentManager fm , int numOfTabs , ArrayList<String> titles) {
super(fm);
this.numOfTabs =numOfTabs;
this.titles = titles;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return this.numOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
You can change your some portion of code::
#Override
public Fragment getItem(int position) {
switch (position){
case 2://change it from 0 -> max
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 0:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
or you can even change the fragment name too::
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
TabFragment3 tab3 = new TabFragment3();
return tab3;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment1 tab1 = new TabFragment1();
return tab1;
default:
return null;
}
}
try this out ..
you can use
HomeListFragment fragment =
(HomeListFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.viewpager+":0");
//"android:switcher:"+R.id.viewpager+":0" returns current fragment
if(fragment != null) // could be null if not instantiated yet
{
if(fragment.getView() != null)
{
ViewPager.LayoutParams params = (ViewPager.LayoutParams) group.getLayoutParams();
params.setLayoutDirection(0x00000001);
}
}
notice that 0x00000001 is const value for rtl refer to here
this solution is little tricky but , this is the best answer for this question
first of all , we need to access to getCount() of PagerAdapter.java
for this in the mainActivity.java and in the onCreate() after the defining the Instance of PagerAdapter and setting the PagerAdapter on ViewPager ( this is important write exactly after the setting the adapter) we write :
iViewPager.setCurrentItem(viewPagerAdapter.getCount());
so in my code , MainActivity be like this :
package com.example.imajid.grid2.activities;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.imajid.grid2.R;
import com.example.imajid.grid2.adapters.PagerAdapter;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------- set toolbar
Toolbar iToolbar = (Toolbar) findViewById(R.id.xmlToolbar);
setSupportActionBar(iToolbar);
//------------------------------ initialize toolbar
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.menu);
actionBar.setDisplayHomeAsUpEnabled(true);
//**************************** find tablayout *****************************//
TabLayout iTabLayout = (TabLayout) findViewById(R.id.xmlTabLayout);
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//******************************* Array list for sending titles *********************************//
ArrayList<String> viewPagersTitle = new ArrayList<String>();
viewPagersTitle.add("صفحه اصلی");
viewPagersTitle.add("فیلم");
viewPagersTitle.add("آهنگ");
//******************************* find view pager in xml *****************************//
ViewPager iViewPager = (ViewPager) findViewById(R.id.xmlViewPager);
//************************************** Rtlizer view pager ************************************
//************************************** find adapter for view pager *******************************//
PagerAdapter viewPagerAdapter = new PagerAdapter(getSupportFragmentManager() , iTabLayout.getTabCount() , viewPagersTitle);
//************************************ set adapter for view pager *******************************//
iViewPager.setAdapter(viewPagerAdapter);
iViewPager.setCurrentItem(viewPagerAdapter.getCount());
//*********************************** setup tablayout to view pager********************************//
iTabLayout.setupWithViewPager(iViewPager);
mDrawerLayout = (DrawerLayout) findViewById(R.id.xmlDrawerLayoutRoot);
//-------------------------------------- find navigation view
NavigationView navigationView = (NavigationView)findViewById(R.id.xmlNavigation);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this , menuItem.getTitle() , Toast.LENGTH_SHORT).show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
//onoptionItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
String btnName = null;
switch (itemId){
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_setting:
btnName = "Setting";
break;
case R.id.menu_compass:
btnName = "Compass";
break;
case R.id.menu_help:
btnName = "Help";
break;
}
Toast.makeText(MainActivity.this , "You clicked at " + btnName , Toast.LENGTH_SHORT).show();
return true;
}
}
Here is my MainActivity
package com.arrival.grontha;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
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 com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_activity_main);
mToolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(mToolbar);
//Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData(getResources().getString(R.string.app_name), getResources().getString(R.string.email), BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo_app));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
switch (position) {
case 0: //stats
fragment = getFragmentManager().findFragmentByTag(Fragment_Books.TAG);
if (fragment == null) {
fragment = new Fragment_Books();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, Fragment_Books.TAG).commit();
break;
case 1:
fragment = getFragmentManager().findFragmentByTag(Fragment_Favorite.TAG);
if (fragment == null) {
fragment = new Fragment_Favorite();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, Fragment_Favorite.TAG).commit();
break;
case 2:
fragment = getFragmentManager().findFragmentByTag(Fragment_About.TAG);
if (fragment == null) {
fragment = new Fragment_About();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, Fragment_About.TAG).commit();
break;
}
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
#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.unused, menu);
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.
int id = item.getItemId();
switch(id) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
And Here is My SettingsActivity
package com.arrival.grontha;
import android.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class SettingsActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
I try to to Switch the SettingsActivity using a ActionBar Menu. It work, but when the SettingsActivity appear my ActionBar goes Disappear :(
How can i solve it? Please Help me....
I had the same thing happen. I'm using AndroidStudio 2.3 and created a new activity. The IDE added android:theme="#style/AppTheme.NoActionBar" to the AndroidManifest.xml while creating the new activity.
You need to call setSupportActionBar(yourToolbar) to display the Toolbar. Also, make sure that your activity_settings.xml has a Toolbar defined in it.
I had accidentally extended Activity instead of AppCompatActivity, which would have included the toolbar by default.
I am trying to use SherlockFragment to create a Fragment, selected from a navigation drawer activity to show a tabbed fragment. My main activity is below:
package com.impact.main;
import com.impact.main.R;
import com.impact.adapters.NavDrawerListAdapter;
import com.impact.helper.SQLiteHandler;
import com.impact.helper.SessionManager;
import com.impact.helper.dbTables;
import com.impact.model.NavDrawerItem;
import java.util.ArrayList;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private com.impact.helper.SQLiteHandler db;
private com.impact.helper.SessionManager session;
GoogleCloudMessaging gcm;
Context context;
String[] title;
Menu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SqLite database handler
db = new com.impact.helper.SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
//get length of menu list
String storedStaffId = SQLiteHandler.getUser(getApplicationContext(), "staffid");
int length = getResources().getStringArray(R.array.nav_drawer_items).length;
int projectsCount = db.getRowCount(dbTables.TABLE_PROJECTS,
"INNER JOIN projectstaff AS p ON p.projectid=projects.projectid WHERE staffid=" + storedStaffId);
// adding nav drawer items to array
for(int i=0; i<length; i++){
if(i == 1 ){
//add menu item with user project count
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons.getResourceId(i, -1), true, ""+projectsCount));
}else{
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons.getResourceId(i, -1)));
}
}
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("");
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.logout:
logoutUser();
return true;
case R.id.unlink:
Toast.makeText(getApplicationContext(), "No Data Connection \nOperating in offline mode", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
boolean isOnline = SessionManager.isOnline(getApplicationContext());
if(isOnline == false){
menu.findItem(R.id.unlink).setVisible(true);
}else{
menu.findItem(R.id.unlink).setVisible(false);
}
menu.findItem(R.id.logout).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
SherlockFragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new ProjectsFragment();
break;
case 2:
fragment = new WorkListFragment();
break;
case 3:
fragment = new ChangeControlFragment();
break;
case 4:
fragment = new CostControlFragment();
break;
case 5:
fragment = new MeetingsFragment();
break;
case 6:
fragment = new ActionsFragment();
break;
case 7:
fragment = new PerformanceFragment();
break;
case 8:
fragment = new DocumentsFragment();
break;
case 9:
fragment = new ReportsFragment();
break;
case 10:
fragment = new ProjectAdminFragment();
break;
case 11:
fragment = new SystemAdminFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SherlockFragment sherfragment = new SherlockFragment();
fragmentTransaction.replace(R.id.frame_container, sherfragment);
fragmentTransaction.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
public void logoutUser() {
// notifies user
//GCMIntentService.generateNotification(getApplicationContext(), "Logged out");
session.setLogin(false);
db.emptyTable("login");
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
Most of the fragments are constructed like this
package com.impact.main;
import com.actionbarsherlock.app.SherlockFragment;
import com.impact.main.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends SherlockFragment {
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
The problem comes when selecting the menu item, I get the following error
java.lang.NoClassDefFoundError: com.main.impact.HomeFragment
This is a bit new to me so I'm not sure exactly what else to include, needless to say that i'll update the question should that be required. Thanks in advance.
First of all thanks a lot to everyone who helped me out with this. I've managed to get this error sorted.
The problem was with using SherlockFragment. I simply changed my fragments to extend android.support.v4.app.Fragment and made the following change to displayView in my main activity
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment);
fragmentTransaction.commit();
...
This is my MainActiviy.java
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.app.Fragment;
import android.support.v4.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 MainActivity 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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = new MyFragment1();
FragmentManager fragmentManager = getSupportFragmentManager();
switch(position) {
case 1:
fragment = new MyFragment1();
break;
case 2:
fragment = new MyFragment2();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.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 = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#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.main, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
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_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
The error I get when trying to run the application is:
Error:(63, 17) error: no suitable method found for replace(int,android.app.Fragment)
method FragmentTransaction.replace(int,android.support.v4.app.Fragment,String) is not applicable
(actual and formal argument lists differ in length)
method FragmentTransaction.replace(int,android.support.v4.app.Fragment) is not applicable
(actual argument android.app.Fragment cannot be converted to android.support.v4.app.Fragment by method invocation conversion)
Any help would be greatly appreciated. The code I inserted is from this post:
How to change fragments using Android navigation drawer
My minsdk version is 14 and my target sdk version is 21.
If you use the support FragmentManager, you must use support Fragments. Or, use non-support versions of each.
Hello I'm new to android developing and I and getting errors in the MainActivity class.
package com.Keondrae.everythingminecraft;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.app.ActionBar;
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 MainActivity 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_main);
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.frame_container, Fragment)
.commit();
}
public void onSectionAttached(int position) {
switch (position) {
case 1:
Fragment = new Welcome();
break;
case 2:
Fragment = new Tutorials();
break;
case 3:
Fragment = new Blueprints();
break;
case 4:
Fragment = new Wiki();
break;
case 5:
Fragment = new Chat();
break;
case 6:
Fragment = new Item_Search();
break;
case 7:
Fragment = new Recipes();
break;
case 8:
Fragment = new Wallpaper();
break;
case 9:
Fragment = new Maps_Mods();
break;
default :
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 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.main, 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.
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_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
I'm getting "Cannot resolve method 'getFragment'()", "Cannot resolve symbol 'fragmentManager'", "Cannot resolve symbol 'frame_container'" and "Cannot resolve symbol 'fragment'". Any help will be great. Thank you.
Gradle requires that you define fragmentManager in your code.