I am making an application in Android for use with Cardboard.
At the moment I have implemented a menu that extends Activity in MainActivity and a code that activates the camera for a Cardboard (extending from CardboardActivity). My problem is when the menu selected the option in which launched this code. How I can throw a CardboardActivity within an Activity?
Sorry for my English. :(
This is the code:
package com.example.dbg.CamaraCV;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.vrtoolkit.cardboard.CardboardActivity;
public class MainActivity extends AppCompatActivity {
private Toolbar appbar;
private DrawerLayout drawerLayout;
private NavigationView navView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.dbg.CamaraCV.R.layout.activity_main);
appbar = (Toolbar)findViewById(com.example.dbg.CamaraCV.R.id.appbar);
setSupportActionBar(appbar);
getSupportActionBar().setHomeAsUpIndicator(com.example.dbg.CamaraCV.R.drawable.ic_nav_menu);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout)findViewById(com.example.dbg.CamaraCV.R.id.drawer_layout);
/*
//Eventos del Drawer Layout
drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
*/
navView = (NavigationView)findViewById(com.example.dbg.CamaraCV.R.id.navview);
navView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
boolean fragmentTransaction = false;
Fragment fragment = null;
CardboardActivity CardboardActivity =null;
switch (menuItem.getItemId()) {
case com.example.dbg.CamaraCV.R.id.menu_seccion_0:
fragment = new Fragment0();
fragmentTransaction = true;
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_1:
startActivity(new Intent(MainActivity.this, CamaraCardBoard.class));
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_2:
fragment = new Fragment2();
fragmentTransaction = true;
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_3:
fragment = new Fragment3();
fragmentTransaction = true;
break;
}
if(fragmentTransaction) {
getSupportFragmentManager().beginTransaction()
.replace(com.example.dbg.CamaraCV.R.id.content_frame, fragment)
.commit();
menuItem.setChecked(true);
getSupportActionBar().setTitle(menuItem.getTitle());
}
drawerLayout.closeDrawers();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(com.example.dbg.CamaraCV.R.menu.menu_navview, 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.
switch(item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
Related
I have created three activities explore/deals and packages. I have created my menu using drawer layout. I would like to saw my menu icon on each activity screen. I have created a base activity for menu items and extends that to all activities. I'm attaching my homeactivity code, base activity code and explore activity code below
enter image description here
Here is explore activity code
package com.example.windows81.travelspoc;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class ExploreActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.menu_second, menu); <- remove this
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
Here is my homeactivity code
package com.example.windows81.travelspoc;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.Timer;
import java.util.TimerTask;
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
ViewPager viewPager;
LinearLayout sliderDotspanel;
NavigationView mNavigationView;
private int dotscount;
private ImageView[] dots;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open,
R.string.close);
NavigationView mNavigationView = (NavigationView)
findViewById(R.id.navigation);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout.addDrawerListener(mtoggle);
mtoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for (int i = 0; i < dotscount; i++){
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8,0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.ic_active));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable
(getApplicationContext(), R.drawable.ic_active));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.navigation_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mtoggle.onOptionsItemSelected(item)){
return true;
}
switch (item.getItemId()) {
case R.id.explore:
// do what you want here
myMethod();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class MyTimerTask extends TimerTask{
#Override
public void run() {
HomeActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem() == 0){
viewPager.setCurrentItem(1);
}else if (viewPager.getCurrentItem() == 1){
viewPager.setCurrentItem(2);
}else{
viewPager.setCurrentItem(0);
}
}
});
}
}
public void myMethod(){
Intent intent = new Intent(this,ExploreActivity.class);
startActivity(intent);
}
public void exploreActivity(View view){
myMethod();
}
public void packagesActivity(View view){
Intent intent = new Intent(this,PackagesActivity.class);
startActivity(intent);
}
public void dealsActivity(View view){
Intent intent = new Intent(this,DealsActivity.class);
startActivity(intent);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.explore) {
myMethod();
}
return false;
}
}
Here is my Base activity code
package com.example.windows81.travelspoc;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
/**
* Created by Windows 8.1 on 11/15/2017.
*/
public class BaseActivity extends AppCompatActivity{
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.navigation_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.explore:
myMethod();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void myMethod(){
Intent intent = new Intent(this,ExploreActivity.class);
startActivity(intent);
}
public void exploreActivity(View view){
myMethod();
}
public void packagesActivity(View view){
Intent intent = new Intent(this,PackagesActivity.class);
startActivity(intent);
}
public void dealsActivity(View view){
Intent intent = new Intent(this,DealsActivity.class);
startActivity(intent);
}
}
Create a base activity in which u write code for menu items then extend the base activity to all your inner activities.
For Title
Create a common title layout.
Then in your HomeActivity
abstract class HomeActivity extends Activity {
protected TextView txtHeading;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void setHeading(int resId) {
if(tv_title == null)
txtHeading = findViewById(R.id.tv_title);
if(tv_title != null)
txtHeading.setText(resId);
}
}
Then in other activities like activity_main.xml
MainActivity
class MainActivity extends BaseActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setHeading(R.string.heading_main);
}
}
same goes for other activities
For Same Menu Option
public class HomeActivity extends Activity {
// other overidden methods
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item:
// do what you want here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Then in child activity
public class ChildActivity extends BaseActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.menu_second, menu); <- remove this
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
If you have same menu through out all activities then i will advice you to create one
BaseActivity then extends it to AppcompatActivity
Make Activity1 -> extends BaseActivity
Magic comes here -> You don't have to use setContentView for all the time.
Make BaseActivity with One XML -> FrameLayout -> with Your
ToolBar & FrameLayout
Now in the Activity1 inflate your view in FrameLayout of BaseActivity
And follow the same system for all the activities.
I had the same situation -> I had to display sideMenu in every Activity so i ended up with this solution.
I read this post :
I try to do it but i have trouble in the "Navigating between Menu Items" section.
Where do the code of this section go ? In the MainActivity.java file or else?
When i paste it on my IDE (Android Studio 1.4) the items "nvDrawer" and "NavigationView" are red:
Also, i have two onCreate() on the same file.
Can you give me some suggestions how to make it work?
Below the code of my MainActivity.java.
package com.ther01s.android.ma0;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
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.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
}
Install latest android studio . then go to File --> New Project-->Configure your Project-->Target Device-->Choose Navigation Drawer Activity--> finish. You will get an awesome template from Android studio itself. Dont be confused by looking up for other useless tutorials.
I'm trying to create a navigation drawer. I have created it but the problem is that when i open the app the first time, the fragment is displayed in the content area but it is not highlighted in the navigation drawer.
This is code i'm using:
package com.hfad.evenit;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.hfad.evenit.Fragments.FourthFragment;
import com.hfad.evenit.Fragments.SecondFragment;
import com.hfad.evenit.Fragments.ThirdFragment;
import com.hfad.evenit.Fragments.TopFragment;
public class Home extends AppCompatActivity {
String []FragmentTitles;
ListView DrawerList;
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
FragmentTitles = getResources().getStringArray(R.array.fragment_titles);
DrawerList = (ListView) findViewById(R.id.drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, FragmentTitles));
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
selectItem(0);
DrawerList.setSelection(0);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = drawerLayout.isDrawerOpen(DrawerList);
menu.findItem(R.id.action_share).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.
getMenuInflater().inflate(R.menu.menu_home, 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.
if(drawerToggle.onOptionsItemSelected(item))
{
return true;
}
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectItem(int position)
{
Fragment fragment;
switch(position)
{
case 0:
fragment = new TopFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
case 3:
fragment = new FourthFragment();
break;
default:
fragment = new TopFragment();
}
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
public void setActionBarTitle(int position)
{
String title;
title = FragmentTitles[position];
getSupportActionBar().setTitle(title);
}
}
The method you should use for changing the items state to "highlighted" or currently activated is setItemChecked(int position, boolean value). It's best to place it in your selectItem method so that the "highlighted" item changes once your SelectItem method is called.
You might also want to consider setting the listView's choice mode to CHOICE_MODE_SINGLE so that only one item can be in an active state at a given time.
drawerList.setChoiceMode(CHOICE_MODE_SINGLE);
Around here...
public void selectItem(int position) {
...
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
Adding DrawerList.setItemChecked(position, true); may work.
public void selectItem(int position) {
...
setActionBarTitle(position);
DrawerList.setItemChecked(position, true); // <== add this line
drawerLayout.closeDrawer(DrawerList);
}
Actually I'm not using Navigation Drawer of the Android Studio's project template but using NavigationView (it is recommended for ease to use), recently. If my answer is invalid, please forget this.
Im trying to use drawer toggle in an action bar with sherlock. This is my main activity:
import uk.co.senab.actionbarpulltorefresh.extras.actionbarsherlock.PullToRefreshAttacher;
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.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.mejorandroid.ejemplo3_clase3.fragments.MainFragment;
import com.mejorandroid.ejemplo3_clase3.fragments.TermsFragment;
public class MainActivity extends SherlockFragmentActivity
implements OnItemClickListener{
private ListView drawer_list;
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle drawer_toggle;
private PullToRefreshAttacher pullToRefreshAttacher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pullToRefreshAttacher = PullToRefreshAttacher.get(this);
drawer_list = (ListView) findViewById(R.id.left_drawer);
drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
ArrayAdapter<String> drawer_adapter = new ArrayAdapter<String>(this,
R.layout.drawer_list_item, getResources().getStringArray(
R.array.array_drawer_options));
drawer_list.setAdapter(drawer_adapter);
drawer_list.setOnItemClickListener(this);
selectItem(0);
drawer_toggle = new ActionBarDrawerToggle(this, drawer_layout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}
};
drawer_layout.setDrawerListener(drawer_toggle);
getSherlock().getActionBar().setDisplayHomeAsUpEnabled(true);
getSherlock().getActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawer_toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawer_toggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home || drawer_toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.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 PullToRefreshAttacher getAttacher() {
return pullToRefreshAttacher;
}
public void selectItem(int position){
Fragment f;
if(position==0){
f = new MainFragment();
}else{
f = new TermsFragment();
}
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.main_content, f)
.commit();
drawer_list.setItemChecked(position, true);
setTitle(drawer_list.getItemAtPosition(position).toString());
drawer_layout.closeDrawer(drawer_list);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
selectItem(position);
}
}
In the method onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home || drawer_toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
I get:
How can I fix this??
This is my main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
I had the same problem and this works for me:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (drawer_layout.isDrawerOpen(drawer_list)) {
drawer_layout.closeDrawer(drawer_list);
} else {
drawer_layout.openDrawer(drawer_list);
}
}
return super.onOptionsItemSelected(item);
}
I don't know if this problem is already fixed in the newest release of the Sherlock library / support library, but the workaround does a good job.
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
}
}