I am trying to open another activity when a button is clicked from Context Menu Action Bar. But the application is force closing when i click the button.Can't we use intents in contextual action mode?
This is my code:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.item_id:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
break;
}
}
Related
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.
I have a Tabbed Activity with 3 different tabs with fragments.
I have a Toolbar too and in this Toolbar i have 1 static menu object and 1 dynamic object.
I put the static object (bluetooth connection) into MainActivity that contains Fragments loaded into a container and the dynamic button into the Fragment that need that button.
The problem is that if i declare the method of menu into MainActivity, the methods declared into fragments are useless and when i press the icon nothing happends....
But if i delete the method that manage menu into MainActivity now the buttons into fragments works...
There is some way to around this thing?
Or the only way is to repeat to every fragments the static button and for each fragment add the specific buttons that other fragments don't need?
MainActivity menu method:
#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.
switch (item.getItemId()) {
case R.id.action_bluetooth:
if (mBluetoothService == null) {
Log.d(TAG, "menu Bluetooth button");
setupComunication();
} else {
mBluetoothService = null;
setupComunication();
}
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
//findDevice();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Fragment menu method:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_dashboard, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#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 R.id.action_commands:
// User chose the "Settings" item, show the app settings UI...
Intent settingsIntent = new Intent(getActivity(), SettingsActivity.class);
startActivityForResult(settingsIntent, RESULT_SETTINGS);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Override these two methods in your Fragment, add items of menu_dashboard to menu_main and set visibility of menuItem to false by default:
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_commands).setVisible(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 R.id.action_commands:
// User chose the "Settings" item, show the app settings UI...
Intent settingsIntent = new Intent(getActivity(), SettingsActivity.class);
startActivityForResult(settingsIntent, RESULT_SETTINGS);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
My problem is almost the same as this Stop AsyncTask in Fragments when Back Button is pressed
But I want to stop my AsyncTask when the back arrow is clicked. I have a code in stoping asynctask and it works when I implemented it in another way. I tried what I researched so far but I still got errors. Please help me with this.
I tried this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==android.R.id.home)
{
Intent returnIntent = new Intent();
returnIntent.putExtra("flag",userid);
setResult(Activity.RESULT_OK,returnIntent);
finish();
return true;
}}
UPDATED:
I am using this code to go to another fragment.
Fragment2 fragmentChild = new Fragment2 ();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.content, fragmentChild);
transaction.addToBackStack(null);
transaction.commit();
I have no problem in my backtrack when I go to another fragment. Then I'm using this code (getSupportActionBar().setDisplayHomeAsUpEnabled(true)) in my (Drawer.java) to show the back arrow. Now I want to add event when I clicked back arrow.
EDIT: (Drawer.java)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final View.OnClickListener originalToolbarListener = toggle.getToolbarNavigationClickListener();
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
toggle.setDrawerIndicatorEnabled(false);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().popBackStack();
}
});
} else {
toggle.setDrawerIndicatorEnabled(true);
toggle.setToolbarNavigationClickListener(originalToolbarListener);
}
}
});
If you properly setup the action bar, then you should be able to achive that with the following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Add the code to stop the task
break;
}
return super.onOptionsItemSelected(item);
}
EDIT: After you are able to handle the back button event, you can add the code to close the tasks in fragments. First of all, I created an interface that is implement by all fragments that should be able to close this tasks.
public interface TaskCancelFragment {
void cancelTask();
}
The implementation in fragments should look something like this:
#Override
public void cancelTask() {
//Add the code to cancel the task
Toast.makeText(getContext(), "The task is canceled", Toast.LENGTH_SHORT).show();
}
The final step is to send the event from activity to fragment. Here I will assume some things since I don't have access to your code to see how you add/find the fragments, but fortunately this doesn't matter so much and is easy to change. In addition to the initial answer, I created a new method in activity to find the current fragment and close the task.
private void cancelTasks() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.placeholder);
if (fragment instanceof TaskCancelFragment) {
((TaskCancelFragment) fragment).cancelTask();
}
}
And in the end, the case android.R.id.home looks like this:
case android.R.id.home:
cancelTasks();
onBackPressed(); // I think that you want to close the activity too
break;
I am trying to manually implement the actions that must take place when the up button on the actionbar is pressed but for some reason nothing happens when I press it.
here is my code:
public class ActivityOne extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_one);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = (Button)findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityTwo();
}
});
Button button2 = (Button)findViewById(R.id.btn2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityThree();
}
});
}
void openActivityTwo(){
Intent intent = new Intent(this, ActivityTwo.class);
startActivity(intent);
}
void openActivityThree(){
Intent intent = new Intent(this, ActivityThree.class);
startActivity(intent);
}
#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_activity_one, 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;
}
else if(id == R.id.homeAsUp){
Log.i("","Up is pressed");
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I understand that I have to explicitly assign a parent activity for the activity I want to implement up navigation on the manifest file, but problem is that this activity has multiple parents so I thought calling the finish() method when the up button is pressed on this activity will be the better approach.
I have already tried both id == R.id.home and id == R.id.homeAsUp and they both do not work. I do not know if it is because I am using AppCompactActivity or what Please help
Here is how you can implement this, try this code
use android.R.id.home instead of R.id.home or R.id.homeAsUp
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//use onBackPressed() OR finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The correct way to do it is to override public boolean onNavigateUp() just like overriding onBackPressed().
Using android studio 3.6.2 I've found that the Up button is not displayed by default in my apps, but it can be easily added..
Go to AndroidManifest.xml and update each activity that needs an Up button as follows:
<activity
android:name=".yourClassName"
android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourPackageName" />
</activity>
The target destination for the Up button is set by changing parentActivityName. In this example I have set it as '.MainActivity' but you can change that to whatever activity you want the user to navigate to.
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);
}
}