Android add icon in toolbar inside a fragment - android

I implement a toolbar and replace it with my actionbar according to my requirments. Now I want to add an icon in toolbar inside a fragment. I tried onCreateOptionMenu() and pass my menu xml to it. But it wont work. I also tried some other things and googling but nothing works so far. Does anybody have any idea about this. Here is my fragment code
public class Fragment_FavouriteLocations extends Fragment {
public Fragment_FavouriteLocations() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main_fav_location_row_item, container, false);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fav_location_menu, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.edit_button) {
Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
return true;
}
//
// if(id == R.id.action_search){
// Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
}
Here is my menu xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mayApp="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/edit_button"
mayApp:icon="#android:drawable/ic_menu_edit"
android:title="Edit"
mayApp:showAsAction="always" />
</menu>
Thanks in advance

In your Fragment, in the onCreateView() method, you have to add:
setHasOptionsMenu(true);
Otherwise the onCreateOptionsMenu() is never called.

you may need to use invalidateOptionsMenu() to tell the fragment to redraw the menu actions like this ...
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().invalidateOptionsMenu();
setHasOptionsMenu(true);
}

Related

onCreateOptionsMenu is never called (toolbar inflate)

My Fragment class:
Toolbar toolbar;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
toolbar = getView().findViewById(R.id.toolbar3);
toolbar.inflateMenu(R.menu.menufragmentmain);
setHasOptionsMenu(true); //i also tried putting this function in oncreate function
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Toast.makeText(getActivity(), "i never enter this function also" , Toast.LENGTH_LONG).show();
super.onCreateOptionsMenu(menu,inflater);
inflater.inflate(R.menu.menufragmentmain, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(getActivity(), "i never enter this function" , Toast.LENGTH_LONG).show();
//some switch cases.....
return super.onOptionsItemSelected(item);
}
I've got a stupid error which I cant find unfourtantly. I've got a simple toolbar for my fragment. In onViewCreated I inflate my actionbar menu with my toolbar.
The issue is that the functions onCreateOptionsMenu and 'onOptionsItemSelected' are never called. I've got no clue why.
Things i checked in other similar questions with the same issue:
I checked if my main activity has a onCreateOptionsMenu or'onOptionsItemSelected'. It doesn*t
Checked if my style class has NOT: android:theme="#android:style/Theme.Black.NoTitleBar
None of the points unfourtantly work. What did I miss. Do I need to check something else?
As per the Fragment-owned app bar guide which explains how to use a Fragment-owned Toolbar, you do not use any of the setHasOptionsMenu(), onCreateOptionsMenu(), or onOptionsItemSelected() APIs - those are only used for activity owned app bars.
Instead, you would follow the guide for handling menu click events by using the Toolbar APIs:
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
toolbar = getView().findViewById(R.id.toolbar3);
toolbar.inflateMenu(R.menu.menufragmentmain);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getActivity(), "onMenuItemClick called" , Toast.LENGTH_LONG).show();
//some switch cases.....
return true;
}
});
}
Set up the toolbar in the host Activity. Then override the menu handling in each Fragment wherever necessary.
Here's some generic scaffolding (with comments):
public class MyFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Report that this Fragment has an options menu
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
// Inflate then menu, and THEN call super()
// Note the order of the invocations
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
// Handle menu item selections
final int itemId = item.getItemId();
switch(itemId) {
case R.id.my_menu_option_x: ...; return true;
case R.id.my_menu_option_y: ...; return true;
case R.id.my_menu_option_z: ...; return true;
default: return super.onOptionsItemSelected(item);
}
}
}

Inflating only a specific action bar menu

I have an action bar menu defined in my main activity. Now, one of the fragments I am using in that activity has its own action bar menu but when I click on the menu option, I get both the fragment's as well as the activity's menu items. How to ensure that only that fragment's menu item is displayed?
My java code for that fragment is:
public class ProfileD extends Fragment {
TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;
public ProfileD() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);
tv_named = (TextView)rootView.findViewById(R.id.tv_named);
tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);
tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);
imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}
#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.edit_profile) {
Intent intent = new Intent(getContext(),PersonalDetails.class);
intent.putExtra("Edit",1);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
ActionBar actionBar = appCompatActivity.getSupportActionBar();
actionBar.setTitle("Profile");
}
}
The xml file for the menu is:
<?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/edit_profile"
android:orderInCategory="100"
android:title="Edit"
app:showAsAction="never" />
</menu>
I found a solution to my problem. I am posting it here so if anyone else is facing the same issue, they can benefit from this:
I created a static menu object and stored the activity's action bar menu in that object. I then called that object from my fragment and cleared it thereby clearing the activity's menu and leaving me with the fragment's menu
Here is the updated java code for the fragment
public class ProfileD extends Fragment {
TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;
public ProfileD() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);
tv_named = (TextView)rootView.findViewById(R.id.tv_named);
tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);
tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);
imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
HomePage.menu_home.clear();
getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}
#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.edit_profile) {
Intent intent = new Intent(getContext(),PersonalDetails.class);
intent.putExtra("Edit",1);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
ActionBar actionBar = appCompatActivity.getSupportActionBar();
actionBar.setTitle("Profile");
}
}

How to make visible a layout programatically in fragment which is called in parent activity

I have a layout defined in fragment.xml which is called in activity....
and I want to make it visible when a button in parent activity action bar is pressed which is in onOptionsItemSelected() .when i do this it make a error of null object reference....
fragment.xml
<RelativeLayout
android:visibility="invisible"
android:id="#+id/relative_layout_current_job"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_view_current_job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_current_job"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passenger_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.passenger_main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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_job_confirm) {
Button b = (Button) findViewById(R.id.action_job_confirm);
RelativeLayout layoutCurrentJob = (RelativeLayout) findViewById(R.id.relative_layout_current_job);
TextView status = (TextView) findViewById(R.id.text_view_current_job_status_in_history);
if((b.getText().toString()) == "job confirm") {
status.setVisibility(View.INVISIBLE);
b.setText("Job Started");
layoutCurrentJob.setVisibility(View.VISIBLE);
} else {
status.setVisibility(View.VISIBLE);
b.setText("jon confirm");
layoutCurrentJob.setVisibility(View.INVISIBLE);
}
}
return super.onOptionsItemSelected(item);
}
mainmenu.xml
<item
android:id="#+id/action_job_confirm"
android:title="job confirm"
app:showAsAction="never"/>
Screenshot
On your code, Intializing
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
is wrong. Because the RelativeLayout you want to hide/show is part of your Fragment .you cannot initialized RelativeLayout by this.
It should be like as shown in below on your Fragment's onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
}`
You can access widgets of your Fragment by below method
RelativeLayout layoutCurrentJob = (RelativeLayout )fragmentobj.getView().findViewById(R.id.img_one));
layoutCurrentJob.setVisibility(View.VISIBLE);
Do it for your fragment like this:
public class testFragment extends Fragment implements Handler.Callback{
public final Handler handler = new Handler(testFragment.this);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
}
#Override
public boolean handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 1) {
//do your job here
}
return false;
}
}
Call it from your activity like this:
testFragment frag = (testFragment) getFragmentManager()
.findFragmentByTag("Fragment_1");
Message ms = Message.obtain(frag.handler,1);
frag.handler.sendMessage(ms);

toolbar menu item click in fragments

I know this question has been asked and but I am unable to solve my problem after looking at those answer. I have an Activity with a Fragment.
In fragment, I have added the toolbar and I want to handle toolbar menu item click events from the fragments.
In menu, I have added a single share button. I am getting the click event callback for the Up navigation (arrow home button) but I am not getting click event callback for the share button in my fragment.
Can some points me at what I am doing wrong here.
menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.rahul.haridasasampada.details.DescriptionActivity">
<item
android:id="#+id/action_share"
android:title="Share"
android:orderInCategory="100"
app:showAsAction="always"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>
</menu>
I have added toolbar to the fragment layout.
My Activity's code -
public class DescriptionActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_description);
if (savedInstanceState == null) {
Article articleExtra = (Article) getIntent().getParcelableExtra(DescriptionFragment.ARGS_EXTRA);
DescriptionFragment descriptionFragment = DescriptionFragment.newInstance(articleExtra);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, descriptionFragment)
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
getSupportActionBar().setTitle(R.string.app_name_in_kannada);
}
#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_description, menu);
Log.d("debug", "activity : onCreateOptionsMenu");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Log.d("debug","activity: action home has clicked");
onBackPressed();
return false;
case R.id.action_share:
Log.d("debug","activity: action share has clicked");
return false;
}
return super.onOptionsItemSelected(item);
}
}
My Fragments code -
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// some code
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBarActivity actionBarActivity = (ActionBarActivity) getActivity();
Toolbar toolbar = (Toolbar) getView().findViewById(R.id.toolbar_actionbar);
actionBarActivity.setSupportActionBar(toolbar);
toolbar.setOnMenuItemClickListener(this);
toolbar.inflateMenu(R.menu.menu_description);
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_share:
if (menuItem.getItemId() == R.id.action_share)
Log.d("debug","action share has clicked");
return true;
}
return false;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
Log.d("debug", "fragment : onCreateOptionsMenu");
MenuItem shareMenuItem = menu.findItem(R.id.action_share);
mShareActionProvider =(ShareActionProvider)MenuItemCompat.getActionProvider(shareMenuItem);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Log.d("debug","fragment : action home has clicked");
return true;
case R.id.action_share:
Log.d("debug","fragment: action share has clicked");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View detailFragmentView = inflater.inflate(R.layout.fragment_description, null);
return detailFragmentView;
}
From Android Docs, for Fragment:
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater)
Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu. For this method to be called, you must have first called setHasOptionsMenu(boolean).
so you want to control actionbar menu in Fragment, then you have to call setHasOptionsMenu method better in Fragment's onCreate(...):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
also important is that you should not use inflateMenu and onCreateOptionsMenu both together for same ToolBar, inflateMenu is for standalone without setting ToolBar as ActionBar.
Suggestion:
keep one ToolBar in Activity as ActionBar for your App, and another ToolBar standalone inside Fragment.
Hope this help!
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MyFragment extends Fragment implements Toolbar.OnMenuItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
Toolbar toolbar= (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(this);
return rootView;
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_menu:
//do sth here
return true;
}
return false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.training1_fragment, container,
false);
setHasOptionMenu(true);
return v;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save :
{
//Write here what to do you on click
return true;
}
}
return super.onOptionsItemSelected(item);
}
You should getPointer toolbar from your activity class and inflate menu in fragment class.
You can look this ex:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
activity = ((DescriptionActivity ) getActivity());
Toolbar tollbar=getView.findViewById(R.id.your_toolbar);
activity.setSupportActionBar(toolbar);
activity.toolbar.inflateMenu(R.menu.menu_search);
activity.toolbar.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_search:
break;
}
return false;
}
Please refer this for click of the Fragment optionMenu click link.

path.reset with menu item onclick

I'm making an paint application just to learn how to work with eclipse.
I would like to clear my (paint)view whenever I click the menu item 'Reset'
The menu item 'Reset' is in the XML file. Now i know i have to use path.reset but don't know how where to write it. Hope someone is able to help me out.
<item android:id="#+id/ResetAction"
android:orderInCategory="100"
android:title="Reset"
android:showAsAction="never"
android:menuCategory="container"
></item>
a
public class SingleTouchActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SingleTouchEventView(this, null));
}
#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) {
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container,
false);
return rootView;
}
}
}
Path.reset() is a method used to reuse a Path object.
For example, if you use a Path object to draw a shape that changes at each frame, at the beginning of the frame drawing (in the draw(Canvas) or onDraw(Canvas) methods) you can reset reset the path, add the new shape to the path and then draw the Path (canvas.drawPath())

Categories

Resources