So I have EditText in my Preferences and i want to get the text it and use it as String.Then i want to use that string everytime when my button is clicked and it will set my another EditText text to the string from Preference. Codes :
<EditTextPreference android:title="Uredi Text"
android:key="ime"
android:summary="ime pjesme"
/>
Java code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String b1t = preferences.getString("ime", "DEFAULT");
et1 = (EditText) findViewById(R.id.editText1);
//Button Click
public void button(View view) {
et1.setText(b1t);
}
According to the developer docs, you can just use edittextpreference.getText().toString()
http://developer.android.com/reference/android/preference/EditTextPreference.html
I'm not sure where your error is so I'll just give you my code for doing this.
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext();
String string = sharedPreferences
.getString("key", "default");
And in my preferences
<EditTextPreference
android:defaultValue="default"
android:key="key"
android:summary="I'm a summary"
android:title="I'm a title" />
For the onCLick method to modify the edit text
EditText editText = (EditText)
findViewById(R.id.editText);
editText.setText(String.valueOf(string));
This code works. If your application still crashes then your issue is either with your onClick event or something else. I personally prefer onClickListeners for buttons.
Heres the code for an onClickListener.
Button button = (Button)
findViewById(R.id.button);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Do some awesome stuff
}
});
edit: John posted his answer before mine, and his answer reflects most use cases, such as in a standard Activity. My answer is directed solely at the use of a PreferenceActivity.
Here's how you can add Preferences with defaults based on another Preference within a PreferenceActivity. Sorry if there are any errors, I'm typing on my phone.
Your XML-defined Preferences will have their values saved to SharedPreferences automatically, but code-created Preferences will need to be saved/persisted manually.
PreferenceActivity's onConfigurationChange() usually saves the state of code-created preferences (nested PreferenceScreens are a bit strange.)
And, of course, you'll want to do null checks (omitted to save my thumbs.)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Preferences"
android:key="root">
<EditTextPreference android:title="Default Pref Text"
android:key="ime"
android:summary="ime pjesme"
/>
<Preference android:title="Click to add a preference."
android:key="add"
android:summary=""
/>
</PreferenceScreen>
MyActivity.class
public class MyActivity extends PreferenceActivity {
public void onCreate(Bundle inState) {
super.onCreate(inState);
setContentView(R.layout.activity_main);
getPreferenceScreen.findPreference(PREFERENCE_BUTTON).
setOnPreferenceClickListener(new OnNewPrefClickListener());
}
private class OnNewPrefClickListener implements OnPreferenceClickListener {
public boolean onPreferenceClick(Preference preference) {
PreferenceScreen rootScreen = getPreferenceScreen();
EditTextPreference defaultPref =
(EditTextPreference)rootScreen.findPreference("ime");
String defaultText = defaultPref.getText();
EditTextPreference newPref = new EditTextPreference(getApplicationContext());
newPref.setText(defaultText);
rootScreen.addPreference(newPref);
return true;
}
}
}
Related
I have checkboxpreference in preference activity and I want that when one of the checkbox is enabled then other checkbox should get to disable and vice versa.
I wants to do that from my main class activity.
Here is my code:
Preferencecheckbox.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:defaultValue="true"
android:icon="#drawable/img"
android:key="check1"
android:title="first" />
<CheckBoxPreference
android:defaultValue="false"
android:icon="#drawable/img2"
android:key="check2"
android:title="second" />
</PreferenceScreen>
Preferenceclass.java
public class preferenceclass extends PreferenceActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferencecheckbox);
}
You need to add a dependency to the checkbox you need disabled.
Like this:
<CheckBoxPreference
android:defaultValue="false"
android:icon="#drawable/img2"
android:key="check2"
android:title="second"
android:dependency="check1" />
Update
To disable other preferences via code.
final CheckBoxPreference checkbox2 = (CheakBoxPreference) findPreference("pref_checkbox2_key");
CheckBoxPreference switch = (CheakBoxPreference) findPreference("pref_switch_key");
switch.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
if (switch.isChecked()) {
checkbox2.setEnabled(false);
} else {
checkbox2.setEnabled(true);
}
return true;
}
});
persistCheckBoxState(switch, checkbox2);
To persist the change when activity is closed, you need to get the preferences references like this and add directly below.
public void persistCheckBoxState (CheckBoxPreference switch, CheckBoxPreference checkbox2) {
if (switch.isChecked ()){
checkbox2.setEnabled(false);
} else {
checkbox2.setEnabled(true);
}
}
Maybe a ListPreference is more what you want. From a usability point of view this would make more sense. When you have to choose one selection out of many this would be the most obvious way to do it. See this post for further instructions
For the application I am working on, I need to have a preference screen, which has a EditTextPreference, SwitchPreference and a VolumePreference. I am using the VolumePreference as I need a preference that is set with a slider, and VolumePreference was the only one I could find that fit the bill. Here is my Preference XML:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:capitalize="words"
android:defaultValue="#string/pref_default_channel"
android:inputType="number"
android:key="pref_channel"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="#string/pref_title_channel"
android:summary="#string/pref_summary_channel"/>
<SwitchPreference
android:key="pref_customVol"
android:title="#string/pref_title_custom_vol"
android:summary="#string/pref_summary_custom_vol"
android:defaultValue="false" />
<VolumePreference
android:name="Volume Preference"
android:title="Notification Volume"
android:summary="Set your notification volume, so you will be notified when your Seahorse is almost finished running"
android:key="pref_notifVolPref"
android:dependency="pref_customVol"/>
I am able to get the value set by the SwitchPreference easily from shared preferences, using the code:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean customVol = sharedPref.getBoolean("pref_customVol", false);
However, when I try to do the same to get the value from my VolumePreference, it always returns the default value of -1. Here is the code I use to retrieve the volume preference:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
int vol = sharedPref.getBoolean("pref_notifVolPref", -1);
Am I using the VolumePreference incorrectly? Do I need to create my own custom preference to display a slider preference? Has anyone had this issue before? Thanks
first extends PreferenceActivity
second add this to onCreate()
addPreferencesFromResource(R.xml.account_preferences);
Preference checkPreference = getPreferenceScreen().findPreference("checkbox_contacts_sync");
Preference.OnPreferenceChangeListener lis1 = new Preference.OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object o)
{
Toast.makeText(SystemManager.getAppContext(), "yess", Toast.LENGTH_LONG).show();
return true;
}
};
checkPreference.setOnPreferenceChangeListener(lis1);
and add this to layout
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:id="#android:id/list">
</ListView>
Or in main activity use this.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener shListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key)
{
Assistance.print("change");
Toast.makeText(SystemManager.getAppContext(),"ohh",Toast.LENGTH_LONG).show();
}
};
sharedPreferences.registerOnSharedPreferenceChangeListener(shListener);
I´m having trouble with setting preferences in my app.
In the main layout I have the button to open the settings layout:
Button btnPreferences = (Button) findViewById(R.id.btnPreferences);
btnPreferences.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent("com.absolutkarlos.AppPreferenceActivity");
startActivity(i);
}
});
Then, it open the PreferenceActivity:
public class AppPreferenceActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//--load the preferences from an XML file---
addPreferencesFromResource(R.xml.user_references);
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="True of False"
android:key="checkboxPref" />
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<EditTextPreference
android:summary="Enter a string"
android:defaultValue="#string/food"
android:title="Edit Text"
android:key="editTextPref"
android:name="#string/name"/>
<RingtonePreference
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref"
android:name="Ringtone Preference" />
<PreferenceScreen
android:title="Second Preference Screen"
android:summary=
"Click here to go to the second Preference Screen"
android:key="secondPrefScreenPref" >
<EditTextPreference
android:summary="Enter a string"
android:title="Edit Text (second Screen)"
android:key="secondEditTextPref"
android:name="EditText" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
Everything looks like its going to work ok, but when I test it, don´t save the string I want it to save.
I Mean, I click the setting button, open the setting layout, I write a text on the EditTextPreference call NAME, but it doesn´t save it, instead the LogCat: sendUserActionEvet() mView == null
So, what I´m doing wrong? Did I miss a step? or forgot to add something?
Basically, I just want to user write his name as part of the settings, this name will be shown at the main layout as a big title. The user can write a nickname if he want. It´s just a string that the app must remember always.
Thanks for your help...
As you might have read, the message:
LogCat: sendUserActionEvet() mView == null
can be ignored on S4 devices.
You need read the value of Preference, and change it, for his title, on your AppPreferenceActivity, set onResume method:
#Override
public void onResume(){
super.onResume();
EditTextPreference preference = (EditTextPreference) findPreference("secondEditTextPref");
preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setTitle(newValue.toString());
return true;
}
});
String name = preference.getText();
if(name != null)
preference.setTitle(name);
}
Also, you must remove addPreferencesFromResource method, because is deprecated. You should use onBuildHeaders method. Here you can see an example of PreferenceActivity.
I tried to solve my problem so i changed so much code. I change even title of the post.
I can change the color of imageview background in preferences ui successfully. But after leaving fragment and launch again, the ui can not be updated in the same way as before.
First of all, I use sherlockactionbar . There are 3 tabs . when 3rd bar is pressed, a fragment is , including buttons, is loaded. When one of button is pressed, another preference fragment is loaded.
The code below shows how to call preference fragment when one of the button is pressed :
SettingsMenuFragment.java
public class SettingsMenuFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button ICSbutton= (Button) view.findViewById(R.id.CallSearchSettingsButton);
ICSbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
clearFragmentStack();
SettingsIncomingSearchFragment removeSISF = (SettingsIncomingSearchFragment) getActivity().getSupportFragmentManager().findFragmentByTag("SISF");
if(removeSISF != null)
{
getActivity().getSupportFragmentManager().beginTransaction().remove(removeSISF).commit() ;
getActivity().getSupportFragmentManager().executePendingTransactions();
}
SettingsIncomingSearchFragment Prefrag = new SettingsIncomingSearchFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, Prefrag ,"SISF");
transaction.addToBackStack(null);
transaction.commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
}
} );}}
and the code below shows preferencefragment :
public class SettingsIncomingSearchFragment extends PreferenceListFragment implements SharedPreferences.OnSharedPreferenceChangeListener,PreferenceListFragment.OnPreferenceAttachedListener {
Context ctx ;
public static final String SHARED_PREFS_NAME = "settings";
LinearLayout mainlayout ;
LinearLayout sublayout ;
View view ;
Preference myPref ;
ImageView img ;
SharedPreferences sp ;
#Override
public void onCreate(Bundle icicle) {
ctx = getActivity() ;
super.onCreate(icicle);
addPreferencesFromResource(R.xml.pref_incomingsearchsettings);
myPref = (Preference) findPreference("incomingsearchbackgroundcolor");
setColor() ;
myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
HSVColorPickerDialog cpd = new HSVColorPickerDialog( ctx, 0xFF4488CC, new OnColorSelectedListener() {
#Override
public void colorSelected(Integer color)
{
sp.edit().putString("incomingsearchbackgroundcolor", String.valueOf(color)).commit();
}
});
cpd.setTitle( "Pick a color" );
cpd.show();
return true ;
}
});
}
private void setColor() {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.rectangle_layout, null);
mainlayout = (LinearLayout)view.findViewById(R.id.rectangle_main_layout_ll);
sublayout = (LinearLayout)mainlayout.findViewById(R.id.rectangle_layout_ll);
sp = ctx.getSharedPreferences(SHARED_PREFS_NAME, ctx.MODE_PRIVATE);
String defValue = null ;
defValue = sp.getString("incomingsearchbackgroundcolor", null);
img = (ImageView)sublayout.findViewById(R.id.iv_priority);
img.setBackgroundColor(Integer.parseInt(defValue));
}
#Override
public void onPreferenceAttached(PreferenceScreen root, int xmlId) {
// TODO Auto-generated method stub
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if(key.equals("incomingsearchbackgroundcolor"))
{
sp = ctx.getSharedPreferences(SHARED_PREFS_NAME, ctx.MODE_PRIVATE);
String defValue = null ;
defValue = sp.getString("incomingsearchbackgroundcolor", null);
Log.d("Debug", defValue);
int iColor = Integer.parseInt(defValue);
img.setBackgroundColor(iColor);
img.invalidate();
if(this.isAdded())
{
getActivity().getSupportFragmentManager().beginTransaction().detach(this).commit() ;
getActivity().getSupportFragmentManager().executePendingTransactions();
getActivity().getSupportFragmentManager().beginTransaction().attach(this).commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
}
}
}
#Override
public void onResume()
{
super.onResume();
sp.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
sp.unregisterOnSharedPreferenceChangeListener(this);
}
}
and this is preference xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:summary = "Options" android:title = "OPTIONS" android:key="options">
<CheckBoxPreference android:key="IncomingCallSearch" android:summary="On/Off" android:title="Enable Incoming Call Search" android:defaultValue="true"/>
</PreferenceCategory>
<PreferenceCategory android:summary = "Screen Settings" android:title = "Screen settings" android:key="ScreenSettings" >
<ListPreference
android:entries="#array/screenLocOptions"
android:entryValues="#array/screenLocValues"
android:key="incomingcallsearch_screenlocation"
android:title="Location"
android:defaultValue="Top"/>
<Preference
android:defaultValue="0xFF000000"
android:key="incomingsearchbackgroundcolor"
android:title="Background Color"
android:layout="#layout/rectangle_layout" />
</PreferenceCategory>
and this is the rectangle_layout 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="wrap_content"
android:padding="5dp"
android:id="#+id/rectangle_main_layout_ll">
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Background color"
android:layout_weight= "0.9"/>
<LinearLayout
android:layout_width="50dp"
android:layout_height="50dp"
android:orientation="vertical"
android:layout_weight= "0.1"
android:id="#+id/rectangle_layout_ll">
<ImageView
android:id="#+id/iv_priority"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
/>
</LinearLayout>
As i wrote previous version of this post, the code above runs successfully in the first the the fragment loaded, imageview background color updated in preferences ui. I try to write failure condition step by step :
1 . I select the 3rd bar from actionbar and a fragment loaded including buttons.2 . I press the button that loads preferences fragment(you can see the code above)
3 . In this preferencefragment, there is a preference including textview and imageview(you can see the details above)
4 . When i click this preference, a color picker ran.(you can see the details above)
5 . I choose a color from color picker and save it to sharedpreference.(you can see the details above)
6 . onsharedpreferencechanged event triggered and i change the background color of imageview(you can see the details above) succesfully.
7 . I leave fragment with choosing another tab from action bar or with using backpress button.
8 . I launch same fragment with pressing same button in 3rd bar.
9 . I again use color picker and onsharedpreferencechanged event is triggered.
10 . I can see with debugging that true color code is taken from sharedpreference and it is set to imageview background color and the code below is run :
getActivity().getSupportFragmentManager().beginTransaction().detach(this).commit() ;
getActivity().getSupportFragmentManager().executePendingTransactions();
getActivity().getSupportFragmentManager().beginTransaction().attach(this).commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
11 . But preference is not updated in this time. The old color or black is seen in imageview.
Thank you very much
getSupportFragmentmanager().detach(this).attach(this).commit()
All the changes cumming only after the commit. So if you will call detach(this) and attach(this) without a commit at the middle you changed nothing.
Try doing some thing like this:
getSupportFragmentmanager().detach(this).commit();
getSupportFragmentmanager().attach(this).commit();
This is what stays behind the commit idea.
P.S
I did not found FragmentManager.detach() method in the API...
at last i solved the problem and it is really simple . I hope this post helps anyone who has problem with dynamic preference updating.
public class SettingsIncomingSearchFragment extends PreferenceListFragment
implements SharedPreferences.OnSharedPreferenceChangeListener,
PreferenceListFragment.OnPreferenceAttachedListener {
Context ctx ;
public static final String SHARED_PREFS_NAME = "settings";
<-- Begin : i delete these global variables and define them in methods locally and
set the values in methods -->
LinearLayout mainlayout ;
LinearLayout sublayout ;
View view ;
Preference myPref ;
ImageView img ;
SharedPreferences sp ;
<-- End : i delete these global variables and define them in methods locally and
set the values in methods -->
I have used PreferenceActivity to have preference in my android application. I want one preference say "pref 2" to be enabled when other preference say "pref 1" is NOT checked and "pref 2" to be disabled when "pref 1" is checked.
i.e. exactly opposite of the android:dependancy attribute.
How can I do that?
Yes it's possible to do this out of the box.
Let's say you want to disable pref2 when pref1 is off
Here's the code(preference xml layout) to put in for pref1:
<CheckBoxPreference
android:title="Pref1"
android:key="pref1">
</CheckBoxPreference>
Here's the code(preference xml layout) to put in for pref2:
<EditTextPreference
android:dialogMessage="Pref 2 dialog"
android:title="Pref2"
android:key="pref2"
android:dependency="pref1">
</EditTextPreference>
Like sigmazero13 said, by default disableDependentsState is false so you don't need to include it in the pref1 attributes.
According to the docs here, you can add an attribute to the CheckBoxPreference tag like so:
android:disableDependentsState="true"
By default this is false, which means that the dependents are disabled when the checkbox is unchecked, but by setting it to true, it should have the opposite effect.
I don't think there's any out-of-the-box solution for it, i.e. an inverted dependancy attribute. But there's always the click-listener:
preference1.setOnPreferenceClickListener(pref1_click);
....
private OnPreferenceClickListener pref1_click = new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
preference2.setEnabled(!preference1.isChecked());
return true;
}
}
Android CheckBox??
I am assuming you are using the Android.widget.checkBox:
http://developer.android.com/reference/android/widget/CheckBox.html
Try this
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkbox_id);
if (checkBox1.isChecked()) {
checkBox2.setChecked(false);
}
}
}
GoodLUCK!!