I'm using editTextPreference to implement a Setting Activity. My problem is that when I click in an EditTextPreference it displays a dialog with the preference title but not appear an edittext to write.
I have searched for this problem but It seems it hasn't happened to anyone. Any help would be appreciated
I have this code :
#EActivity
#OptionsMenu(R.menu.settings_activity_menu)
public class ActivitySettings extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new FragSettings_())
.commit();
}
}
#EFragment
public class FragSettings extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
{
#App
MyApplication app;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#AfterViews
void init()
{
EditTextPreference url =(EditTextPreference)findPreference(app.getResource(R.string.CONFIG_URL_SERVER));
EditTextPreference user =(EditTextPreference)findPreference(app.getResource(R.string.CONFIG_USER_);
if(url!=null)
url.setSummary(app.getSettings().getSharedPreferences().getString(app.getResource(R.string.CONFIG_URL_SERVER), ""));
if(user!=null)
user.setSummary(app.getSettings().getSharedPreferences().getString(app.getResource(R.string.CONFIG_USER_), ""));
}
#Override
public void onResume() {
super.onResume();
// Register as listener to validate settings values
app.getSettings().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
// Remove listener
app.getSettings().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
EditTextPreference connectionPref = (EditTextPreference) findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(app.getSettings().getSharedPreferences().getString(key, ""));
}
}
My preferences.xml, in these editTextPreference is where I have the problem, the input doesn't appear :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/settings_server">
<EditTextPreference
android:key="#string/CONFIG_USER_"
android:title="#string/settings_user"/>
<EditTextPreference
android:inputType="textPassword"
android:key="#string/CONFIG_PASS_"
android:title="#string/settings_password"/>
<EditTextPreference
android:key="#string/CONFIG_URL_SERVER"
android:title="#string/settings_url"/>
</PreferenceCategory>
<Preference
android:key="#string/AREA"
android:title="#string/settings_area"/>
</PreferenceScreen>
What I really not understand is Your Parameters, but let me suspect You are giving the correct references with these to the Preferences. But usually, You have to initialize them with the correct Object:
Preference url =findPreference(Parameters.CONFIG_URL_SERVER);
Preference user =findPreference(Parameters.CONFIG_USER_);
must be
EditTextPreference url =(EditTextPreference)findPreference(Parameters.CONFIG_URL_SERVER);
EditTextPreference user =(EditTextPreference)findPreference(Parameters.CONFIG_USER_);
And it´s better to set the keys inside Your xml layout as a reference to a string in strings.xml, for example:
<EditTextPreference
android:key="#string/user_pref_key"
android:title="#string/settings_user"/>
EDIT
Be sure to use the correct context. For this, You have to wait until the Activity is attached by Override onAttachActivity. Make a global Context:
private Context mContext;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
mContext=activity;
}
Then You can refer it in Your PreferenceFragment.
EditTextPreference url =(EditTextPreference)findPreference(mContext.getResources().getString(R.string.user_pref_key));
At the end I found what was happening. I wanted to use the same text style that I was using in all my application, so in ManifestFIle.xml I had this:
<activity
android:name=".mobile.settings.ActivitySettings_"
android:theme="#style/PreferenceActivity"
android:label="#string/title_activity_settings"/>
Which refers to this style:
<style name="PreferenceActivity" parent="AppTheme">
<item name="android:editTextPreferenceStyle">#style/CodeFont</item>
<item name="android:preferenceCategoryStyle">#style/CodeFont</item>
</style>
<style name="CodeFont" parent="#android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">#dimen/text_size_medium</item>
</style>
It seems that if I use editTextPreferenceStyle it makes disappear the box input. This is my solution:
<activity
android:name=".mobile.settings.ActivitySettings_"
android:theme="#style/AppTheme"
android:label="#string/title_activity_settings"/>
And to custom the edit text I use this http://secutyhf.org/wordpress/zeegers/2014/12/16/android-edittextpreference-style/
<style name="AppTheme" parent="android:Theme.Holo">
<item name="android:editTextStyle">#style/EdittEXTsTYLE</item>
</style>
<style name="EdittEXTsTYLE" parent="android:Widget.EditText">
</style>
Related
I have a pretty weird issue. In my SettingsActivity, I have a DropDownPreference (the one that displays a list when clicked), and it works fine on Portrait mode.
However, when I go into Landscape mode, whenever the preference is clicked, it quickly disappears after being displayed, as if I had pressed the screen twice.
Here is my style, although I doubt there's something to do with it:
<style name="SettingsFragment">
<item name="android:navigationBarColor">?navBackground</item>
<item name="android:statusBarColor">?colorPrim</item>
<item name="android:colorBackground">?colorPrim</item>
<item name="android:colorForeground">?textForeground</item>
<item name="android:textColor">?textForeground</item>
<item name="alertDialogTheme">#style/DialogTheme</item>
<item name="colorAccent">?accentVariant</item>
<item name="preferenceCategoryTitleTextColor">?accentVariant</item>
</style>
Notes: My phone is a Samsung Galaxy Note 10, running Android 12 (API 31).
EDIT: Posting the activity's source code:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
ActivityUtils.applyTheme(this);
getTheme().applyStyle(R.style.SettingsFragment, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settingsContainer, new SettingsFragment())
.commit();
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.settings, rootKey);
}
}
}
PS: Parent theme does not change any attributes aside colors.
I am trying to implement android theme (using <style name="AppTheme" parent="Theme.AppCompat.DayNight">).
Now, from SettingActivity, I am truing to choose theme.
I have defined SettingsActivity as:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
and res/xml/root_preferences has:
<ListPreference
app:defaultValue="default"
app:entries="#array/themes_labels"
app:entryValues="#array/themes_color"
app:key="Theme"
app:title="#string/Theme"
app:useSimpleSummaryProvider="true" />
</PreferenceCategory>
where the arrays are defined as:
<array name="themes_labels">
<item>"Default"</item>
<item>"Light"</item>
<item>"Dark"</item>
</array>
<string-array name="themes_color">
<item>"Default"</item>
<item>"Light"</item>
<item>"Dark"</item>
</string-array>
Now, problem is how to implement the theme, i.e. getting the values from preference and implement. This guide shows a very easy way as:
int currentNightMode = configuration.uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
case Configuration.UI_MODE_NIGHT_NO:
// Night mode is not active, we're using the light theme
break;
case Configuration.UI_MODE_NIGHT_YES:
// Night mode is active, we're using dark theme
break;
}
But the question is how I can get the value of ListPreference and put it to uiMode.
Kindly help.
For saving theme use SharedPreferences,
To save data
//init sharedPreferences
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.apply();
//for saving String
editor.putString("theme", "day"); // here "theme" is key and "day" is value
editor.apply();
now you can get saved theme like this
//init SharedPreference here
//get SharedPreference
String sTheme = sharedPreferences.getString("theme", ""); // "theme" is key and second "" is default value
// now according to this value change theme
switch(sTheme){
// check and set theme here
setTheme(R.style.NightTheme);
}
// this is before setContent
setContentView(R.layout.your_activity);
You can create static method to do all this as you have to check and set theme in every activity
You also need to create multiple Style in res->styles.xml
Hope this will help!
I created a Preferences screen by extending PreferencesActivity as per the example here.
The first screen appears okay but when I click to see the second screen I see them one on top of the other.
So, taking advice from a number of other thread, I changed the background of the second fragment to black.
This worked in as much as I no longer see them both. But instead I see the FIRST one only except for the header.
The first screen looks like this:
and the second one looks like this:
Only the header line changed whereas the rest remained the same.
This is the code in my activity:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferencesMain()).commit();
}
/**
* This fragment contains a second-level set of preference that you
* can get to by tapping an item in the first preferences fragment.
*/
public static class PreferencesMain extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onStart() {
super.onStart();
View view = getView();
view.setBackgroundColor(ResourcesCompat.getColor(getResources(),android.R.color.black, null));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ResourcesCompat.getColor(getResources(),android.R.color.black, null));
}
}
/**
* This fragment contains a second-level set of preference that you
* can get to by tapping an item in the first preferences fragment.
*/
public static class PreferencesNotifications extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_notifications);
}
#Override
public void onStart() {
super.onStart();
View view = getView();
view.setBackgroundColor(ResourcesCompat.getColor(getResources(),android.R.color.black, null));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ResourcesCompat.getColor(getResources(),android.R.color.black, null));
}
}
#Override
protected boolean isValidFragment (String fragmentName) {
return true;
}
}
preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/settings_notifications">
<!-- This PreferenceScreen tag sends the user to a new fragment of
preferences. If running in a large screen, they can be embedded
inside of the overall preferences UI. -->
<PreferenceScreen
android:fragment="activities.SettingsActivity$PreferencesNotifications"
android:title="#string/settings_notifications_managePushTitle"
android:summary="#string/settings_notifications_managePushSummary">
android:background="#android:color/black"
<!-- Arbitrary key/value pairs can be included for fragment arguments -->
<extra android:name="someKey" android:value="somePrefValue" />
</PreferenceScreen>
</PreferenceCategory>
preferences_notifications.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/settings_notifications_managePushHeader">
<CheckBoxPreference
android:key="checkbox_preference"
android:title="#string/settings_notifications_managePushEntry1Title"
android:summary="#string/settings_notifications_managePushEntry1Summary" />
</PreferenceCategory>
Add a header.xml to manage settings, and use onBuildHeaders method.
Resource headers.xml:
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header android:title="Digle"
android:fragment="activities.SettingsActivity$PreferencesMain"/>
</preference-headers>
Class SettingsActivity:
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove all code in here
}
#Override
public void onBuildHeaders(List<Header> target) {
super.onBuildHeaders(target);
loadHeadersFromResource(R.xml.headers, target);
}
...
}
EDIT:
An alternative could be use subscreens. You have to place the group of Preference objects inside a PreferenceScreen.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="Settings"
android:title="#string/app_name">
<PreferenceCategory
android:title="#string/settings_notifications">
<PreferenceScreen
android:background="#android:color/black"
android:summary="#string/settings_notifications_managePushSummary"
android:title="#string/settings_notifications_managePushTitle">
<PreferenceCategory
android:title="#string/settings_notifications_managePushHeader">
<CheckBoxPreference
android:key="checkbox_preference"
android:summary="#string/settings_notifications_managePushEntry1Summary"
android:title="#string/settings_notifications_managePushEntry1Title"/>
</PreferenceCategory>
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
I am trying to add theme support to app. It is working, but I want user to choose between themes. The problem is, I cannot do that I tried so many things. I am using ListPreference to define a list of arrays for user to choose. I cannot link those listpreference entry values with util.
If I edit "0" in Util with any number, themes work but it doesnt work when I change those entry values (from list in phone)IDK why.
Below is the code
Settings.java
public class Settings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Util.setAppTheme(this);
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
PrefsFragment mPrefsFragment = new PrefsFragment();
mFragmentTransaction.replace(android.R.id.content, mPrefsFragment);
mFragmentTransaction.commit();
}
public static class PrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
}
Util.java
public class Util extends Activity {
public static void setAppTheme(Activity a) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(a);
int mTheme = Integer.parseInt(sp.getString("theme", "0"));
if(mTheme==0)
{
a.setTheme(R.style.Dark);
}
if(mTheme==1)
{
a.setTheme(R.style.Light);
}
if(mTheme==2)
{
a.setTheme(R.style.LimeLight);
}
if(mTheme==3)
{
a.setTheme(R.style.MojoLight);
}
if(mTheme==4)
{
a.setTheme(R.style.SanMarinoLight);
}
if(mTheme==5)
{
a.setTheme(R.style.LimeDark);
}
if(mTheme==6)
{
a.setTheme(R.style.MojoDark);
}
if(mTheme==7)
{
a.setTheme(R.style.SanMarinoDark);
}
}
}
preferences.xml
<PreferenceCategory
android:title="#string/preference_category2_title">
<ListPreference android:key="list2_preference"
android:title="#string/list2_title"
android:summary="#string/list2_summary"
android:entries="#array/list2_preferences"
android:entryValues="#array/list2_preferences_values"
android:dialogTitle="#string/list2_dialog_title"/>
<SwitchPreference android:key="switch1_preference"
android:title="#string/switch1_title"
android:switchTextOff="#string/switch1_textoff"
android:switchTextOn="#string/switch1_texton"
/>
</PreferenceCategory>
styles.xml
<!-- Dark -->
<style name="Dark" parent="android:Theme.Holo">
<item name="android:windowBackground">#drawable/activity_background_dark</item>
</style>
<!-- Light -->
<style name="Light" parent="android:Theme.Holo.Light">
<item name="android:actionBarStyle">#style/ActionBar_Light</item>
<item name="android:windowBackground">#drawable/activity_background_light</item>
</style>
arrays.xml
<resources>
<string-array name="list2_preferences">
<item>Dark</item>
<item>Light</item>
<item>Light Lime</item>
<item>Light Mojo</item>
<item>Light San Marino</item>
<item>Dark Lime</item>
<item>Dark Mojo</item>
<item>Dark San Marino</item>
</string-array>
<string-array name="list2_preferences_values">
<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
</string-array>
I will be thankful if anyone can help me out?
What is your on code for the onItemSelected method of your list?
Also you can't change the theme of an activity after you've initialized it's layout.
In my current application I also allow the user to change the theme. To achieve this I simply start the activity again passing an argument (the selected theme) and finish the current one.
In the activity onCreate() I then check the argument. If it's -1 (activity first time start) I get the default theme.
private static final String INTENT_EXTRA = "theme";
private boolean onCreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
onCreate = true;
themeId = getIntent().getIntExtra(INTENT_EXTRA, -1);
if (themeId == -1) {
themeId = SharedPreferencesManagment
.getApplicationThemeResourceId(SharedPreferencesManagment
.getIntApplicationTheme(this));
} else {
themeId = SharedPreferencesManagment
.getApplicationThemeResourceId(themeId);
}
setTheme(themeId);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options_theme);
initSpinner();
}
In the list's onItemSelected() method I call something like:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!onCreate) {
Intent intent = new Intent(this, OptionsThemeActivity.class);
intent.putExtra(INTENT_EXTRA, getSelectedTheme());
startActivity(intent);
finish();
}
onCreate = false;
}
Also note the onCreate-boolean as the onItemSelected()-method is also called when the activity inits the spinner.
(Was the simpliest workaround to prevent a infinte loop)
ALSO:
Why is Util a Activity? If the code you've posted is everything you do with Util you don't need to extend Activity as you pass the context.
I am new to Android, so I need a little guidance on how to programmatically add EditTextPreference objects to my PreferenceFragment.
I am pulling in a list of values from a web service. I have saved them successfully to my SharedPreferences, and I use them to generate URLs (path portion).
I would like the users of my app to be able to edit these values, but after lots of searching on Google, it isn't clear to me how to programmatically add EditTextPreference objects to my PreferenceFragment.
Please note, my PreferenceFragment is working fine for the SharedPreferences values I hard code as names into the preference xml file (PreferenceScreen). I also know how to get my SharedPreferences, so don't worry about having to explain that portion to me.
I use addPreferencesFromResource in onCreate of my PreferenceFragment. Should I add them in the onCreateView? I was thinking I could get the PreferenceCategory and add them there? But again, I am not sure how to do that. I would really be grateful for the help!
// Code
PrefsFragment.java:
package com.example.lorddoineedhelp;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, container, savedInstanceState);
// I am guessing I need to do something here?
return v;
}
}
XML File for PreferenceFragment:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Hard coded values -->
<PreferenceCategory
android:title="General">
<CheckBoxPreference
android:key="debug"
android:title="Debug"
android:summary="Enable Debug" />
</PreferenceCategory>
<PreferenceCategory android:title="Address">
<EditTextPreference
android:key="ipAddress"
android:title="IP Address"
android:summary="IP Address used for Image pings"
/>
<EditTextPreference
android:key="port"
android:title="Port"
android:summary="Port used for Image pings" />
</PreferenceCategory>
<!-- Where I want to add the values from my web service -->
<PreferenceCategory
android:title="Paths"
android:key="urlPaths">
</PreferenceCategory>
</PreferenceScreen>
You can add preferences, e.g. EditTextPreference, CheckBox, etc, programmatically in the "onCreate" method of the PreferenceFragment.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load "dummy" (empty) preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_channelconfig);
PreferenceScreen screen = this.getPreferenceScreen(); // "null". See onViewCreated.
// Create the Preferences Manually - so that the key can be set programatically.
PreferenceCategory category = new PreferenceCategory(screen.getContext());
category.setTitle("Channel Configuration");
screen.addPreference(category);
CheckBoxPreference checkBoxPref = new CheckBoxPreference(screen.getContext());
checkBoxPref.setKey(channelConfig.getName() + "_ENABLED");
checkBoxPref.setTitle(channelConfig.getShortname() + "Enabled");
checkBoxPref.setSummary(channelConfig.getDescription());
checkBoxPref.setChecked(channelConfig.isEnabled());
category.addPreference(checkBoxPref);
}
The crucial step is the addPreferencesFromResource(...), with a dummy xml to attach an empty PreferenceScreen to the fragment. Without this, there is no "top-level Preference that is the root of a Preference hierarchy", thus this.getPreferenceScreen() returns Null.
The XML I used was just:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:orderingFromXml="true">
</PreferenceScreen>
Hope that helps someone.
Here is the code to create a PreferenceFragment programmatically:
public class MyPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(getActivity());
setPreferenceScreen(screen);
EditTextPreference preference = new EditTextPreference(screen.getContext());
preference.setKey("EditTextPreference");
preference.setTitle("Edit Text Preference");
preference.setSummary("Click the preference to edit text.");
screen.addPreference(preference);
}
}
I don't know if it works in the onCreateView method but it does in the onViewCreated.
Here is my code (Inside a subclass of PreferenceFragment):
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.getPreferenceScreen().addPreference(new EditTextPreference(getActivity()));
}