In my project i have 2 activity , in second activity i have a switch button .
i have 2 problems :
1: I want to get the value of switch button from second activity and pass it to first activity by using shared preferences to show a toast in first activity but i do not get the value of switch button so toast does not work correctly .
2:When i press back or close application , the value of switch button change to default , how can i save the value of switch button ?
This is my first activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Boolean isChecked = settings.getBoolean("status" , false);
if (isChecked){
Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_setting:
Intent settingIntent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(settingIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is my second activity :
public class Main2Activity extends AppCompatActivity {
Switch aSwitch;
EditText editText;
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editText = (EditText) findViewById(R.id.editText);
aSwitch = (Switch) findViewById(R.id.switch1);
back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(swIntent);
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("MySwitch", true);
super.onSaveInstanceState(outState);
}
public void enable_disable(View view) {
if (aSwitch.isChecked()) {
SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
editor.putBoolean("status", true);
editor.commit();
} else {
SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
editor.putBoolean("status", false);
editor.commit();
}
}
}
And this is the layout of my second activity :
<LinearLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">
<Switch
android:id="#+id/switch1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="enable_disable"
android:text="Switch" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnBack"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Use switch onChangedListener. This will retain your switch state in your Main2Activity
public class Main2Activity extends AppCompatActivity {
Switch aSwitch;
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
aSwitch = (Switch) findViewById(R.id.switch1);
SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
boolean isChecked = sharedPreference.getBoolean("status",false);
Log.d("Shriyansh",isChecked+"");
aSwitch.setChecked(isChecked);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
editor.putBoolean("status", isChecked);
editor.commit();
Log.d("Shriyansh1",isChecked+"");
}
});
back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(swIntent);
}
});
}
Now to show toast in your first activity you can use this preference in onResume() method of your MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
boolean isChecked = sharedPreference.getBoolean("status",false);
if (isChecked){
Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_setting:
Intent settingIntent = new Intent(getApplicationContext(),
Main2Activity.class);
startActivity(settingIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Layout of your Main2Activity remove enable_disable method for switch
<LinearLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">
<Switch
android:id="#+id/switch1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnBack"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
in you MainActivity you need to replace
PreferenceManager.getDefaultSharedPreferences(this);
with
SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
also remove this from your Main2Activity
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("MySwitch", true);
super.onSaveInstanceState(outState);
}
SharedPreferences are just key value xml files stored on the device. The problem you are having is that you are using two different SharedPreferences which is why the value is not showing up.
In your SecondActivity where you use the line:
getSharedPreferences("switch", MODE_PRIVATE).edit();
You are creating a SharedPreferences file called switch.xml and storing the value of your switch in it. However in your MainActivity when you call:
PreferenceManager.getDefaultSharedPreferences(this);
This fetches the 'default file' which is a different xml file and as such the value is not there. You need to be consistent with which SharedPreferences file you are accessing between the two Activities. In this case I'd recommend just using the default file and changing your SecondActivity to be:
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(this)
.edit();
editor.putBoolean("status", true);
editor.commit();
Now the value will be saved in the default file which is the same one which your reading in the MainActivity
Related
Inside my SettingsActivity extends AppCompatActivity I have SettingsFragment extends PreferenceFragment. When I try press home-buttion in toolbar it is not working. Here is my code
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/settingsToolbar"
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="?android:actionBarSize"
android:background="#color/colorPrimary" />
SettingsActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupToolBar();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
private void setupToolBar() {
getLayoutInflater().inflate(R.layout.toolbar, (ViewGroup) findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar) findViewById(R.id.settingsToolbar);
setSupportActionBar(toolbar);
setTitle(getResources().getString(R.string.settings));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setFocusable(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
I tried to solve it in such way: remove setNavigationOnClickListener and add this:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return (super.onOptionsItemSelected(menuItem));
}
It does not help. How can I fix this?
add this line to config your getSupportActionBar:
getSupportActionBar().setHomeButtonEnabled(true);
use both code in your activity like below:
in your setupToolbar method:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Log.d("cek", "home selected");
finish();
}
});
and in your onOptionsItemSelected method:
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
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.
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);
//...
}
I have code like this:
DrawerLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/drawerList"
android:layout_width="180dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:divider="#android:color/darker_gray"
android:dividerHeight="1dp"
android:entries="#array/Functions" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
DrawerActivity:
public class Drawer extends Activity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle mDrawerToggle;
private Intent intent;
public RelativeLayout fullLayout;
public FrameLayout frameLayout;
#Override
public void setContentView(int layoutResID) {
fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_main, null);
frameLayout = (FrameLayout) fullLayout.findViewById(R.id.content_frame);
drawerLayout = (DrawerLayout) fullLayout.findViewById(R.id.drawerLayout);
drawerList = (ListView) fullLayout.findViewById(R.id.drawerList);
getLayoutInflater().inflate(layoutResID, frameLayout, true);
super.setContentView(fullLayout);
drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.Functions)));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {}
public void onDrawerOpened(View drawerView){}
};
drawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setIcon(R.drawable.ic_drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(int position) {
drawerLayout.closeDrawers();
switch (position) {
case 0:
intent = new Intent(this, 0Act.class);
startActivity(intent);
break;
case 1:
// intent = new Intent(this, 1Act.class);
break;
case 2:
intent = new Intent(this, 2Act.class);
startActivity(intent);
break;
case 3:
intent = new Intent(this, 3Act.class);
startActivity(intent);
break;
case 4:
// intent = new Intent(this, 4Act.class);
break;
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
}
FirstActivity:
public class 0Act extends Drawer implements ActionBar.TabListener {
ActionBar.Tab t1,t2,t3;
ActionBar actionBar;
Button oneButton;
final CharSequence[] items = {"1", "2", "3", "4"};
AlertDialog.Builder ad;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.0Act);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
t1 = actionBar.newTab().setText("1");
t2 = actionBar.newTab().setText("2");
t3 = actionBar.newTab().setText("3");
t1.setTabListener(this);
t2.setTabListener(this);
t3.setTabListener(this);
actionBar.addTab(t1);
actionBar.addTab(t2);
actionBar.addTab(t3);
actionBar.setSelectedNavigationItem(0);
oneButton= (Button) this.findViewById(R.id.oneButton);
oneButton.setOnClickListener(new View.OnClickListener(){#Override public void onClick(View v) {ad.show();}});
ad = new AlertDialog.Builder(getActivity());
ad.setTitle("Menu");
ad.setItems(items, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int item) {}});
}
}
I see the drawer - I can click on the drawer but I cannot click on any buttons from the first activity. What is going wrong?
Before added drawer to many activities all working good but now I dont see any error and activity dont working.
Mention super.onClick(v); inside onClick method for your Item1Activity Class
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).