Preference with custom layout not clickable - android

I'm new to android development. I have created a PreferenceFragment. there is a button(Preference) bottom of the page.after adding the custom layout to the button, the button is not clickable. But outside the button(within preference is clickable) please help me to solve this issue
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="#string/header_user_detail"
android:title="YOUR DETAIL">
<EditTextPreference
android:key="user_name"
android:title="#string/user_name"></EditTextPreference>
<com.empite.oneonus.helpers.custom_preferences.DatePreference
android:key="dob"
android:title="#string/date_of_birth"></com.empite.oneonus.helpers.custom_preferences.DatePreference>
<EditTextPreference
android:key="work_postcode"
android:title="#string/work_postcode"></EditTextPreference>
<EditTextPreference
android:key="home_postcode"
android:title="#string/home_postcode"></EditTextPreference>
<ListPreference
android:dialogTitle="Application language"
android:key="work_category"
android:summary="Select the Application language"
android:title="Language"></ListPreference>
<Preference
android:key="update_profile_key"
android:layout="#layout/update_profile_btn"></Preference>
<Preference
android:key="button"
android:summary="This will act like a button"
android:title="Acts like a button" />
</PreferenceCategory>
<PreferenceCategory
android:key="#string/header_user_account"
android:title="YOUR ACCOUNT">
<EditTextPreference
android:key="edit_email"
android:layout="#layout/edit_email_address"></EditTextPreference>
<EditTextPreference
android:key="edit_password"
android:layout="#layout/edit_password"></EditTextPreference>
</PreferenceCategory>
layout/update_profile_btn
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/update_profile_btn"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="10dp"
android:background="#color/btn_light_green_color"
android:focusable="false"
android:text="Update Profile"
android:textAllCaps="false"
android:textColor="#color/white"></Button>
public class UpdateProfilePrefFragment extends com.github.machinarius.preferencefragment.PreferenceFragment implements Preference.OnPreferenceClickListener {
protected static void setListPreferenceData(ListPreference lp) {
CharSequence[] entries = {"English", "French"};
CharSequence[] entryValues = {"1", "2"};
lp.setEntries(entries);
lp.setDefaultValue("1");
lp.setEntryValues(entryValues);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.update_profile);
final ListPreference listPreference = (ListPreference) findPreference("work_category");
setListPreferenceData(listPreference);
listPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
setListPreferenceData(listPreference);
return false;
}
});
Preference pref = findPreference("update_profile_key");
pref.setOnPreferenceClickListener(this);
Preference button = (Preference) findPreference("button");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
Toast.makeText(getActivity(), "button", Toast.LENGTH_SHORT).show();
return true;
}
});
}
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
return false;
}
}

Your button custom preference does not specify a layout. You may need to specify a layout and set android:focusable="false". See Custom preference not clickable
Edit: For the #layout/update_profile_btn file, you may try the following modifications:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false">
<Button
android:id="#+id/update_profile_btn"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="10dp"
android:background="#color/btn_light_green_color"
android:onClick="onButtonClick"
android:text="Update Profile"
android:textAllCaps="false"
android:textColor="#color/white"></Button>
</RelativeLayout>
and define the method
void onButtonClick(View v) {
Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
}

Related

How to reach Custom Preferences items from Fragment?

In my application Settings Layout i need custom preference for profile Category. I searched and done something .
pref.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Profil">
<Preference
android:key="custom"
android:title="My Custom Preferenece"
android:layout="#layout/custom">
</Preference>
<Preference
android:icon="#drawable/transparency"
android:key="email"
android:selectable="false"
android:summary=""
android:title="Email"
/>
custom.xml (i used for preference layout)
<?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="50dp"
android:background="#android:color/white"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
>
<android.support.v7.widget.AppCompatImageView
android:id="#+id/custom_image"
android:layout_width="100dp"
android:layout_height="50dp"
android:src="#drawable/no_photo"
android:textColor="#color/black"
/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/custom_text"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Custom Text"
android:textColor="#color/black"
android:gravity="center"
/>
</LinearLayout>
I want to reach and set android:id="#+id/custom_image" or android:id="#+id/custom_text" , i didn't reach these items from my fragment.
How can i reach these items from fragment ?
Thank you
My fragment
public class GeneralPreferenceFragmentN extends PreferenceFragment {
private Context mContext;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_main);
mContext = getActivity().getApplicationContext();
bindPreferenceSummaryToValue(findPreference("phone"));
private static void bindPreferenceSummaryToValue(Preference preference)
{
preference.setOnPreferenceChangeListener(
sBindPreferenceSummaryToValueListener);
SharedPreferences prefs = preference.getSharedPreferences();
Object value;
if (preference instanceof MultiSelectListPreference) {
value = prefs.getStringSet(preference.getKey(), new HashSet<String>
());
} else {
value = prefs.getString(preference.getKey(), "");
}
..................
Try this:
in your onCreate() initialize the view:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_abschliessen_einsatz, container, false);
//#INFO: Create a global View v element if you want to use the view in other funtions (for example on slected and so on). Otherwise just use
this.v = v;
//#INFO: Otherwise just use th View elemnt to to find by ID
myCustomImage = (AppCompatImageView) v.findViewById(R.id.custom_image);
myCustomText = (AppCompatTextView) v.findViewById(R.id.custom_text);
//Set Text or do stuff with the elements afterwards
return v;
}
//Use the view in other fuctions, ex. onSelcted
#Override
public void onSelected() {
//update UI when selected
//#INFO: Use the global View elemnt to to find by ID
myCustomImage = (AppCompatImageView) v.findViewById(R.id.custom_image);
myCustomText = (AppCompatTextView) v.findViewById(R.id.custom_text);
//Set Text or do stuff with the elements afterwards
}

Problems with UnregisterOnSharedPreferenceChangeListener in android

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.

How to add a Progress Bar in a PreferenceFragment in Android?

How can I add a progress bar in a PreferenceFragment? I have some async task running that will display some values in my preference upon completion. So while it is doing the background process, I plan to show only a progress bar in the center. After the task is complete, then I plan to show all my preferences.
Here's what I have so far.
PreferenceFragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_account);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void,Void,Void>() {
String firstName, lastName, email;
#Override
protected void doInBackground() {
// Doing something here to fetch values
}
#Override
protected void onPostExecute() {
findPreference("first_name").setSummary(firstName);
findPreference("last_name").setSummary(lastName);
findPreference("email").setSummary(email);
}
}
}
pref_account.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference android:key="first_name"
android:title="#string/prompt_first_name"
android:summary="" />
<Preference android:key="last_name"
android:title="#string/prompt_last_name"
android:summary="" />
<Preference android:key="email"
android:title="#string/prompt_email"
android:summary=""
android:inputType="textEmailAddress" />
<Preference android:key="sign_out"
android:title="#string/action_sign_out" />
</PreferenceScreen>
My question is, since this is a PreferenceFragment and I'm not overriding the method onCreateView, where and how should I add the progress bar?
Here's what I did:
Create a custom Preference class:
public class LoadingPreference extends Preference {
public LoadingPreference(Context context){
super(context);
setLayoutResource(R.layout.preference_loading_placeholder);
}
}
Create a custom Layout (preference_loading_placeholder) while preserving the Preference layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingEnd="?android:attr/scrollbarSize"
android:background="?android:attr/selectableItemBackground" >
<ImageView
android:id="#+android:id/icon"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dip"
android:layout_marginEnd="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="6dip"
android:layout_weight="1">
<!-- (start) I added this part. -->
<ProgressBar
android:id="#+id/progressBar"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminateTintMode="src_atop"
android:indeterminateTint="#color/colorAccent"
android:layout_gravity="center" />
<TextView
android:id="#+id/progressTitle"
android:text="#string/loading"
android:textSize="24sp"
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_toLeftOf="#+id/progressBar" />
<!-- (end) I added this part. -->
<TextView android:id="#+android:id/title"
android:layout_width="0dp"
android:layout_height="0dp"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:ellipsize="marquee"
android:fadingEdge="horizontal" />
<TextView android:id="#+id/summary"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#android:id/title"
android:layout_alignStart="#android:id/title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary"
android:maxLines="4" />
</RelativeLayout>
<!-- Preference should place its actual preference widget here. -->
<LinearLayout android:id="#+id/widget_frame"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical"/>
</LinearLayout>
Used a PreferenceCategory to hold my loading preference:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:key="#string/pref_key_wifi_enabled"
android:title="#string/pref_title_wifi_enabled"
android:summary="#string/pref_summary_wifi_enabled" />
<Preference
android:key="#string/pref_key_wifi_refresh"
android:title="#string/pref_title_wifi_refresh"
android:summary="#string/pref_summary_wifi_refresh"
android:dependency="#string/pref_key_wifi_enabled"/>
<PreferenceCategory
android:key="#string/pref_key_wifi_section"
android:title="#string/pref_title_wifi_section"
android:summary="#string/pref_summary_wifi_section"
android:dependency="#string/pref_key_wifi_enabled"/>
</PreferenceScreen>
Put the loading preference where needed
((PreferenceCategory)findPreference(WIFI_OPTIONS_SECTION_KEY)).addPreference(new LoadingPreference(getActivity()));
Remove the loading preference after loading is complete:
((PreferenceCategory)findPreference(WIFI_OPTIONS_SECTION_KEY)).removeAll();
Add other preferences after loading is complete:
Preference p = new Preference(getActivity());
p.setTitle("...");
p.setSumary("...")
((PreferenceCategory)findPreference(WIFI_OPTIONS_SECTION_KEY)).addPreferece(p);
I had a similar use case and I used a custom layout for the preference.
In the preference fragment file I had (non relevant attributes are omitted)
<!-- res/xml/somePref.xml -->
<PreferenceScreen>
<PreferenceCategory>
...
<Preference android:widgetLayout="#layout/customLayout" />
...
</PreferenceCategory>
</PreferenceScreen>
Then in the custom layout I placed the progress bar by itself
<!-- res/layout/customLayout.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/progress"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminateOnly="true" />
</RelativeLayout>
Before starting the async task I call
findViewById(R.id.progress).setVisibility(View.VISIBLE)
and when the task is done I set the visibility back to gone. This will allow you to set each preference independently without having to wait for each one to complete. Hope this helps.
I ended up using the following approach.
In my fragment_account.xml layout file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
</RelativeLayout>
Then on my class:
public class AccountFragment extends PreferenceFragment {
private ListView mListView;
private ProgressBar mProgressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_account, container, false);
mListView = (ListView) view.findViewById(android.R.id.list);
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
showProgress();
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
addPreferencesFromResource(R.xml.pref_account);
hideProgress();
}
private void showProgress() {
mListView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
}
private void hideProgress() {
mListView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
}
}
}
You could try to apply the following solution:
Use fragments in your preference activity.
When you need to display preferences - display preference fragment.
When you need to display progress - display progress fragment.
Here is a code excerpt:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showPreferences();
// or call showProgress, launch your task and call showPreferences upon completion
}
private void showPreferences() {
runOnUiThread(new Runnable() {
#Override
public void run() {
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new YourPreferenceFragment())
.commit();
}
});
}
private void showProgress() {
runOnUiThread(new Runnable() {
#Override
public void run() {
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new YourProgressFragment())
.commit();
}
});
}
Use this approach. Create one Dialog with a custom layout which a progressBar in it and just call show() and dismiss().
#Synchronized
fun showLoader(activity: Activity) {
val activityWeakReference = WeakReference(activity)
if (activityWeakReference.get() != null) {
hideLoader()
dialog = Dialog(activityWeakReference.get()!!, android.R.style.Theme_Translucent)
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.setContentView(R.layout.progress_indicator)
dialog?.setCancelable(false)
dialog?.show()
}
}
#Synchronized
fun hideLoader() {
dialog?.dismiss()
dialog = null
}
Use the following concept in AsyncTasks default Methods
private class MyAsynTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog();// show your progressbar
}
#Override
protected String doInBackground(String... urls) {
//your code
}
protected void onProgressUpdate(String... progress) {
progressDialog.setProgress(Integer.parseInt(progress[0]));
// here you get the value of progress
}
#Override
protected void onPostExecute(String result) {
dismissDialog(); //dismiss progressbar
}
}

How can I pass a setting preference into a Toast

I have set my Setting activity and my Menu (I did the old way without fragments since Im working on API 10) my Menu got 2 ítems Settings (which goes to the Activity Settings just fine) and Show Settings, this one has to show into a custom Toast the Setting Values. This is my code so far
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.config:
startActivity(new Intent(MainActivity.this,
OpcionesActivity.class
));
return true;
case R.id.mconfig:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));
TextView text = (TextView) layout.findViewById(R.id.text);
TextView text1 = (TextView) layout.findViewById(R.id.text1);
TextView text2 = (TextView) layout.findViewById(R.id.text2);
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
And this is my custom Toast XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/custom_toast_layout_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFF"
android:orientation="horizontal"
android:padding="5dp" >
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#000" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#000" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#000" />
</LinearLayout>
How can I Access to the setting values and what method should I use? .setText();
I have an OpcionesActivity class that looks like this:
public class OpcionesActivity extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
And settings.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="General">
<CheckBoxPreference
android:key="opcion1"
android:title="Sonido"
android:summary="Sonido" />
<EditTextPreference
android:key="opcion2"
android:title="Usuario"
android:summary="Nombre de usuario"
android:dialogTitle="Nombre" />
<ListPreference
android:key="opcion3"
android:title="Dificultad"
android:summary="Dificultad"
android:dialogTitle="Dificultad"
android:entries="#array/d"
android:entryValues="#array/dif" />
</PreferenceCategory>
</PreferenceScreen>
add this before you create a toast
SharedPreferences preferences = getApplication().getSharedPreferences("your prefrens name",MODE_PRIVATE);
text.setText(preferences.getString("key","defaultValue"));
text1.setText(preferences.getString("key","defaultValue"));
text2.setText(preferences.getString("key","defaultValue"));

Unclickable button set on a preference activity

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");
}
}

Categories

Resources