Unclickable button set on a preference activity - android

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

Related

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
}
}

Preference with custom layout not clickable

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

Unable to call methods with a button in PreferenceActivity

This is my first time to use PreferenceActivity.
I have made a simple activity for a settings screen, and when I set up a button in the layout and set the onClickListener for the button, there are no actions nor are there any errors.
All I want to do is to send the user back to the main screen by pressing the button. Is there some error or some setup that I have missed?
The mysterious part is that neither the xml onClick nor the direct method call work. No actions, no errors, it does not even show a Toast (when altered for debugging). Is there anyone who actually used PreferenceActivity and used some widgets like buttons ?
Here is my sample activity for the Settings Screen
public class Settings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//This button doesn't work
Button b = (Button)findViewById(R.id.setupid);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(Settings.this,HomeActivity.class);
startActivity(i);
}
});
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
Here is the xml layout for the Settings.java
<?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="match_parent"
android:layout_height="0dp"
android:layout_weight="5" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3498db"
android:gravity="center"
>
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Set"
android:id="#+id/setupid" />
</LinearLayout>
</LinearLayout>
You didn't have to use the Fragment in the first place. All you have to do is to use addPreferencesFromResource(R.xml.preferences); under setContents View.
public class Settings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//It is depricated but it works
addPreferencesFromResource(R.xml.preferences);
Button b = (Button)findViewById(R.id.setupid);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(Settings.this,HomeActivity.class);
startActivity(i);
}
});
//getFragmentManager().beginTransaction().replace(android.R.id.content, //new MyPreferenceFragment()).commit();
}
}

Set custom title bar in PreferenceAcivity

I am using PreferenceActivity, how can I set a custom title bar? Not only text but background color, size - the whole layout.
PreferenceActivity extends ListActivity, and when you inflate the preferences from xml with addPreferencesFromResource(), it puts the stuff into the standard ListView that ListActivity uses.
So basically, you can use setContentView() to specify a layout, but you need to have a ListView in it with the id "#+android:id/list".
So using kleini's example code:
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.login_settings);
setContentView(R.layout.login_settings_layout);
}
You would need a ListView in login_settings_layout.xml that looks something like:
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
This is the only thing that worked for me. Rest of the above stuff did not fetch desired results on my 4.3 Nexus Tablet.
I could not really recreate a proper actionbar like widget, but was able to put a large 'Settings' title on top of the PreferenceActivity, with below steps.
I got the hint from another stackoverflow answer and am just making it more elaborate.
In PreferenceActivity class (remove the existing titlebar)
public class Settings extends PreferenceActivity· {
...
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); // This goes first
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
In res/xml/settings.xml, I would like to draw attention to the first PreferenceCategory
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:layout="#layout/settings_titlebar" />
<PreferenceCategory android:title="Notifications">
<Preference .....
In res/layout/settings_titlebar.xml
Navals-MacBook-Pro:ver_ui_0.2 Naval$ vi res/layout/settings_titlebar.xml
<?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="wrap_content"
android:orientation="horizontal"
android:background="#drawable/header_background"
android:enabled="false">
<TextView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="#android:color/transparent"
android:padding="4dip"
android:text="Settings"
android:textSize="32sp"
/>
</RelativeLayout>
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
}
}
Ben's method worked out well for me!!. Here is the code
public class PreferenceCustomTitleActivity extends PreferenceActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
/** Customize your background, textsize, cachetint, dividers
for your list view in the xml **/
setContentView(R.layout.layout_with_simple_listview_only);
ListView list = (ListView) findViewById(android.R.id.list);
View preferenceHeader = getLayoutInflater().inflate(
R.layout.preference_header, null);
list.addHeaderView(preferenceHeader);
}
}
Awesome, worked fine for "NO_TITLE":
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.login_settings);
setContentView(R.layout.login_settings_layout);
}
Or like this:
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitlebar);
addPreferencesFromResource(R.xml.preferences);
}
With a customtitlebar.xml like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/customTitleBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/CustomWindowTitle">
</TextView>

Categories

Resources