I want to make my Searchview to be visible only when I open product option from the drawer, to do that I am trying using onOptionsItemSelected method to listen which options is being used.
The problem is I am always get a NullPointerException everytime I tried to get my SearchView id from onOptionsItemSelected.
I knew how to hide the SearchView in onCreateOptionsMenu using :
menu.findItem(R.id.action_search).setVisible(false);
This is the source code for my onCreateOptionsMenu :
#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);
View lay = findViewById(R.id.nav_header);
//id in this line is found
menu.findItem(R.id.action_search).setVisible(false);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, null);
username = sharedpreferences.getString(TAG_USERNAME, null);
name = sharedpreferences.getString(TAG_NAME, null);
txt_id = lay.findViewById(R.id.txt_id_admin);
txt_username = lay.findViewById(R.id.txt_textView);
txt_name = lay.findViewById(R.id.txt_name_admin);
imb = lay.findViewById(R.id.btn_exit);
txt_id.setText("ID : " + id);
txt_name.setText("Nama : " + name);
txt_username.setText("Status : " + username);
imb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
intent = new Intent(getApplicationContext(), Login.class);
finish();
startActivity(intent);
}
});
return true;
But I can't do the same thing in onOptionsItemSelected method, because the argument it used was MenuItem instead of Menu.
This is my latest try for the onOptionsItemSelected method :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
NavigationView navigationView = findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
//id in this line is null
MenuItem item_search = menu.findItem(R.id.action_search);
Log.d(TAG, "Response : " + item_search);
SearchView searchView = (SearchView) item_search.getActionView();
if (item.getItemId() == R.id.nav_produk) {
searchView.setVisibility(View.VISIBLE);
return true;
} else {
Log.d(TAG, "Response : " + searchView);
searchView.setVisibility(View.INVISIBLE);
return super.onOptionsItemSelected(item);
}
}
And this is my res/menu/main.xml file :
<?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_settings"
android:visible="false"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"/>
<item
android:id="#+id/action_search"
android:visible="true"
android:orderInCategory="100"
android:icon="#android:drawable/ic_menu_search"
android:title="#string/search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/>
I laready found answer! Apparently I don't need onOptionsItemSelected at all.
I am using NavController on my DrawerLayout, so the easier way to make a listener is using onDestinationChanged method inside onCreateOptionsMenu
This is the result :
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
View lay = findViewById(R.id.nav_header);
menu.findItem(R.id.action_search).setVisible(false);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, null);
username = sharedpreferences.getString(TAG_USERNAME, null);
name = sharedpreferences.getString(TAG_NAME, null);
txt_id = lay.findViewById(R.id.txt_id_admin);
txt_username = lay.findViewById(R.id.txt_textView);
txt_name = lay.findViewById(R.id.txt_name_admin);
imb = lay.findViewById(R.id.btn_exit);
txt_id.setText("ID : " + id);
txt_name.setText("Nama : " + name);
txt_username.setText("Status : " + username);
imb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
intent = new Intent(getApplicationContext(), Login.class);
finish();
startActivity(intent);
}
});
//Only show SearchView when produk is open
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
if (destination.getId() == R.id.nav_produk) {
menu.findItem(R.id.action_search).setVisible(true);
} else {
menu.findItem(R.id.action_search).setVisible(false);
}
}
});
return true;
}
Related
I'm trying to make the "sign out" item take me back to the Login window. I did a lot of searching and watching videos but nothing worked for me.
Here's my built-in navigation drawer code.
The code I typed starts from line 46 to line 56, most codes are just built-in.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityHomepageBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarHomepage.toolbar);
binding.appBarHomepage.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 = binding.drawerLayout;
NavigationView navigationView = binding.navView;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id=menuItem.getItemId();
if (id == R.id.nav_Sign_out){
Intent intent = new Intent(Homepage.this, Login.class);
startActivity(intent);
}
return true;
}
});
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_dashboard, R.id.nav_profile, R.id.nav_orders, R.id.nav_recent_orders,
R.id.nav_pending_deliveries, R.id.nav_cancelled_orders, R.id.nav_settings)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homepage, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Login.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
textview = (TextView) findViewById(R.id.textViewSignUp);
textview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login.this,Register.class);
startActivity(intent);
}
});
button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Login.this,Homepage.class);
startActivity(intent);
}
});
}
}
It doesn't have an error but it doesn't work.
Here's the activity_main_drawer.xml where I put the items.
<group
android:id="#+id/menu_top"
android:checkableBehavior="none">
<item
android:id="#+id/nav_dashboard"
android:icon="#drawable/ic_baseline_dashboard_24"
android:title="#string/dashboard">
</item>
<item
android:id="#+id/nav_profile"
android:icon="#drawable/ic_baseline_person_24"
android:title="#string/profile" >
</item>
</group>
<item
android:id="#+id/nav_orders"
android:title="#string/orders" >
<menu>
<item
android:id="#+id/nav_menu_orders"
android:title="#string/Orders"
android:icon="#drawable/ic_orders" />
<item
android:id="#+id/nav_recent_orders"
android:title="#string/recent_orders"
android:icon="#drawable/ic_recent" />
</menu>
</item>
<item
android:id="#+id/nav_deliveries"
android:title="#string/deliveries" >
<menu>
<item
android:id="#+id/nav_pending_deliveries"
android:title="#string/pending_deliveries"
android:icon="#drawable/ic_pending_deliveries"/>
<item
android:id="#+id/nav_recent_deliveries"
android:title="#string/recent_deliveries"
android:icon="#drawable/ic_recent" />
</menu>
</item>
<item
android:id="#+id/nav_cancelled_orders"
android:icon="#drawable/ic_baseline_cancel_24"
android:title="#string/cancelled_orders" >
</item>
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_baseline_settings_24"
android:title="#string/settings" >
</item>
<group
android:id="#+id/nav_menu_bottom"
android:checkableBehavior="none">
<item
android:id="#+id/nav_Sign_out"
android:icon="#drawable/ic_sign_out"
android:title="#string/sign_out">
</item>
</group>
Try this -
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = ActivityHomepageBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarHomepage.toolbar);
binding.appBarHomepage.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 = binding.drawerLayout;
NavigationView navigationView = binding.navView;
navigationView.setNavigationItemSelectedListener(this);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_dashboard, R.id.nav_profile, R.id.nav_orders, R.id.nav_recent_orders,
R.id.nav_pending_deliveries, R.id.nav_cancelled_orders, R.id.nav_settings)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homepage, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id=menuItem.getItemId();
if (id == R.id.nav_Sign_out){
Intent intent = new Intent(Homepage.this, Login.class);
startActivity(intent);
}
return true;
}
}
I can give link via Button.But I want to add a App store link to "rateus" in menu item.(please see attached image)here is the button code in MainActivity.java.This is not working for menu item.please help me.
//rateus button
android.widget.Button ratebutton = (android.widget.Button) findViewById(R.id.id_rateus);
ratebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
android.net.Uri.parse("market://play.google.com/store/apps/details?id=com.slsindupotha&hl=en")));
}catch (android.content.ActivityNotFoundException e){
startActivity(new Intent(Intent.ACTION_VIEW,
android.net.Uri.parse("https://play.google.com/store/apps/details?id=com.slsindupotha&hl=en")));
}
}
});
//end rateus button code
here is my menu item image...
rate us ite menu
here is the code for rate us item
<item
android:id="#+id/id_rateus"
android:orderInCategory="100"
android:title="#string/action_rateus"
android:textAllCaps="false"
app:showAsAction="ifRoom" />
You need to override the menu functions, something like the code below.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds appModels to the action bar if it is present.
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.share:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBodyText = "Check it out. Your message goes here";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Subject here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(sharingIntent, "Shearing Option"));
return true;
case R.id.id_rateus:
try {
startActivity(new Intent(Intent.ACTION_VIEW,
android.net.Uri.parse("market://play.google.com/store/apps/details?id=com.slsindupotha&hl=en")));
}catch (android.content.ActivityNotFoundException e){
startActivity(new Intent(Intent.ACTION_VIEW,
android.net.Uri.parse("https://play.google.com/store/apps/details?id=com.slsindupotha&hl=en")));
}
return true;
}
return super.onOptionsItemSelected(item);
}
This is how you can handle a menu item click
Inflate the menu file
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file, menu);
return true;
}
Then handle onCLick here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.id_rateus:
//handle onclick event for intent to playstore
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I'm new to android trying to create a popup menu, but my app is crashing when I'm calling createMenu() in my activity which is extending to AppCompatActivity can anybody help me about the issue?
#SuppressLint("RestrictedApi")
public void createMenu() {
MenuBuilder menuBuilder = new MenuBuilder(this);
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.popup_menu, menuBuilder);
MenuPopupHelper optionsMenu = new MenuPopupHelper(this, menuBuilder);
optionsMenu.setForceShowIcon(true);
menuBuilder.setCallback(new MenuBuilder.Callback() {
#Override
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
return true;
default:
return false;
}
}
#Override
public void onMenuModeChange(MenuBuilder menu) {
}
});
optionsMenu.show();
}
In my XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/one"
android:icon="#drawable/ic_one"
android:title="One"
android:orderInCategory="0"/>
</menu>
calling it
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.option) {
createMenu();
}
}
getting error
java.lang.IllegalStateException: MenuPopupHelper cannot be used without an anchor
Add this to menu file android:showAsAction="always"
Use this menu file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/one"
android:icon="#drawable/ic_one"
android:title="One"
android:showAsAction="always"
android:orderInCategory="0"/>
The issue is the null action view. So showing the menuitem as action view solves the issue
And call this using this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.option) {
createMenu(item.getActionView());
}
}
And change your createMenu() to
#SuppressLint("RestrictedApi")
public void createMenu(View v) {
PopupMenu popup = new PopupMenu(getActivity(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_menu, popup.getMenu());
popup.show();
}
EDIT Added MyActivity.java (i.e., main activity) at bottom
EDIT2 Added lines to MyActivity.java (this solved the problem)
I have preferences set up but have no way to access them. No matter what style I pick in xml and no matter what virtual device or style I pick in Android Studio (AS) 1.1.0, the screen lacks the 3 dots shown below. Not even the pulldown styles that include LightActionBar and DarkActionBar show the dots.
In xml, I've tried <style name="AppBaseTheme" parent="android:Holo.ButtonBar">, which finally worked last night (was having same problem) on a small app, and also, for parent, I tried Base.Theme.AppCompat.Light.DarkActionBar and other things.
I don't so much care if I see the 3 dots; just ANYTHING to expose the preferences screen.
I've also tried never, ifroom, and always for showAsAction:
<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=".MyActivity">
<item android:id="#+id/itemFocus"
android:title="#string/focusAtClue"
android:orderInCategory="200"
app:showAsAction="never"/>
Here's preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
>
<CheckBoxPreference
android:key="#string/focusAfterShow"
android:title="#string/focusAfterShow"
android:summary="Always place the cursor at the 'clue' (sum) after tapping 'Show'."
android:defaultValue="true"
/>
</PreferenceCategory>
<PreferenceCategory
>
<CheckBoxPreference
android:key="#string/screenSaver"
android:title="#string/screenSaver"
android:summary="Keep screen on at all times while running this app."
android:defaultValue="true"
/>
</PreferenceCategory>
</PreferenceScreen>
Here's SettingsFragment.java:
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (key.equalsIgnoreCase("pie_type")){
Log.w("Settings", sharedPref.getString(key, ""));
}
}
}
And SettingsActivity.java:
import android.app.Activity;
import android.os.Bundle;
public class SettingsActivity extends Activity {
public static final String SETTINGS = "com.whatever.kakurocombosbuildvariants.settings";
public static final String FIRST_USE = "com.whateverkakurocombosbuildvariants.firstUse";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
Here's where SettingsActivity is invoked in MyActivity.java:
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
MyActivity.java (main activity; 300 LINES OF EXTRANEOUS CODE DELETED)
public class MyActivity extends Activity {
public final String
prefix = "com.XXXX.kakurocombosbuildvariants"
, SETTINGS = prefix + ".settings"
, FIRST_USE = prefix + ".firstUse"
, FOCUS_AT_CLUE = prefix + ".focusAtClue"
, SCREENSAVER = prefix + ".screensaver"
, literally_Focus_At_Clue = "Focus at clue"
, literally_Screen_saver = "Screen saver"
;
public boolean firstUse;
SharedPreferences preferences;
SharedPreferences.Editor editor;
boolean screenSaver;//= false;
boolean focusAtClue ;//= true;
AlertDialog alertDialog;
private void makeActionOverflowMenuShown() {
//devices with hardware menu button (e.g. Samsung Note) don't show action overflow menu
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
popupMessage("Problem making actionbar overflow");
}
}
void showKeypad(){
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
public static boolean isTablet(Context ctx){
return (ctx.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK
)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
#Override public boolean onPrepareOptionsMenu(Menu menu)
{
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setScreensaver()
{
if( ! screenSaver) getWindow().addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override protected void
onCreate(Bundle savedInstanceState) // ************************** ON CREATE **********
{
super.onCreate(savedInstanceState);
/////////////////////////// EDIT2 ///////////////////////////////////////
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getWindow().setFormat(Window.FEATURE_ACTION_BAR);
/////////////////////////// EDIT2 ///////////////////////////////////////
if(! FREE) setContentView(R.layout.activity_my);
else setContentView(R.layout.activity_free);
SharedPreferences preferences = getSharedPreferences(SETTINGS, MODE_PRIVATE);
firstUse = preferences.getBoolean(FIRST_USE, true);
if(firstUse){
Toast.makeText(getApplicationContext(), "Welcome to Kakuro Combos", Toast.LENGTH_SHORT).show();
editor = preferences.edit();
editor.putBoolean(FIRST_USE, false);
editor.commit();
}
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() { public void
onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}});
showKeypad();
makeActionOverflowMenuShown();
getWindow().setFormat(Window.FEATURE_ACTION_BAR);
showKeypad();
setScreensaver();
} // onCreate
}
/////////////////////// EDIT2 ////////////////////////////
#Override public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/////////////////////// EDIT2 ////////////////////////////
It looks like main issue is that you're not inflating your menu xml.
Try using ActionBarActivity for your MainActivity, and add onCreateOptionsMenu() in order to inflate the menu xml.
public class MyActivity extends ActionBarActivity{
//...........
#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;
}
//............
}
You need to load the menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.<your_menu>, menu);
//...
}
When I access the PreferenceScreen, I notice that my custom switch is off. Then I turn it on and restart the app. I went back to the PreferenceScreen and the switch went back off. This doesn't happen when I use the default SwitchPreference. I am able to customize the SwitchPreference the way I want it to be, so the only problem is the switch value not saving. I have four files related to a customize SwitchPreference and all of the Preferences are placed in an extension of a PreferenceFragment
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings"
>
<com.example.CustomSwitchPreference
android:key="vibration"
android:title="vibration"
android:summary=""
android:defaultValue="true" />
</PreferenceScreen>
CustomSwitchPreference.java:
public class CustomSwitchPreference extends SwitchPreference {
public CustomSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSwitchPreference(Context context) {
super(context);
}
#Override
protected View onCreateView( ViewGroup parent )
{
LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
return li.inflate( R.layout.customswitch_preference, parent, false);
}
/*
#Override
protected void onBindView(View view) {
MainActivity mainActivity = (MainActivity)getContext();
RelativeLayout relativeLayout = (RelativeLayout)mainActivity.findViewById(R.id.switch_frame);
Switch s = (Switch)relativeLayout.getChildAt(1);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
persistBoolean(isChecked);
}
});
super.onBindView(view);
}
*/
}
customswitch_preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/switch_title"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_alignParentStart="true"/>
<Switch
android:id="#+id/switch_pref"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private ActionBar actionBar;
private boolean mInit = false;
private boolean showIcon = true;
private Menu m;
private GridFragment gridFragment;
private SettingsFragment settingsFragment;
public ImageButton startButton;
public TextView gameTimer;
public TextView mineCount;
public boolean isVibrating;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsFragment = new SettingsFragment();
actionBar = getActionBar();
actionBar.setTitle("Settings");
actionBar.setCustomView(R.layout.actionbar);
//actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView();
startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight);
startButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
startButton.setImageResource(R.drawable.smiley2);
break;
case MotionEvent.ACTION_UP:
restartGame();
break;
}
return false;
}
});
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf");
TextView textView;
int[] resources =
{R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
for(int r: resources) {
textView = (TextView) findViewById(r);
textView.setTypeface(myTypeface);
}
if (findViewById(R.id.fragment_container) != null){
if (savedInstanceState != null) {
return;
}
}
}
public void restartGame() {
startButton.setImageResource(R.drawable.smiley);
getFragmentManager().beginTransaction().remove(gridFragment).commit();
setText(999, gameTimer);
startGame();
}
private void startGame(){
gridFragment = new GridFragment();
gridFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();
}
public void setText(int value, TextView textView){
value = Math.min(999,value);
value = Math.max(-99,value);
textView.setText(String.format("%03d",value));
}
#Override
protected void onStart() {
if (!mInit) {
mInit = true;
Database db = new Database(this);
db.deleteAllSessions();
db.close();
startGame();
}
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
m = menu;
return true;
}
private void openSettings(){
showIcon = false;
gridFragment.pauseTimer();
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(false);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.hide(gridFragment);
ft.add(android.R.id.content, settingsFragment).commit();
//ft.replace(android.R.id.content,settingsFragment);
}
private void updateSettings(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Map<String, ?> map = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
isVibrating = (Boolean)map.get("vibration");
}
private void closeSettings(){
showIcon = true;
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.show(gridFragment);
ft.remove(settingsFragment).commit();
//ft.replace(android.R.id.content,gridFragment);
gridFragment.resumeTimer();
}
#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) {
openSettings();
return true;
}
else if(id == R.id.backButton){
updateSettings();
closeSettings();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(showIcon);
item = menu.findItem(R.id.backButton);
item.setVisible(!showIcon);
return super.onPrepareOptionsMenu(menu);
}
}
You're never actually setting or saving the state of the switch. You need to override onBindView to set the initial state of the view, and attach a checked change listener to the Switch (R.id.switch_pref) to listen for changes and persist them into SharedPreferences (you can call persistBoolean to do that).