Getting back to the fragment which calls another activity - java

I have my MainActivity which has two fragments, say fragment1 and fragment2. Now when the activity starts the default fragment is fragment1. Then I navigate to fragment2, which in turn creates another activity say CalledActivity on some event changes. What I want is to be able to navigate back to fragment2 rather than fragment1 on back press in CalledActivity. How can I accomplish that?
Looked at few SO questions, there seems to be no clear answer.
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
private Toolbar toolbar;
//for display of name and email inside the navigation drawer header
private TextView name_header;
private TextView email_header;
private String nameChar;
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session class instance
session = new SessionManager(getApplicationContext());
session.checkLogin();
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name_header = (TextView) findViewById(R.id.name_header);
email_header = (TextView) findViewById(R.id.email_header);
name_header.setText(Config.USER_FULL_NAME);
email_header.setText(Config.USER_EMAIL);
nameChar= Utils.parseName(Config.USER_FULL_NAME);
TextDrawable drawable = TextDrawable.builder()
.buildRound(nameChar, Color.parseColor("#FF6F00"));
ImageView image = (ImageView) findViewById(R.id.image_view_name);
image.setImageDrawable(drawable);
/**
* Lets inflate the very first fragment
* Here , we are inflating the TabFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new PrimaryFragment()).commit();
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_product) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new ProductsFragment()).addToBackStack( "products fragment commit" ).commit();
}
if (menuItem.getItemId() == R.id.nav_item_home) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new UploadImageFragment()).addToBackStack( "home fragment commit" ).commit();
}
if (menuItem.getItemId() == R.id.nav_item_order) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).addToBackStack( "orders fragment commit" ).commit();
}
return true;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
this.finish();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String stredittext = data.getStringExtra("edittextvalue");
Log.d("xyz",stredittext);
}
}
}
}

you have to override the onOptionsItemSelected method on your CalledActivity activity like this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}

Related

Navigation between fragments with back button

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;
}
}

How to setup base activity for new Navigation Drawer in Android?

I create activity with Android studio, however I don't know how to setup the fragment class when the activity is launched. Whenever, I start the activity I am getting a blank screen. This means that the home screen is not a fragment class screen.
Code is below:
public class Dashboard extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ActionBarDrawerToggle toggle;
DrawerLayout drawer;
NavigationView navigationView;
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
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.dashboard, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
selectDrawerItem(item);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_dashboard:
fragmentClass = DashboardFragment.class;
break;
case R.id.nav_importexport:
fragmentClass = ImportexportFragment.class;
break;
case R.id.nav_backuprestore:
fragmentClass = BackuprestoreFragment.class;
break;
case R.id.nav_setting:
fragmentClass = SettingFragment.class;
break;
default:
fragmentClass = DashboardFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_dashboard, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
}
}
you have already setup fragment classes on click of drawer item.
case R.id.nav_dashboard:
fragmentClass = DashboardFragment.class;
break;
Here is the code for multiple fragments where you are getting id and opening DashboardFragment.
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_dashboard, fragment).commit();
fragments are well replaced over here.

How change a textview from a fragment on android studio

I am having a problem. I have an activity that implements several fragments. Now I need to update a textview of one of the fragments, I have the string in the activity, so I need to pass this string to the fragment and update that textview.
NavigationDrawer.java --> this is the activity
String user = "";
InicialPage inicialpage = new InicialPage();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_naviagation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
user = extras.getString("KEY"); // TODO this is the value that i need to pass to the fragment InicialPage
}
Bundle bundle = new Bundle();
bundle.putString("USER", user);
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);
android.support.v4.app.FragmentTransaction fragmenttransaction =
getSupportFragmentManager().beginTransaction();
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
//inicialpage.setUsernameTextView(user);
DrawerLayout drawer1 = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer1.closeDrawer(GravityCompat.START);
TextView userNameTextView = (TextView)findViewById(R.id.usernametext);
//userNameTextView.setText(user);
android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.InicialPage);
}
#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.naviagation_drawer, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected (MenuItem item){
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.FragmentTransaction fragmenttransaction =
getSupportFragmentManager().beginTransaction();
if (id == R.id.InicialPage) {
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
} else if (id == R.id.HistoryItem) {
fragmenttransaction.replace(R.id.container, new Historic());
fragmenttransaction.commit();
} else if (id == R.id.FriendsItem) {
fragmenttransaction.replace(R.id.container, new Friends());
fragmenttransaction.commit();
} else if (id == R.id.PointsItem) {
fragmenttransaction.replace(R.id.container, new Points());
fragmenttransaction.commit();
} else if (id == R.id.BookBikeItem) {
fragmenttransaction.replace(R.id.container, new BookBike());
fragmenttransaction.commit();
} else if (id == R.id.MessagesItem) {
fragmenttransaction.replace(R.id.container, new Messages());
fragmenttransaction.commit();
}else if(id == R.id.Mapdebug)
{
Intent maps = new Intent(this,MapsActivity.class);
startActivity(maps);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void FrameClicked(View view) {
//send user name to chat
Intent i = new Intent(this, Chat.class);
i.putExtra("USER", user);
startActivity(i);
}
public void addFriend(View view) {
LinearLayout principalLayout= (LinearLayout) findViewById(R.id.idFriendsVertical);
LinearLayout secondaryLauout= new LinearLayout(this);
TextView tx= new TextView(this);
EditText et= (EditText) findViewById(R.id.ADD);
String edittx= String.valueOf(et.getText().toString());
if (edittx.equals("")) {
}else
{
tx.setText(edittx);
tx.setTextSize(22);
tx.setTextColor(Color.BLACK);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.setMargins(0, 20, 0, 10);
secondaryLauout.addView(tx, params);
principalLayout.addView(secondaryLauout);
}
et.setText("");
}
}
InicialPage.java --> this is the fragment
public class InicialPage extends Fragment {
SQLiteDatabase db;
View view;
TextView usernameTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_inicial_page, container, false);
usernameTextView = (TextView) view.findViewById(R.id.usernametext);
return view;
}
If I understand your question correctly, you need to add inicialpage.setArguments(bundle); before your replace and commit in your fragment transaction.
Then, inside your Fragment you call
Bundle bundle = getArguments();
String bundleText = bundle.getString("USER");
to retrieve it.
You were already creating a bundle so I'm assuming that's the data you want to send. You have to attach that bundle to the Fragment before your Fragment Transaction though.
Inside your Activity:
Bundle bundle = new Bundle(); //create the bundle
bundle.putString("USER", user); //attach data to the bundle
inicialpage.setArguments(bundle); //set the bundle on the fragment
//perform fragment transaction
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
Inside your Fragment:
//retrieve the bundle
Bundle bundle = getArguments(); //retrieve the bundle
String bundleText = bundle.getString("USER"); //get the data on the bundle
//find view & set the text
usernameTextView = (TextView) view.findViewById(R.id.usernametext);
usernameTextView.setText(bundleText);
This type of problem can be solved using Localbroadcast Receiver .Write the following code in your fragment. Something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("custom-event-name"));
return view;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
usernameTextView.setText(message);
Log.d("receiver", "Got message: " + message);
}
};
then pass the user value by adding this following code in your activity when you want to pass
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", user);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

new fragment cannot be loaded by clicking on Drawer item in Android Studio

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;
}
}

Display logo in ActionBar

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"

Categories

Resources