Android Navigation drawer display items twice - android

I am developing an application where i have to display a navigation drawer in home page.I am using NavigationView where i will point which menu it should populate.Now what problem i am facing is, its displaying items twice.Below code will show you what i have done so far
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.mylaw.rkme3.mylawproject.fragments.HomeFragment;
import com.mylaw.rkme3.mylawproject.fragments.VideoHomeFragment;
import com.mylaw.rkme3.mylawproject.interfaces.FragmentInterface;
import com.mylaw.rkme3.mylawproject.utils.Constants;
/**
* Created by Lincy on 7/4/2016.
**/
public class MainActivity extends AppCompatActivity implements FragmentInterface {
private static final String TAG = "MainActivity";
private Toolbar mToolBar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
displayScreens();
}
private void initView() {
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mToolBar = (Toolbar) findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setUpNavigationDrawer();
mNavigationView.inflateMenu(R.menu.drawer);
}
private void setUpNavigationDrawer() {
setSupportActionBar(mToolBar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, mToolBar,
R.string.openDrawer,
R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.isChecked())
item.setChecked(false);
else item.setChecked(true);
mDrawerLayout.closeDrawers();
switch (item.getItemId()) {
case R.id.sub_item_in_progress:
goToInProgress();
return true;
case R.id.sub_item_completed:
goToCompleted();
return true;
case R.id.sub_lapsed:
goToLapsed();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
}
private void goToLapsed() {
Intent courseLapsedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Lapsed");
courseLapsedIntent.putExtras(extras);
startActivity(courseLapsedIntent);
}
private void goToCompleted() {
Intent courseCompletedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Completed");
courseCompletedIntent.putExtras(extras);
startActivity(courseCompletedIntent);
}
private void goToInProgress() {
Intent courseProgressIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "InProgress");
courseProgressIntent.putExtras(extras);
startActivity(courseProgressIntent);
}
private void displayScreens() {
this.action(Constants.FragmentInterfaceConstants.ACTION_HOME, null);
}
#Override
public void action(int tag, Bundle args) {
switch (tag) {
case Constants.FragmentInterfaceConstants.ACTION_HOME:
handleHomeScreen();
break;
case Constants.FragmentInterfaceConstants.ACTION_VIDEO_HOME:
handleVideoHomeScreen();
break;
default:
break;
}
}
#Override
public void showActionBar(boolean show) {
}
#Override
public void showHomeButton(boolean show) {
}
#Override
public void setActionBarTitle(String title) {
}
private void handleHomeScreen() {
HomeFragment homeFragment = new HomeFragment();
addFragment(homeFragment, HomeFragment.TAG);
}
private void handleVideoHomeScreen() {
VideoHomeFragment videoHomeFragment = new VideoHomeFragment();
addFragment(videoHomeFragment, HomeFragment.TAG);
}
private void addFragment(Fragment fragment, String tag) {
FragmentTransaction ft =
getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(tag);
ft.commitAllowingStateLoss();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
}else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_Register:
Intent registerIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle extras = new Bundle();
extras.putString("fragName", "Register");
registerIntent.putExtras(extras);
startActivity(registerIntent);
break;
case R.id.item_search:
Intent searchIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle searchExtras = new Bundle();
searchExtras.putString("fragName", "Search");
searchIntent.putExtras(searchExtras);
startActivity(searchIntent);
break;
case R.id.item_login:
Intent loginIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle loginExtras = new Bundle();
loginExtras.putString("fragName", "Login");
loginIntent.putExtras(loginExtras);
startActivity(loginIntent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}

Related

I can't click on my navigation drawer

I am struggling to get the Navigation drawer items to register and start and intent for a new activity. The drawer opens fine and is displayed correctly but nothing happens when I click on the items in the list. Here is my code
package radiofm.arabel;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageButton;
import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ImageButton id_play,id_pause;
private Button btn;
private boolean playPause;
private MediaPlayer mediaPlayer;
private ProgressDialog progressDialog;
private boolean initialStage = true;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.d("myTag", "This is my toolbar");
id_play = (ImageButton) findViewById(R.id.id_play);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
progressDialog = new ProgressDialog(this);
id_play.setEnabled(true);
id_play.setImageResource(R.drawable.play);
id_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
id_play.setImageResource(R.drawable.pause);
if (initialStage) {
Log.d("myTag", "This is my excute");
new Player().execute("http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3");
} else {
Log.d("myTag", "This is my beforestart");
if (!mediaPlayer.isPlaying())
Log.d("myTag", "This is my afterstart");
mediaPlayer.start();
}
playPause = true;
} else {
id_play.setImageResource(R.drawable.play);
Log.d("myTag", "This is my beforestop");
if (mediaPlayer.isPlaying()) {
Log.d("myTag", "This is afterstop");
mediaPlayer.reset();
}
playPause = false;
}
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
class Player extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
Boolean prepared = false;
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
Log.d("myTag", "This is my listnner");
initialStage = true;
playPause = false;
id_play.setImageResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
prepared = true;
} catch (Exception e) {
// Log.e("MyAudioStreamingApp", e.getMessage());
prepared = false;
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (progressDialog.isShowing()) {
progressDialog.cancel();
}
mediaPlayer.start();
initialStage = true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Buffering...");
//progressDialog.show();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displaySelectedScreen(int id)
{
Fragment fragment=null;
Log.d("myTag", "This is my displ");
switch (id){
case R.id.nav_alarm:
fragment = new Add_Alarm();
break;
}
if (fragment !=null)
{
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main,fragment);
ft.commit();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_alarm) {
Intent goToNextActivity = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(goToNextActivity);
}
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main,fragment);
ft.addToBackStack(null);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
try change your code inside onNavigationItemSelected to this:
switch (item.getItemId()){
case R.id.nav_alarm:
//do stuff
Intent goToNextActivity = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(goToNextActivity);
break;
}
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main,fragment);
ft.addToBackStack(null);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
You should check your onNavigationItemSelected(MenuItem item) method because while replacing the fragment you initailized you fragment null like Fragment fragment = null; .So, for replace the fragment you need to take actual fragment instead of null fragmnet.
You may go through about the fragments here.
`
Change the flow of the code as below:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
item.setCheckable(false);
Fragment fragment=null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break
}
loadHomeFragment(fragment);
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void loadHomeFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commitAllowingStateLoss();
}

Call a Fragment implements View.OnClickListener in a drawermenu

I'm trying to call via my drawer menu a Fragment implements View.OnClickListener.
Hier the main code:
package thyroid.com.thyroidmenu;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
Toolbar toolbar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
setupToolbar();
DataModel[] drawerItem = new DataModel[3];
drawerItem[0] = new DataModel(R.drawable.connect, "Connect");
drawerItem[1] = new DataModel(R.drawable.fixtures, "Fixtures");
drawerItem[2] = new DataModel(R.drawable.table, "Table");
drawerItem[3] = new DataModel(R.drawable.table, "Table");
drawerItem[4] = new DataModel(R.drawable.fixtures, "Table");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(mDrawerToggle);
setupDrawerToggle();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
RegisterFragment fragment = null;
switch (position) {
case 0:
fragment = new ConnectFragment();
break;
case 1:
fragment = new FixturesFragment();
break;
case 2:
fragment = new TableFragment();
break;
case 3:
fragment = new LoginFragment();
break;
case 4:
fragment = new RegisterFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
void setupToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
void setupDrawerToggle(){
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.app_name, R.string.app_name);
//This is necessary to change the icon of the Drawer Toggle upon state change.
mDrawerToggle.syncState();
}
}
And there the fragment code with which I have problem:
package thyroid.com.thyroidmenu;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import thyroid.com.thyroidmenu.models.ServerRequest;
import thyroid.com.thyroidmenu.models.ServerResponse;
import thyroid.com.thyroidmenu.models.User;
public class LoginFragment extends Fragment implements View.OnClickListener{
private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register,tv_reset_password;
private ProgressBar progress;
private SharedPreferences pref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
initViews(view);
return view;
}
private void initViews(View view){
pref = getActivity().getPreferences(0);
btn_login = (AppCompatButton)view.findViewById(R.id.btn_login);
tv_register = (TextView)view.findViewById(R.id.tv_register);
tv_reset_password = (TextView)view.findViewById(R.id.tv_reset_password);
et_email = (EditText)view.findViewById(R.id.et_email);
et_password = (EditText)view.findViewById(R.id.et_password);
progress = (ProgressBar)view.findViewById(R.id.progress);
btn_login.setOnClickListener(this);
tv_register.setOnClickListener(this);
tv_reset_password.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.tv_register:
goToRegister();
break;
case R.id.btn_login:
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(!email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
loginProcess(email,password);
} else {
Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
}
break;
case R.id.tv_reset_password:
goToResetPassword();
break;
}
}
private void loginProcess(String email,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.NAME,resp.getUser().getName());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.apply();
goToProfile();
}
progress.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToResetPassword(){
Fragment reset = new ResetPasswordFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,reset);
ft.commit();
}
private void goToRegister(){
Fragment register = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,register);
ft.commit();
}
private void goToProfile(){
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,profile);
ft.commit();
}
}
There my errors:
"Error:(81, 28) error: incompatible types: LoginFragment cannot be converted to RegisterFragment"
How could I call this fragment ? Should I modify everything ?
The wrong thing is that you are try to cast all your fragments to RegisterFragment, and they do not extend that class.
You should cast them to Fragment:
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ConnectFragment();
break;
case 1:
fragment = new FixturesFragment();
break;
case 2:
fragment = new TableFragment();
break;
case 3:
fragment = new LoginFragment();
break;
case 4:
fragment = new RegisterFragment();
break;
default:
break;
}
...
}

Navigation drawer won't close when item selected

I have a navigation drawer that when an Item is selected, it loads the new fragment but never closes the drawer. My navigation drawer code looks like this:
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends ActionBarActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
//getActionBar().setDisplayHomeAsUpEnabled(true);
//enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_menu_white, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
//getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
//getActionBar().setTitle(mTitle);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
//setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
//setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
I also have an enum that I use for my drawer which looks like this:
import android.support.v4.app.Fragment;
public enum MainNavItem
{
// Displayed in NavDrawerListAdapter
STATISTICS("Your Statistics", R.layout.statistics_pagelayout, StatisticsPage.class),
DISCOVER ("Discover", R.layout.activity_discover, BPTopBeers.class),
PORTFOLIO ("Portfolio", R.layout.activity_portfolio, Portfolio.class),
DRINKLOCAL ("Drink Local", R.layout.beer_location_list, DrinkLocal.class),
Map ("Brewery Map", R.layout.activity_brewmap, MapTabs.class),
LISTS ("Your Lists", R.layout.activity_search, AllLists.class),
NEWS ("News", R.layout.activity_news, NewsWeb.class),
Find ("Nearby Breweries", R.layout.beer_location_list, FindBrewery.class),
CONTACT ("Contact", R.layout.activity_contact, ContactPage.class),
// Items NOT displayed in NavDrawerListAdapter
SEARCH ("Search", R.layout.activity_search, Search.class),
;
private static MainNavItem LAST_NAV_ITEM = CONTACT;
private String mTitleResId;
private int mLayoutResId;
private Class<? extends Fragment> mFragClass;
private MainNavItem(String titleResId, int layoutResId, Class<? extends Fragment> fragClass)
{
mTitleResId = titleResId;
mLayoutResId = layoutResId;
mFragClass = fragClass;
}
public int getLayoutResId()
{
return mLayoutResId;
}
public String getTitleResId()
{
return mTitleResId;
}
public Class<? extends Fragment> getFragClass()
{
return mFragClass;
}
public static MainNavItem[] getNavAdapterItems()
{
int count = LAST_NAV_ITEM.ordinal() + 1;
MainNavItem[] adapterItems = new MainNavItem[count];
for(int i = 0; i < count; i++){
adapterItems[i] = values()[i];
}
return adapterItems;
}
}
Add this to your onItemClick method of the mDrawerList
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
I can't find where are you loading fragment in your code but you are probably missing mDrawerToggle.onDrawerClosed(mDrawerLayout); before you replace your fragments.

Hold click menu item different than click?

I currently have a menu that I load into my Toolbar which looks like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:onClick="goToSearch"
android:title="Search"/>
<item android:id="#+id/action_barcode"
android:icon="#drawable/bar"
android:title="barcode"
app:showAsAction="ifRoom"
android:onClick="scanBarcode"/>
</menu>
When you click the barcode icon, it loads my barcode scanning fragment. I want to clean up my toolBar and not have multiple icons up there. Essentially I want my search icon, that opens up when clicked to have two functions.
When clicked open the search bar.
When long pressed, open my barcode scan fragment.
Currently Number one works, looking at how to employ number 2.
This is what my code looks liek for launching the barcode scan fragment and search.
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends ActionBarActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getActionBar().setDisplayHomeAsUpEnabled(true);
//enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_menu_white, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
//getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
//getActionBar().setTitle(mTitle);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
//setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
//setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
The action bar concept doesn't count on this requirement, so using built-in functionality you'll never be able to achieve what you need.
You can, however, introduce your own custom layout in stock action bar and do whatever you want there. See an example here:
http://javatechig.com/android/actionbar-with-custom-view-example-in-android

Android - ActionBarSherlock Navigation Drawer and Fragments with Activities

I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project. I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock. I have an error under the selectItem(int position) section of the code. I will paste it here:
package com.rufflez.absnavdrawer;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mFragmentTitles = getResources().getStringArray(R.array.fragments);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Sources.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
newFragment = new Fragment_3();
break;
case 3:
newFragment = new Fragment_4();
break;
case 4:
newFragment = new Fragment_5();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();. The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
// webview = (WebView) findViewById(R.id.WebView);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == View.GONE){
pd.setVisibility(View.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100) {
pd.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("file:///android_asset/about.html");
}
#Override
public void onBackPressed()
{
if(webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.
Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:
Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{
i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);
//change frag1 to corresponding XML
}
}

Categories

Resources