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);
//...
}
Related
I'm trying to add a BottomNavigationView in my project but don't show up when i run the project.
I'd like to put this on several activities, aswell as Toolbar so i created a class that initialize both of them and extends AppCompatActivity so that my activies using the Toolbar or the BottomNavigationView just have to extends this activity and call the method that initialize it (i don't know if this is the right method to use, if no please tell me). So this work with my Toolbar, but my BottomNavigationView isn't showing up.
This is my NavigationActivity i talked about :
public abstract class NavigationActivity extends AppCompatActivity {
private Toolbar mToolbar;
private BottomNavigationView mNavigationView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void initNavigation(int navigationId) {
mNavigationView = (BottomNavigationView) findViewById(navigationId);
mNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.navigation_entrainements:
startActivity(new Intent(getBaseContext(),MenuEntrainementsActivity.class));
break;
case R.id.navigation_nutrition:
startActivity(new Intent(getBaseContext(),NutritionActivity.class));
break;
case R.id.navigation_statistiques:
startActivity(new Intent(getBaseContext(),StatistiquesActivity.class));
break;
}
return true;
}
});
}
public void initToolbar(int toolbarId) {
mToolbar = (Toolbar) findViewById(toolbarId);
mToolbar.setNavigationIcon(R.drawable.baseline_arrow_back_black_18dp);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.btnHome :
startActivity(new Intent(this,MainActivity.class));
return true;
case R.id.btnProfil :
startActivity(new Intent(this,ProfilActivity.class));
return true;
default :
return super.onOptionsItemSelected(item);
}
}
}
and an exemple of how i'm using it in others activities :
initNavigation(R.id.navigation);
initToolbar(R.id.toolbar);
this is how i implement the BottomNavigationView in my XML files :
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
if you need anything else just ask,
thanks for your help :)
(sorry if i made mistakes i'm not great in english)
I Use this from outside of onCreate mothod.
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.btnHome :
startActivity(new Intent(this,MainActivity.class));
return true;
case R.id.btnProfil :
startActivity(new Intent(this,ProfilActivity.class));
return true;
default :
startActivity(new Intent(this,MainActivity.class));
return true;
}
}
};
I have 3 tabs in my dashboard namely,
Invitation
Event
Groupchat
I am added all those tabs programmatically,In my layout code id:tabContent using for add all my tabs. My Userdashboard.xml code is below,
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="-4dp"
android:layout_weight="0" />
</LinearLayout>
In below code all tabs are grouped as "tabHost". Now i am need to set unique id for all the three tabs, but i dont know how to set unique id for that help me please thanks in advance.
public class UserDashBoardActivity extends ActionBarActivity {
/** Called when the activity is first created. */
private static final String TAB_1_TAG = "Invitation";
private static final String TAB_2_TAG = "Event";
private static final String TAB_3_TAG = "GroupChat";
private FragmentTabHost tabHost;
private Context context;
private SharedPreferences sharedpreferences;
private Gson gson = new Gson();
private Menu menu;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.menu=menu;
getMenuInflater().inflate(R.menu.menu_user_dash_board, menu);
return true;
//return super.onCreateOptionsMenu(menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE);
// Get TabHost Reference
tabHost= (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
**Invitation,Event,Groupchat tabs** are added here
tabHost.addTab(tabHost.newTabSpec(TAB_1_TAG).setIndicator("Invitation"), InvitationFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_2_TAG).setIndicator("Event"), OccasionFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_3_TAG).setIndicator("GroupChat"), GroupChatFragment.class, null);
//invitation tab highlighted by default
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.Orange));
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.scandal));
tabHost.getTabWidget().getChildAt(2).setBackgroundColor(getResources().getColor(R.color.scandal));
//onTabChangedListener added for move one tab to others
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
setTabColor(tabHost);
}
});
}
if(tabHost.getCurrentTab()==0)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange));//1st tab selected
else if(tabHost.getCurrentTab()==1)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //2nd tab selected
else if(tabHost.getCurrentTab()==2)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //3rd tab selected
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.account_settings) {
Intent userSettingIntent = new Intent(getApplicationContext(),ActivityUserSettings.class);
userSettingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(userSettingIntent);
return true;
}
if (id == R.id.profile) {
Intent profileIntent = new Intent(getApplicationContext(),ImageUploadActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(profileIntent);
return true;
}
if(id == R.id.create_occasion){
Intent occasionAct = new Intent(getApplicationContext(), OccasionActivity.class);
// Clears History of Activity
occasionAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(occasionAct);
}
return super.onOptionsItemSelected(item);
}
}
The call to tabHost.newTabSpec() takes a String as tag. In your case these are TAB_1_TAG, TAB_2_TAG, TAB_3_TAG, so these are your unique IDs for each tab respectively.
You can identify the selected tab in onTabChanged(String arg0) here arg0 is the name of the selected tag.
Furthermore you can use tabHost.getCurrentTabTag() to identify tabs by tag instead of tabHost.getCurrentTab() which is by tab position.
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).
I am trying to make a collapsible EditText in the Action Bar. I have followed the Android Developers guide. But when I click on my search icon, nothing happens.
What can I do?
Here is my code.
The activity:
public class ElementPagerActivity extends ActionBarActivity
implements ElementListFragment.onElementClickListener,
CalculateFragment.OnCalculateClickListener{
ViewPager theViewPager;
private ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
actionBar = getSupportActionBar();
theViewPager = new ViewPager(this);
theViewPager.setId(0x1);
theViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
if(position == 0){
return new ElementListFragment();
} return Element.values()[position - 1].toFragment();
}
#Override
public int getCount() {
return Element.values().length + 1;
}
});
theViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
if(position == 0){
actionBar.setTitle(R.string.Element_info_activity_label);
actionBar.selectTab(null);
} else {
actionBar.setTitle(Element.values()[position - 1].getName());
actionBar.selectTab(actionBar.getTabAt(position - 1));
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
actionBar = actionBar;
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
int position = tab.getPosition();
theViewPager.setCurrentItem(position + 1, true);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
int position = tab.getPosition();
theViewPager.setCurrentItem(position + 1, true);
}
};
for (int i = 0; i < Element.values().length; i++){
actionBar.addTab(
actionBar.newTab()
.setText(Element.values()[i].getName())
.setTabListener(tabListener));
}
theViewPager.setCurrentItem(0);
actionBar.selectTab(null);
setContentView(theViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.element_pager, menu);
menu.findItem(R.id.pager_activity_show_list_action).setVisible(!(theViewPager.getCurrentItem() == 0));
menu.findItem(R.id.pager_activity_edit_text_action).expandActionView();
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.pager_activity_show_list_action){
theViewPager.setCurrentItem(0, true);
return true;
} else if (id == R.id.pager_activity_edit_text_action){
return false;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (theViewPager.getCurrentItem() == 0){
super.onBackPressed();
} else {
theViewPager.setCurrentItem(0);
}
}
#Override
public void onElementClick(int position) {
theViewPager.setCurrentItem(position + 1, true);
}
#Override
public Element onRequestElement() {
return Element.values()[theViewPager.getCurrentItem() - 1];
}
}
Menu resources:
<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=".MainActivity" >
<item android:id="#+id/pager_activity_edit_text_action"
app:showAsAction="always|collapseActionView"
android:title="text here"
android:icon="#android:drawable/ic_menu_search"
android:actionLayout="#layout/test"/>
<item android:id="#+id/pager_activity_show_list_action"
android:title="#string/action_bar_pager_show_list"
android:orderInCategory="100"
app:showAsAction="ifRoom|withText" />
</menu>
Action layout (test.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="element"
android:inputType="textCapWords"/>
</LinearLayout>
And here is a short film demonstrating the problem.
I appreciate all answers.
Greetings from the Netherlands
You can use a SearchView, which will make things a bit easier for you.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/search"
android:title="#string/search_title"
android:icon="#drawable/ic_search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
more here: http://developer.android.com/training/search/setup.html
I am a newbie to android, so please be patient.
I am trying to learn preferences. I have an app that has a mainActivity, when the menu icon it's pressed a MyPreferenceActivity is shown. It allows the user setting some preferences related to a subject.
In my mainActivity I have a loadPrefernces method that works fine when the app is installed, but the first time it throws an error: unable to start activity component info[..] java.lang.NullPointerException
Here is my code:
MainActivity
public class MainActivity extends Activity {
public static final String PREFERENCE_FILENAME = "com.id11298775.exercise6_preferences";
SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPreferences(); // this cause the error
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, MyPreferenceActivity.class);
startActivity(i);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
loadPreferences();
}
private void loadPreferences() {
mSharedPreferences = getSharedPreferences(PREFERENCE_FILENAME,
MODE_PRIVATE);
// Setting the textView related to the subject
TextView subjectTv = (TextView) findViewById(R.id.activitymain_favouritesubjectresult_tv);
subjectTv.setText(mSharedPreferences.getString("list_subject_pref",
null));
// Setting the TextView related to the URL
TextView urlTv = (TextView) findViewById(R.id.activitymain_handbookurlresult_tv);
urlTv.setText(mSharedPreferences.getString("et_subject_pref", null));
// Setting the TextView related to the times selected
TextView labTimeTv = (TextView) findViewById(R.id.activitymain_labtimeresult_tv);
// #SuppressWarnings("unchecked")
Map<String, ?> map = mSharedPreferences.getAll();
Object cs = map.get("list_times_pref");
labTimeTv.setText(cs.toString());
}
#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;
}
}
this is my MyPreferenceActivity
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("list_subject_pref")) {
ListPreference preference = (ListPreference) findPreference(key);
CharSequence currText = preference.getEntry();
preference.setSummary(currText);
} else if (key.equals("et_subject_pref")) {
EditTextPreference preference = (EditTextPreference) findPreference(key);
String newUrl = preference.getText().toString();
preference.setSummary(newUrl);
} else if (key.equals("list_times_pref")) {
Set<String> selections = sharedPreferences.getStringSet(
"list_times_pref", null);
String[] selected = selections.toArray(new String[] {});
String listSelection = "";
for (int i = 0; i < selected.length; i++) {
listSelection += selected[i] + " ";
}
MultiSelectListPreference multi = (MultiSelectListPreference) findPreference(key);
multi.setSummary(listSelection);
} else if (key.equals("ringtonePref")) {
RingtonePreference preference = (RingtonePreference) findPreference("ringtonePref");
String strRingtonePreference = ((SharedPreferences) preference).getString("ringtonePref", "none");
Uri ringtoneUri = Uri.parse(strRingtonePreference);
Ringtone ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
String name = ringtone.getTitle(this);
preference.setSummary("select " + name);
}
}
}
here is logcat:
I think that the first time the app is installed there are no preference set, therefore the error, but I can't figure out a good way to prevent the exception.
Anybody can please help me?