I'm very new to android development and have ran into an issue that I can't seem to get around or get my head around the resolution.
I'm trying to add a navigation drawer to an activity that has a bottom navigation bar in the java program. I've got the XML looking good and working but the below java is reporting the following error:
'onCreate(Bundle)' is already defined in 'MyApp'
which I understand and can see but I don't know how to resolve it - is it possible?
public class Dash extends AppCompatActivity {
private DrawerLayout drawer;
Button signout;
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
signout=findViewById(R.id.logout);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Existing.class));
finish();
}
});
chipNavigationBar = findViewById(R.id.bottom_nav_menu);
chipNavigationBar.setItemSelected(R.id.bottom_nav_menu, true);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new NewsFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int i) {
Fragment fragment = null;
switch (i) {
case R.id.bottom_nav_menu:
fragment = new HomeFragment();
break;
case R.id.bottom_nav_news:
fragment = new NewsFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override public void onBackPressed(){
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Remove one OnCreate(....)
Try Below Code:
public class Dash extends AppCompatActivity {
private DrawerLayout drawer;
Button signout;
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
signout=findViewById(R.id.logout);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Existing.class));
finish();
}
});
chipNavigationBar = findViewById(R.id.bottom_nav_menu);
chipNavigationBar.setItemSelected(R.id.bottom_nav_menu, true);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new NewsFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int i) {
Fragment fragment = null;
switch (i) {
case R.id.bottom_nav_menu:
fragment = new HomeFragment();
break;
case R.id.bottom_nav_news:
fragment = new NewsFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
});
}
#Override public void onBackPressed(){
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Related
I know that this subject has been already discussed, but I have difficulties with implementing navigation between fragments. I want to return to a previous fragment or main activity using the back button. Now, the back button only closes the navigation drawer or exits the app. I know I should use addToBackStack but I don't know exactly how.
My MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("infoGmina");
ImageView gminaImageView = (ImageView) findViewById(R.id.gminaImageView);
ImageView weatherImageView = (ImageView) findViewById(R.id.weatherImageView);
ImageView partlyCloudImageView = (ImageView) findViewById(R.id.partlyCloudImageView);
partlyCloudImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PogodaFragment fragment = new PogodaFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.replacableConstraintLayout, fragment);
transaction.commit();
}
});
weatherImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WeatherFragment fragment = new WeatherFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.replacableConstraintLayout, fragment);
transaction.commit();
}
});
gminaImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AnnouncementListFragment fragment = new AnnouncementListFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.replacableConstraintLayout, fragment);
transaction.commit();
}
});
ParseAnalytics.trackAppOpenedInBackground(getIntent());
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_gmina) {
AnnouncementListFragment listFragment = new AnnouncementListFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.replacableConstraintLayout, listFragment).commit();
setTitle("Gmina");
} else if (id == R.id.nav_restauracja) {
} else if (id == R.id.nav_sklep) {
} else if (id == R.id.nav_weather) {
WeatherFragment weatherFragment = new WeatherFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.replacableConstraintLayout, weatherFragment).commit();
setTitle("Jakość powietrza");
} else if (id == R.id.nav_pogoda) {
PogodaFragment pogodaFragment = new PogodaFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.replacableConstraintLayout, pogodaFragment).commit();
setTitle("Pogoda");
} else if (id == R.id.nav_onas) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
i create this drawer from empty activity so i don't use fragment
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private Button signOut;
private DrawerLayout nDrawer;
private ActionBarDrawerToggle nToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
when i put this setNavigaionViewListener, this activity will crash on build, do i wrong somewhere ?
//setNavigationViewListner();
//get firebase auth instance
auth = FirebaseAuth.getInstance();
and i don't know why but get current user don't work but i don't get where the error is.
//get current user
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
signOut = (Button) findViewById(R.id.sign_out);
nDrawer = (DrawerLayout) findViewById(R.id.drawer);
nToggle = new ActionBarDrawerToggle(MainActivity.this,nDrawer,R.string.open,R.string.close);
nDrawer.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
//method to set Listener
private void setNavigationViewListner() {
NavigationView navigationView = (NavigationView) findViewById(R.id.drawer);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.account:{
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
break;
}
case R.id.logout:{
signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
}
}
nDrawer.closeDrawer(GravityCompat.START);
return true;
}
//sign out method
public void signOut() {
auth.signOut();
}
Use this
Toolbar toolbar = (Toolbar) findViewById(R.id.Yourtoolbar);
nToggle = new ActionBarDrawerToggle(
MainActivity.this, nDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
instead of this
nToggle = new ActionBarDrawerToggle(MainActivity.this,nDrawer,R.string.open,R.string.close);
and also change this remove DrawerLayout findViewById(R.id.drawer) and put Your NavigationView ID
EXample findViewById(R.id.YournavigationView);
NavigationView navigationView = (NavigationView) findViewById(R.id.YournavigationView);
in my main activity I initialized a class with a method which download data from my server.
I want to show a Progress Dialog until the download. But it doesn't show the Progress Dialog.
My Main Activity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
setFragmentManager(new MainActivityFragment());
Updater updater = new Updater(this,(ViewGroup) findViewById(R.id.fragment));
updater.check();
}
public void setFragmentManager(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#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();
switch (id){
case R.id.action_settings:
return true;
case R.id.medi_calc_item:
setFragmentManager(new MediCalcFragment());
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_start:
setFragmentManager(new MainActivityFragment());
break;
case R.id.nav_medis:
setFragmentManager(new MediAbcFragment());
break;
case R.id.nav_bos:
setFragmentManager(new BosAbcFragment());
break;
default:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
My Class:
public class Updater {
private Context context;
private ViewGroup viewGroup;
private VersionsDAO versionsDAO;
private MediDAO mediDAO;
private RegioDAO regioDAO;
private HashMap<String,Integer> onlineVersions;
private HashMap<String,Integer> versions;
private ProgressDialog progressDialog;
public Updater(Context context, ViewGroup viewGroup) {
this.context = context;
this.versionsDAO = new VersionsDAO(context);
this.mediDAO = new MediDAO(context);
this.viewGroup = viewGroup;
this.onlineVersions = new HashMap<>();
this.regioDAO = new RegioDAO(context);
this.progressDialog = new ProgressDialog(context);
}
public void check(){
progressDialog.setMessage(context.getString(R.string.update_cities));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.show();
RequestQueue queue = Volley.newRequestQueue(this.context);
String url ="http://resper.de/resperApi.php?cmd=deStadt";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
for(int i = 0; i < jArray.length(); i++){
JSONObject jObject = jArray.getJSONObject(i);
regioDAO.insertDeStadt(jObject.getInt("id"), jObject.getString("name"), jObject.getInt("bl"), jObject.getInt("rb"), jObject.getInt("kreis"), jObject.getInt("lk"));
}
versionsDAO.updateVersion("deStadt", onlineVersions.get("deStadt"));
progressDialog.cancel();
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverNotAvailable();
}
});
queue.add(stringRequest);
progressDialog.cancel();
}
}
Remove progressDialog.cancel(); from last line. That is after queue.add(stringRequest); and try again.
I've implemented the following code , but when I run the app and click on an item in Drawer nothing happened. I guess it's a problem related to the Listener but I couldn't grasp how to fix it. or maybe other problem!
once I click on one item the only thing happen is the following two lines in the logcat :
01-12 03:14:26.606 1565-1565/? I/LatinIME: Starting input. Cursor position = -1,-1
01-12 03:14:29.601 1565-1565/? I/LatinIME: Starting input. Cursor position = 0,0
here is the code:
public class Welcome extends AppCompatActivity {
private DrawerLayout mDrawer,dlDrawer;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
dlDrawer.setDrawerListener(drawerToggle);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.drawer_layout, new EditPersonal());
tx.commit();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, dlDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
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 = EditPersonal.class;
break;
case R.id.nav_second_fragment:
fragmentClass = Chronogram.class;
break;
case R.id.nav_third_fragment:
fragmentClass = BloodTest.class;
break;
case R.id.nav_forth_fragment:
fragmentClass = GlucoseTest.class;
break;
case R.id.nav_fifth_fragment:
fragmentClass = SendRecord.class;
break;
case R.id.nav_sixth_fragment:
fragmentClass = ReviewLogin.class;
break;
case R.id.nav_seventh_fragment:
fragmentClass = SignOut.class;
break;
default:
fragmentClass = EditPersonal.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();
}
// ...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
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);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
}
the app screen shot:
On your switch case, try something like this:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
case R.id.nav_first_fragment:
EditPersonal editPersonal= new EditPersonal();
fragmentTransaction.replace(R.id.flContent, editPersonal);
fragmentTransaction.commit();
break;
Do this on other cases too.
Have you tried putting logs into your code to see where the logic flows to or fails to flow to?
For example inside your switch statement, try seeing if menuItem.getItemId() actually matches your case statements. It'd help to see if your listener is actually the problem or if it's just not matching the cases. Or it could be a problem with your fragment manager.
Check out http://developer.android.com/reference/android/util/Log.html. You should be able to see the logs in logcat. Good luck!
Basically I have changed the code using the Activity (Navigation Drawer Activity) of Android studio itself. so here is the code :
public class Welcome extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.review_login_listview, 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.menu_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_first_fragment) {
// Handle the camera action
}
else {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I have an action bar but have only been to display the title of application or/and the title of the current fragment activity into it. I would want to display logo in it, and any attempts to add a logo have been unsuccessful.
Below is the code:
public class MainActivity extends ActionBarActivity {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView button=(ImageView)findViewById(R.id.logobutton);
mOptionMenu = new String[] { "Opción 1", "Opción 2", "Opción 3" };
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout)
findViewById(R.id.left_drawer);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
mOptionMenu));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mTitleSection = mOptionMenu[position];
getSupportActionBar().setTitle(mTitleSection);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
});
mDrawerList.setItemChecked(0, true);
mTitleSection = getTitle();
mTitleApp = getTitle();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitleSection);
getSupportActionBar().setLogo(R.drawable.logo);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
getSupportActionBar().setLogo(R.drawable.logo);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
;
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I tried adding this line in the code, but no image is being displayed:
getSupportActionBar().setLogo(R.drawable.logo);
I also have a similar concern, in that I want the logo to be clickable and to direct user to the MainActivity
You have to enable Logo feature on you ActionBar by calling getSupportActionBar().setDisplayUseLogoEnabled(true).
Try this in your OnCreate in this order:
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_logo);
In your manifest, you can set android:logo="#drawable/logo" on your <application> node, and/or android:icon="#drawable/icon" for each <activity> node.
In your mainfest file, add under <application>:
android:icon="#drawable/logo"