I have a frame where I put different fragments in. Some has actionbar displayed, some does not. But the one given below does not display action bar as any other.
public class AFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_a, container, false);
ButterKnife.bind(this, view);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_a, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_a) {
//getFragmentManager().popBackStackImmediate();
}
return super.onOptionsItemSelected(item);
}
}
This fragment is called from previous fragment like
AFragment aFragment = new AFragment ();
getFragmentManager().beginTransaction()
.replace(R.id.fragment, aFragment , "fragment_a")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
By the way, I do not show action bar in the previous fragment.
In case it is needed, styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppActionBar" parent="AppTheme">
<item name="android:windowActionBarOverlay">true</item>
<item name="windowActionBarOverlay">true</item>
</style>
For fragments you have to make sure that the setHasOptionsMenu() is set in the onCreate() method and now the onCreateView() method.
Then be sure to set the toolbar(if added in the fragment layout) as the toolbar for the activity.
public class AFragment extends Fragment {
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_a, container, false);
ButterKnife.bind(this, view);
//moved to onCreate() method
//setHasOptionsMenu(true);
//set toolbar as the default for the activity class if AppCompat
((AppCompatActivity) getActivity()).setSupportActionBar(/*your toolbar goes here*/);
//set toolbar is activity class is not AppCompat
getActivity().setActionBar(/*your toolbar goes here*/);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_a, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_a) {
//getFragmentManager().popBackStackImmediate();
}
return super.onOptionsItemSelected(item);
}
}
Related
Setting activity:
This is setting Activity and it includes Preference Category.
When I click folder option, then it goes to Preference Fragment.
Preference fragment:
As you can see, status bar color changed from WHITE.
But I have to keep WHITE color.
public class SettingsFragment extends PreferenceFragment
implements OnPreferenceClickListener, OnPreferenceChangeListener {
private SecurityHelper securityHelper;
private Preference preference;
public SettingsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(R.color.primaryColor));
int nightModeFlags = DocumentsApplication.getInstance().getBaseContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if(nightModeFlags == Configuration.UI_MODE_NIGHT_YES)
getActivity().getWindow().setStatusBarColor(Color.BLACK);
else if(nightModeFlags == Configuration.UI_MODE_NIGHT_NO)
getActivity().getWindow().setStatusBarColor(Color.WHITE);
return super.onCreateView(inflater, container, savedInstanceState);
}
I tried this, but not success, How can I fix status bar Color?
You can define style for the whole application for both lite and night mode.
<style name="AppTheme" parent="AppTheme.Base">
<item name="android:textColorHint">#color/white</item>
<item name="android:statusBarColor">#color/white</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
</style>
I am a beginner Android developer and I have been struggling the issue that I can't see the toolbar in any activity that inherits Base Activity. According to other resource, to use the same toolbar in the different activities. I have to implement it in Base Activity and inherit it where I need to use it. Could anyone help me figure out the problem?
styles.xml
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<style name="AppTheme" parent="AppBaseTheme">
</style>
</resources>
quiz.menu.xml inside of menu folder
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/contact"
android:icon="#drawable/ic_contacts_black_24dp"
android:title="Contact"
app:showAsAction="ifRoom" />
<item android:id="#+id/language"
android:title="Language"
app:showAsAction="never" />
<item android:id="#+id/speech"
android:title="Speech"
app:showAsAction="never">
<munu>
<item android:id="#+id/subitem1"
android:title="Sub Item 1"/>
<item android:id="#+id/subitem2"
android:title="Sub Item 2"/>
</munu>
</item>
</menu>
BaseActivity
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.quiz_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.contact:
Toast.makeText(this, "Contact is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.language:
Toast.makeText(this, "Language is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.speech:
Toast.makeText(this, "Speech is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.subitem1:
Toast.makeText(this, "Language is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.subitem2:
Toast.makeText(this, "Speech is selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
WelcomeActivity (inherits base Activity)
public class WelcomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
final Button databaseButton = findViewById(R.id.database);
databaseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
Intent databaseIntent = new Intent(WelcomeActivity.this, Questionnaire.class);
startActivity(databaseIntent);
}
});
}
Questionnaire
public class Questionnaire extends BaseActivity {
public Spinner languageSpinner;
public int languageId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questionnaire);
...
}
}
The answer is actually simple. You firstly set contentview in OnCreate() method of the BaseActivity class, then you change the view to another xml file in OnCreate() methods of the child classes.
What I suggest is that you do not implement OnCreate() method in BaseActivity class but implement SetContentView() method in BaseActivity.
In short, delete onCreate() method from BaseActivity() and add setContentView() method in the below.
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
P.S - Your quiz_menu.xml file does not look like a menu file. :)
P.P.S - Let me know if it works, or if you have troubles. :)
This is my Starting Activity. It is working fine programmatically.
The only problem which I'm facing is that the OverFlow-Menu comes is dark theme when called by the Hardware Menu key.
I've provided all the essential lines of code in this sample.
public class StartingActivity extends AppCompatActivity implements LoginActivity_Tab.loginActivityTab_interface {
private static final String LOGIN_URL = "http://rollhack.96.lt/login.php";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting);
includeWidgets();
}
private void includeWidgets() {
///// Tab Layout /////
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
///// ToolBar /////
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Note Pad");
}
///// This method is called for Exiting the App /////
public void exitApp() {
final AlertDialog.Builder exit = new AlertDialog.Builder(StartingActivity.this);
exit.setTitle("Exit Application")
.setMessage("Are you sure you want to Exit the application?")
.setCancelable(true)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
StartingActivity.this.finishAffinity();
}
})
.setNegativeButton(android.R.string.no, null);
exit.create().show();
}
///// This method is called to assign the Key Events /////
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
exitApp();
return true;
}
return super.onKeyUp(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_starting_activity, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
return Boolean.parseBoolean(null);
case (R.id.menu_about):
return Boolean.parseBoolean(null);
case (R.id.menu_exit):
exitApp();
return true;
}
return super.onOptionsItemSelected(item);
}
This is how it looks when it is called by the overflow menu icon of the ActionBar
This is how my App OverFlow-Menu looks when Hardware Menu key is pressed
Overflow menu by Icon
You can change the color of the overflow menu background by adding a new style in style.xml.
<style name="OverflowMenu"
parent="#android:style/Theme.Holo">
<item name="android:popupMenuStyle">#style/MyOverflowMenu</item>
<item name="android:itemTextAppearance">#style/TextAppearance</item>
</style>
<style name="MyOverflowMenu"
parent="#android:style/Widget.Holo.ListPopupWindow">
<item name="android:popupBackground">#color/your_color</item>
</style>
<style name="TextAppearance">
<item name="android:textColor">#color/your_color</item>
</style>
Overflow Menu by Hardware Key
To change the color of Overflow menu called by Hardware key, add another style.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="actionBarPopupTheme">#style/OverflowMenuHardware</item>
</style>
<style name="OverflowMenuHardware" parent="ThemeOverlay.AppCompat.Dark">
<item name="android:textColorSecondary">#color/your_color</item>
<item name="android:colorBackground">#color/your_color</item>
</style>
Implement either one of these to change the color of Overflow menu of either the one called by icon(former code) or by hardware key(latter code).
I created an App that uses Fragment. From my MainActivity I set the ActionBar.
But in one of my Fragment I need to modify the action icons and on click.
So With the code below, when I load the my Fragment, it still display the action bar menu from MainActivity
here is my MainActivity :
public void restoreActionBar() {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
// enable ActionBar app icon to behave as action to toggle nav drawer
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
#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.main, menu);
//Handle the Search Menu
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setQueryHint(this.getString(R.string.action_search));
((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text))
.setHintTextColor(getResources().getColor(R.color.white));
searchView.setOnQueryTextListener(OnQuerySearchView);
mSearchCheck = false;
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}//end onCreateOptionsMenu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
/** CAMERA **/
case R.id.action_camera:
//openCamera();
Utils.makeToast(getApplicationContext(), "Implement Camera", false);
return true;
/** SEARCH **/
case R.id.action_search:
//openSearch();
mSearchCheck = true;
Utils.makeToast(getApplicationContext(), "Implement Search", false);
return true;
/** SETTINGS **/
case R.id.action_settings:
//openSettings();
Utils.makeToast(getApplicationContext(), "Implement Settings", false);
return true;
/** ABOUT **/
case R.id.action_help:
//openHelp();
Utils.makeToast(getApplicationContext(), "Implement Help", false);
return true;
default:
return super.onOptionsItemSelected(item);
}//end switch
}//end onOptionsItemSelected
private OnQueryTextListener OnQuerySearchView = new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String arg0) {
// TODO Auto-generated method stub
if (mSearchCheck){
// implement your search here
}
return false;
}
};//end OnQueryTextListener
Here is the layout :
<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.example.sellbeesclean.MainActivity" >
<!-- CAMERA -->
<item
android:id="#+id/action_camera"
android:orderInCategory="100"
android:icon="#drawable/ic_action_camera"
android:title="#string/action_camera"
app:showAsAction="ifRoom|collapseActionView"/>
<!-- SEARCH -->
<item
android:id="#+id/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/>
<!-- SETTINGS -->
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"/>
<!-- HELP -->
<item
android:id="#+id/action_help"
android:orderInCategory="100"
android:icon="#drawable/ic_action_help"
android:title="#string/action_help"
app:showAsAction="ifRoom|collapseActionView"/> </menu>
Her is my Fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.user_profile_fragment, container, false);
Log.i(TAG, "onCreateView");
.....
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
/** EDIT **/
case R.id.action_edit:
//openEditProfile(); //Open Edit Profile Fragment
Utils.makeToast(MyApplication.getAppContext(), "Implement Camera", false);
return true;
default:
return super.onOptionsItemSelected(item);
}//end switch
}//end onOptionsItemSelected
here the fragment menu layout
<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.example.sellbeesclean.MainActivity" >
<!-- EDIT -->
<item
android:id="#+id/action_edit"
android:orderInCategory="100"
android:icon="#drawable/ic_action_edit"
android:title="#string/action_edit_profile"
app:showAsAction="ifRoom|collapseActionView"/></menu>
In your fragment's onCreateView method write
setHasOptionsMenu(true);
And inflate your menu xml file in onCreateOptionsMenu method
In onCreateOptionsMenu of a fragment, write
menu.clear();
before inflating menus
I am trying to create a New button (icon only) next to the 3 dots button in the ActionBar. This is the code I tried, but it adds it as child of the 3 dots button.
main_activity_actions.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/create_game"
android:menuCategory="container"
android:orderInCategory="1"
android:title="#string/new_game"
android:titleCondensed="nieuw spel">
</item>
</menu>
MainActivity.java:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return true;
}
Also, how can I find out what default icons I can use?
To show icons in the action bar, you can add the line android:showAsAction="always" to your XML item. Still Android would show it only if it judges there is adequate space in the action bar. If you strictly always want to show your button, you can define and set a custom layout for your action bar.
You can download the default icon set for action bar from https://developer.android.com/design/downloads/index.html
try it
/res/menu/activity_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_settings"
android:showAsAction="never"
android:title="#string/menu_settings"/>
<item
android:id="#+id/menu_save"
android:showAsAction="ifRoom"
android:icon="#android:drawable/ic_menu_save"
android:title="#string/menu_guardar"/>
<item
android:id="#+id/menu_new"
android:showAsAction="ifRoom|withText"
android:icon="#android:drawable/ic_menu_add"
android:title="#string/menu_nuevo"/>
</menu>
MainActivit.class
public class MainActivity extends Activity {
//...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
//onClic item
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_new:
Log.i("ActionBar", "Nuevo!");
return true;
case R.id.menu_save:
Log.i("ActionBar", "Guardar!");;
return true;
case R.id.menu_settings:
Log.i("ActionBar", "Settings!");;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And you can download All IconPack here:
https://developer.android.com/design/downloads/index.html
Yes, you can inflate a custom actionbar for adding buttons with images like this:
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) getActionBar()
.getThemedContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View customActionBarView = inflater.inflate(R.layout.actionbar_custom, null);
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setCustomView(customActionBarView,
new ActionBar.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(R.layout.activity_main);
}
Where _actionbar_custom.xml_ would be your layout resource, usually a LinearLayout with whatever components you want.