I would like to add a share button that opens something like this.
I am using this source from the official Android site
I want to send standard text so I thought I should use this part:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);
But I have no idea where to place the code.
How would I do it if I wanted to place it in 1 of these 3 spots?
I would prefer to have it in the Menu or up top and just remove the button below but I am open to any solution.
To add a click event listener to the FloatingActionButton:
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
share();
}
});
private void share(){
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);
}
To handle a menu item click:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.yourItemId:
share();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
From your comment : This worked for me. Is there anyway to do this on top of the screen next to the settings button?
You have to create menu directory in resource/res. Then, create a menu. Add following source code to menu.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/share"
android:title="Shar"/>
</menu>
Add following source code to MainActivity
#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) {
int id = item.getItemId();
switch (id){
case R.id.share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you want to trigger this code from your navigation drawer, then you need to override the onNavigationItemSelected method in your calling activity like this
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_share: {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);
break;
}
}
//close navigation drawer
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
Identify the ID of the menu item, then place the code accordingly.
Related
Instead of the action overflow icon opening a menu I would like it to immediately send the user to the settings page when it's clicked.
I know that in order to create the action overflow icon and have it open a menu this is the way you do it:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.pab_menu, menu);
return true;
}
So I replaced it with this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivityForResult(intent, 8);
return true;
}
Needless to say it didn't work.
You can add a menu item and make this always visible for the icon you can assign the overflow icon and set it to show always
So your pab_menu.xml will be like:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/settings"
android:icon="#drawable/overflow_icon"
android:title="#string/settings"
android:showAsAction="always" />
</menu>
And your action handling:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivityForResult(intent, 8);
return true;
default:
return super.onContextItemSelected(item);
}
}
So basically I have an app in the making that uses navigation drawer to navigate across all activity. I have successfully make the drawer but the items inside were unable to respond and bring me to the respective activity.
This is part of my MainActivity.java that should do the action:
NavigationView nv = (NavigationView)findViewById(R.id.nv1);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case(R.id.btLogout):
logout();
Toast.makeText(MainActivity.this, "Logging Out", Toast.LENGTH_SHORT).show();
Intent in = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(in);
break;
case(R.id.enquiries):
Intent in2 = new Intent(getApplicationContext(), EnquiryActivity.class);
startActivity(in2);
break;
}
return true;
}
});
}
private void logout()
{
session.setLoggedIn(false);
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
And this is my navigation_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/timetable"
android:icon="#mipmap/ic_schedule_black_24dp"
android:title="Timetable"></item>
<item android:id="#+id/attendance"
android:icon="#mipmap/ic_trending_up_black_24dp"
android:title="Attendance"></item>
<item android:id="#+id/weeklyreport"
android:icon="#mipmap/ic_assignment_black_24dp"
android:title="Weekly Report"></item>
<item android:id="#+id/upcomingevents"
android:icon="#mipmap/ic_event_black_24dp"
android:title="Upcoming Events"></item>
<item android:id="#+id/announcements"
android:icon="#mipmap/ic_announcement_black_24dp"
android:title="Announcements"></item>
<item android:id="#+id/enquiries"
android:icon="#mipmap/ic_person_black_24dp"
android:title="Enquiries"></item>
<item android:id="#+id/btLogout"
android:icon="#mipmap/ic_highlight_off_black_24dp"
android:title="Logout"></item>
</menu>
May I know where did I go wrong? I'm quite new to this but I tried my best. Appreciate any help.
Try using the method below:
NavigationView nv = (NavigationView)findViewById(R.id.nv1);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case(R.id.btLogout):
logout();
Toast.makeText(MainActivity.this, "Logging Out", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
case(R.id.enquiries):
startActivity(new Intent(MainActivity.this, EnquiryActivity.class));
break;
}
return true;
}
});
}
For my application I used a bouton to logout, but now I would like to use the action bar (When user click on logout icon he goes to homepage) and I can't make them live together.
(I'm french, its hard to code because all tuto are in english. So please be patient with me).
Thank you very much.
My button code was :
btn_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sessionManager.logout();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
});
My code where I would like to add icon logout :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
return true;
}
return super.onOptionsItemSelected(item);
}
My XML :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_logout"
android:icon="#android:drawable/ic_lock_power_off"
android:title="#string/logout"
app:showAsAction="ifRoom" />
</menu>
You need to do something when the user taps the menu item.
if (id == R.id.action_logout) {
logout();
return true;
}
Move your logout code to a method so you can call it from any place:
private void logout() {
sessionManager.logout();
startActivity(new Intent(this, MainActivity.class));
finish();
}
Work good like this. Thank you guys.
#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_logout) {
sessionManager.logout();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
At the moment i use this code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
, but now the Button shouldnt be only a back-function. I like to start an other activity:
Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
startActivity(intent);
I know i should use the setOnClickListener, but I don't know where i call the Listener.
Although I agree with Tanis.7x comment, you shouldn't be using that button if it's not to go back by calling finish() or popBackStack(),
the action for the home button is called with the menu options
http://developer.android.com/guide/topics/ui/actionbar.html#Home
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
i want to show my menu with action bar, but my menu won't display, this is my source code :
public class EpolicyMainActivity extends TabActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
//hide title bar
BasicDisplaySettings.toggleTaskBar(EpolicyMainActivity.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(EpolicyMainActivity.this, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, LoginActivity.class);
spec = tabHost.newTabSpec("Login").setIndicator("",
res.getDrawable(R.drawable.epolicy_menu_xml_home))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, NABActivity.class);
spec = tabHost.newTabSpec("NAB").setIndicator("",
res.getDrawable(R.drawable.epolicy_menu_xml_nab))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, ContactActivity.class);
spec = tabHost.newTabSpec("Contact").setIndicator("",
res.getDrawable(R.drawable.epolicy_menu_xml_contact))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, AgenActivity.class);
spec = tabHost.newTabSpec("Agen").setIndicator("",
res.getDrawable(R.drawable.epolicy_menu_xml_agen))
.setContent(intent);
tabHost.addTab(spec);
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++){
tabHost.getTabWidget().getChildAt(i).setPadding(0,0,0,0);
tabHost.getTabWidget().getChildTabViewAt(i).setBackgroundDrawable(null);
}
tabHost.setCurrentTab(0);
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_bantuan:
Intent itAbout = new Intent(EpolicyMainActivity.this, EpolicyBantuan.class);
itAbout.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(itAbout);
break;
case R.id.menu_exit:
dialogExit();
break;
case R.id.menu_logout:
dialogSignOut();
break;
}
return true;
}
public void dialogSignOut()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Apakah anda ingin sign-out?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent itSignOut = new Intent(EpolicyMainActivity.this, LoginActivity.class);
itSignOut.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(itSignOut);
finish();
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dialogExit()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Apakah anda ingin keluar?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent itSplashEnd = new Intent(EpolicyMainActivity.this, SplashOutActivity.class);
itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(itSplashEnd);
finish();
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onBackPressed() {
dialogExit();
}
this is my menu.xml :
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_bantuan"
android:title="#string/menu_bantuan"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"/>
<item android:id="#+id/menu_exit"
android:title="#string/menu_exit"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText" />
<item android:id="#+id/menu_logout"
android:title="#string/menu_logout"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText" />
in my main layout, i'm using header, is this giving effect to my menu, so my menu won't display or anything else?
I was under the assumption that you should always first call super.
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
I am assuming your menu.xml has an appropriate menu closing tag. Do you have this xml file stored in your res/menu folder? Can you verify that onCreateOptionsMenu is called?
On Android 2.3 and lower you will have to press the menu button, whereas in later distributions it should be displayed in the title bar. Since you are using a TabActivity I assume you are writing an app for Android 2.3.
This question might be useful for the onMenuItemSelected() method:
Merge TabActivity menu with contained Activities menus
For Activities within you TabActivity: How to create an optionsMenu in an Android's TabActivity
Perhaps when you press the menu button, the options menu of the specific tab activity that you are in (e.g. LogInActivity) is called, and not that of its parent. Try putting this code in every subactivity:
public boolean onCreateOptionsMenu(Menu menu)
{
return getParent().onCreateOptionsMenu(menu);
}
Google decided to avoid using menu at all. Please read this article http://android-developers.blogspot.ru/2012/01/say-goodbye-to-menu-button.html
If device doesn't have hardware menu button and you set targetSDK version > 10 user does not have ability to use menu. As short term solution you can set targetSDK = 10 as long term solution consider using ActionBar http://developer.android.com/guide/topics/ui/actionbar.html