I am trying to get a checkbox to default to True when the app is launched.
I used this answer Android CheckBoxPreference Default Value but it still defaults to false and prints False in LogCat.
Any ideas where I have messed up? I've been looking at this for hours... thanks in advance!
public class Preferences extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
PreferenceManager.setDefaultValues(this, R.layout.preferences, true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean autoStart = prefs.getBoolean("checkBox1", true);
System.out.println(autoStart);
}
}
XML class:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:summary="Username and password information"
android:title="User request" >
<CheckBoxPreference
android:key="checkBox1"
android:title="request details"
android:defaultValue="true"/>
</PreferenceCategory>
</PreferenceScreen>
In Your main activity you could do following:
SharedPreferences prefs = getSharedPreferences("YOUR_PREFERENCES_KEY",false);
boolean isSetToTrue = prefs.getBoolean("YOUR_BOOLEAN_KEY",false);
if(isSetToTrue==false){
//here set your checkBox to true
}
main Activity means the activity that starts first with starting app.
Related
I need to display number keyboard in EditText Preference which is androidx.
proxy.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:dialogTitle="edittext_dialogtitle_proxy_port"
android:key="edittext_key_proxy_port"
android:inputType="numberPassword"
android:digits="0123456789."
android:summary="Summary"
android:title="Port"/>
</PreferenceScreen>
MainActivity:
public class MainActivity extends PreferenceFragmentCompat {
EditTextPreference mPortField;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.proxy);
mPortField = (EditTextPreference) findPreference("edittext_key_proxy_port");
mPortField.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
#Override
public void onBindEditText(#NonNull EditText editText) {
}
});
}
I am not getting number keypad
[![enter image description here][1]][1]
according to this doc android:inputType is applicable only for EditText, not EditTextPreference (which isn't extending EditText, DialogPreference instead). but you already figured out how to get EditText hidden in EditTextPreference, so maybe just set digit limitation programmatically inside onBindEditText with below line
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
(more info HERE)
I would like to crate a settings Activity with items with Title and subtitle.
I've checked a lot in documentation and even other posts here and people say it's not possible... android default settings page has a lot of it:
sorry for the picture in portuguese, but what is written there doesn't matter, the point is the settings page built on android has plenty of titile/subtitle items (and it happens in many other screens)
I would like to achieve it using android default Preference api. is that possible?
Yes it is possible. One fast solution is the following (that might be improvied and tuned according your needs):
public class SettingsActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.settings_fragment, new PrefsFragment()).commit();
}
}
public static class PrefsFragment extends PreferenceFragment {
public PrefsFragment(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
}
}
}
activity_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/settings_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.vb.myapplication.SettingsActivity$PrefsFragment" />
</LinearLayout>
settings.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="keyCategory"
android:title="titleCategory">
<CheckBoxPreference
android:key="keyCheckPreference"
android:title="titlePreference"
android:summary="summaryPreference"
android:defaultValue="false"/>
</PreferenceCategory>
</PreferenceScreen>
I am creating a basic settings page and my code works fine till now. But when i add UnregisterOnSharedPreferenceChangeListener at Onpause it starts giving errors. Insight is required that what i am doing wrong and where should i insert the unregister. All the codes are presented below. I would be happy if you guys could test it out in Android Studio. Any help would be appreciated. I am trying to avoid using deprecated code but if no alternatives i will use it as last resort.
Main Activity.java
public class MainActivity extends AppCompatActivity {
TextView settingsValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button startsettings = (Button)findViewById(R.id.startsettings);
settingsValue=(TextView)findViewById(R.id.textView);
startsettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SettingsActivity.class));MainActivity.this.finish();}
});
}}
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity {
static SharedPreferences sharedPreferences12;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences12 = PreferenceManager.getDefaultSharedPreferences(this);
getFragmentManager().beginTransaction().replace(android.R.id.content,new SettingsFragment()).commit();
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
{
Context context;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.custompreferences);
context=getActivity();
Preference prefalarm = findPreference("key_ringtone_alarm");
Ringtone ringtone = RingtoneManager.getRingtone(getActivity(),Uri.parse(sharedPreferences12.getString("key_ringtone_alarm","")));
prefalarm.setSummary(ringtone.getTitle(getActivity()));
Preference prefnoti = findPreference("key_ringtone_notification");
Ringtone ringtonenoti = RingtoneManager.getRingtone(getActivity(),Uri.parse(sharedPreferences12.getString("key_ringtone_notification","")));
prefnoti.setSummary(ringtonenoti.getTitle(getActivity()));
PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if(pref instanceof RingtonePreference)
{
Ringtone ringtone = RingtoneManager.getRingtone(context,Uri.parse(sharedPreferences.getString(key,"")));
pref.setSummary(ringtone.getTitle(context));
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(SettingsActivity.this,MainActivity.class));SettingsActivity.this.finish();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.atulk.createcustomsettings.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Settings"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/startsettings"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintVertical_bias="0.095" />
</android.support.constraint.ConstraintLayout>
custompreferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="User Details"
android:key="key_user_details">
<Preference
android:key="key_user_name"
android:title="User First Name"
android:summary="John Smith"/>
<Preference
android:key="key_user_emailid"
android:title="User Email ID"
android:summary="asd#asd.com"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Sounds & Notifications"
android:key="key_sounds_settings">
<RingtonePreference
android:key="key_ringtone_alarm"
android:title="Alarm Ringtone"
android:ringtoneType="alarm"/>
<RingtonePreference
android:key="key_ringtone_notification"
android:title="Notification"
android:ringtoneType="notification"/>
<SwitchPreference
android:title="Vibrate"
android:summary="Virate during Alarm or Notification"
android:key="key_vibrate_onoff"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Message Delivery"
android:key="key_message_delivery">
<SwitchPreference
android:title="Shorten SMS"
android:summary="Reduce SMS length by using slangs"
android:key="key_shorten_sms_length"/>
</PreferenceCategory>
</PreferenceScreen>
Just create 2 different java files with preferenceactivity and preferencefragment
and call PF from PA with getFragmentManager routine. Rest all will work fine. Also use UnregisterOnPreferenceChangeListener in OnDestroy instead of OnPause.
I have one main activity with multiple Fragments. From the menu, the user can go to a new activity which contains the PreferenceFragment:
Preference Activity and Fragment:
public class SettingsActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options_screen);
}
/**
* This fragment shows the preferences for the first header.
*/
public static class Prefs1Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_options);
}
}
}
Preferences xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/pref_cat_display">
<ListPreference
android:key="pref_key_display_units"
android:title="#string/pref_title_units"
android:summary="#string/pref_summary_units"
android:entries="#array/entries_list_units"
android:entryValues="#array/entryvalues_list_units"
android:dialogTitle="#string/pref_dialog_title_list_units"
android:defaultValue="0"/>
</PreferenceCategory>
</PreferenceScreen>
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/settings_content"
android:paddingTop="?android:attr/actionBarSize">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.cs.biodyapp.usl.activity.SettingsActivity$Prefs1Fragment"
android:id="#+id/fragment" />
</LinearLayout>
Once the option has been initialized, I try to access to this preference from the original Activity but I always get an empty Map in the SharedPreferences object.
I tried many ways that supposely let you access preferences form a different activity or directly from the file but no chance:
//SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
SharedPreferences sharedPref = getActivity().getApplication().getSharedPreferences("pref_options", Context.MODE_PRIVATE);
int units = sharedPref.getInt("pref_key_display_units", 0);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
Is the correct line to use ( getting the application context and not the base context ).
I also detected a problem in using ListPreference with integer arrays in a PreferenceFragment. Finally I had to use string arrays and sharedPrefs.getString() to then cast it to an integer.
I just set a button on a preference activity from one the answers from this question. My main issue is that this button is unclickable while the other elements of the preference activity is click able.
I created a simple example to demonstrate my dilemma it should show the same symptoms as you copy and paste.
public class preferenceTest extends PreferenceActivity{
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "I got clicked", Toast.LENGTH_SHORT).show();
}
});
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preftest);
// Do Stuff
}
}
}
res\layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#android:color/black"
android:layout_weight="10"/>
<Button android:text="This is a button on bottom of all preferences."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:textColor="#android:color/black"
android:layout_weight="1"/>
</LinearLayout>
res\xml\preftest.xml
<PreferenceCategory
android:title="New Title"
android:summary="Title">
<ListPreference
android:key="list1"
android:title="List one"
android:summary="List1"
/>
<ListPreference
android:key="list2"
android:title="List two"
android:summary="List2"/>
</PreferenceCategory>
<CheckBoxPreference
android:key="check1"
android:title="check1"
android:summary="CheckBox Test"/>
</PreferenceScreen>
I'm not sure why you would want to add a button in a PreferenceActivity, but what you can do is add a plain Preference and then make that clickable through the activity code.
For instance, on your preferences.xml
<Preference
android:key="#string/pref_key_dummy_pref_button"
android:title="#string/pref_title_dummy_pref_button" />
Then, on your PreferenceActivity, create a Preference object:
Preference mDummyButtonPref;
Initialize it from onCreate:
addPreferencesFromResource(R.xml.preferences);
mDummyButtonPref= findPreference(getString(R.string.pref_key_dummy_pref_button));
Then, add override onPreferenceTreeClicked to handle clicks:
#Override
#Deprecated
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
if (preference == mDummyButtonPref) {
Log.v(TAG, "Dummy got clicked");
}
}