Ok, I know there have been a lot of questions about SharedPreferences in Android asked before, and I did manage to get quite far, but since I'm kinda new to SharedPreferences I don't know the last few steps to get it to work.
In my MainActivity I have the following:
public class MainActivity extends ActionBarActivity
{
...
// Public static MainActivity so we can use findViewById from MyPrefsActivity
public static MainActivity mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mActivity = this;
}
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id){
case R.id.action_settings:
startActivity(new Intent(this, MyPrefsActivity.class));
return true;
}
return false;
}
}
And this is MyPrefsActivity.java:
package com.example.checkboxoptionsv2;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ImageButton;
public class MyPrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
private static int prefs = R.xml.settings;
private ImageButton cbButton, spinnerButton, popupButton;
private final String LIST_PREFERENCE = "prefCheckboxOption";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
getClass().getMethod("getFragmentManager");
AddResourceApi11AndGreater();
}
catch(NoSuchMethodException e){ // Android API < 11
AddResourceApiLessThan11();
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.registerOnSharedPreferenceChangeListener(this);
* ListPreference listPreference = (ListPreference) findPreference(LIST_PREFERENCE);
if(listPreference.getValue() == null)
listPreference.setValue("0");
cbButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnCheckbox);
spinnerButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnSpinner);
popupButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnPopup);
setChosenPreference(0);
}
private void setChosenPreference(int chosen_value){
// First put all Visibilities on GONE
cbButton.setVisibility(View.GONE);
spinnerButton.setVisibility(View.GONE);
popupButton.setVisibility(View.GONE);
// Then turn the chosen on VISIBLE again
switch(chosen_value){
case 0: // Multi-Click CheckBox
default:
cbButton.setVisibility(View.VISIBLE);
break;
case 1: // Dropdown CheckBox
spinnerButton.setVisibility(View.VISIBLE);
break;
case 2: // Pop-up CheckBox
popupButton.setVisibility(View.VISIBLE);
break;
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(LIST_PREFERENCE)){
ListPreference listPreference = (ListPreference) findPreference(key); // LIST_PREFERENCE
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int chosen_option = Integer.valueOf((String) newValue);
setChosenPreference(chosen_option);
return false;
}
});
}
else{
// Other settings
}
}
#SuppressWarnings("deprecation")
protected void AddResourceApiLessThan11(){
addPreferencesFromResource(prefs);
}
#TargetApi(11)
protected void AddResourceApi11AndGreater(){
* MyPreferenceFragment pf = new MyPreferenceFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, pf).commit();
}
#TargetApi(11)
public static class MyPreferenceFragment extends PreferenceFragment{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
* addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
// private members seem to be visible for inner class, and
// making it static made things so much easier
}
}
}
And the settings.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="#string/checkbox_options_title" >
<ListPreference
android:key="prefCheckboxOption"
android:title="#string/pref_checkbox_option"
android:summary="#string/checkbox_options_summary"
android:entries="#array/checkbox_options"
android:entryValues="#array/checkbox_option_values" />
</PreferenceCategory>
</PreferenceScreen>
and arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="checkbox_options">
<item>CheckBox as Multi-Click</item>
<item>CheckBox as Dropdown</item>
<item>CheckBox as Pop-up</item>
</string-array>
<string-array name="checkbox_option_values">
<item>0</item>
<item>1</item>
<item>2</item>
</string-array>
</resources>
(Of course I've also included the MyPrefsActivity in the AndroidManifest.xml)
My goal is to make one of the three checkbox-option (found in the setChosenPreference method) VISIBLE, and the other two GONE, based on the preference selected in the ListPreference.
Right now the Listpreference in both the onCreate() method and onSharedPreferenceChanged() is null and giving a NullPointerException. So I set some breakpoints (see the three " * ") and the reason they are null is because the third " * " (in the static class PF) isn't called.
The addPreferencesFromResources should be called before using findPreference, otherwise it will return null. Does anyone know why during debugging I do get to the second " * " in the AddResourceApi11AndGreater() method, but I'm not getting to the third one in the MyPreferenceFragment-class onCreate method() ?.. the onCreate isn't called at all..
Also, does the rest of my code seems ok(-ish) or should I change something in order to make it work as I intended?
Thanks in advance for the responses.
TL;DR: MyPreferenceFragment instantion is created successfully, but it's #Override onCreate method is never called.
EDIT 1: Ok, I did found the problem: When I added addPreferencesFromResource(prefs) in the activity's onCreate method as a debug-test, I found out that the MyPreferenceFragment-class is indeed being initialized, then it finishes the activity's onCreate method (which would have failed at findPreference() if I didn't added the addPreferencesFromResource(prefs) test-line), and only after the activity's onCreate method is completely finished, it goes to the MyPreferenceFragment's onCreate method.
Is there a way to let the PreferenceFrament's onCreate method go first, while in the middle of the activity's onCreate method, so after AddResourceApi11AndGreater() but before findPreference(LIST_PREFERENCE)?
Move your logic to PF, don't do things in PreferenceActivity.
There are also changes in the way of listening to the preferences changes. Check the code.
public class MyPrefsActivity extends PreferenceActivity {
private static int prefs = R.xml.settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
getClass().getMethod("getFragmentManager");
AddResourceApi11AndGreater();
}
catch(NoSuchMethodException e){ // Android API < 11
AddResourceApiLessThan11();
}
}
#SuppressWarnings("deprecation")
protected void AddResourceApiLessThan11(){
addPreferencesFromResource(prefs);
}
#TargetApi(11)
protected void AddResourceApi11AndGreater(){
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PF()).commit();
}
#TargetApi(11)
public static class PF extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private ImageButton cbButton, spinnerButton, popupButton;
private final String LIST_PREFERENCE = "prefCheckboxOption";
#Override
public void onCreate(final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
// private members seem to be visible for inner class, and
// making it static made things so much easier
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
preferences.registerOnSharedPreferenceChangeListener(this);
ListPreference listPreference = (ListPreference) findPreference(LIST_PREFERENCE);
if(listPreference.getValue() == null)
listPreference.setValue("0");
cbButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnCheckbox);
spinnerButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnSpinner);
popupButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnPopup);
setChosenPreference(Integer.valueOf(preferences.getString(LIST_PREFERENCE, "0")));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
int chosen_option = Integer.valueOf(sharedPreferences.getString(key, "0"));
setChosenPreference(chosen_option);
}
private void setChosenPreference(int chosen_value){
// First put all Visibilities on GONE
cbButton.setVisibility(View.GONE);
spinnerButton.setVisibility(View.GONE);
popupButton.setVisibility(View.GONE);
// Then turn the chosen on VISIBLE again
switch(chosen_value){
case 0: // Multi-Click CheckBox
default:
cbButton.setVisibility(View.VISIBLE);
break;
case 1: // Dropdown CheckBox
spinnerButton.setVisibility(View.VISIBLE);
break;
case 2: // Pop-up CheckBox
popupButton.setVisibility(View.VISIBLE);
break;
}
}
}
}
Related
I'm trying to display preference screen and with a text box and doesn't show but in another screen it has no problem? It shows a negative 1 or null.
StatsActivity
public class StatsActivity extends Activity {
static final String TAG = "StatsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats_settings_layout);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n" + sharedPrefs.getString("time_usage_key", "-1"));
TextView settingsTextViewStats = (TextView) findViewById(R.id.stats_settings_text_view);
settingsTextViewStats.setText(builder.toString());
}
}
StatsPrefsActivity
public class StatsPrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
static final String TAG = "StatsPrefsActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_stats);
PreferenceManager.setDefaultValues(this,R.xml.preferences_stats, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(Menu.NONE, 0, 0, "Show current settings");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, StatsActivity.class));
return true;
}
return false;
}
#Override
public void onStart(){
super.onStart();
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(StatsPrefsActivity.this);
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
}
}
preference_stats.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Settings"
android:key="first_category">
<EditTextPreference
android:id="#+id/text_pref_box"
android:key="time_usage_key"
android:title="7 Day Usage"
android:summary="A total of usage of 7 days." />
</PreferenceCategory>
</PreferenceScreen>
if you want an inital value then set one. right now you have "-1" set as the default value. so if the preference has never been used before your going to get "-1" as the default. Try changing that to a blank string "" or something if you want better presentation.
I implemented a bottom button bar(something like a tab bar controller in iPhone). For this I created a common layout (button_bar.xml, 5 image buttons) and included in other activity xml files. and for the managing the click action I created a BaseActivity.java extended from Activity and perform the click actions. and I extend other activity which need button bar from this BaseActivity, which works fine. Now I want to include a selected state to these buttons, but when I access the buttons in base activity it give a null pointer error. How can I solve this.
button_bar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/bottomButtonBar"
style="#android:style/ButtonBar"
... >
<ImageButton
android:id="#+id/btnGuests"
android:onClick="showAllGuests"
android:src="#drawable/ic_guest_list" />
<ImageButton
android:id="#+id/btnAddGuest"
android:onClick="selectGuestType"
android:src="#drawable/ic_add_guest" />
<ImageButton
android:id="#+id/btnAddParty"
android:onClick="showAddParty"
android:src="#drawable/ic_add_party" />
....
</LinearLayout>
public class BaseActivity extends Activity {
// common to other activities.
public void showAddParty(View view) {
//showAddParty is one one of the buttons click method. 4 more buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
// I can get "view.findViewById(R.id.btnAddParty)" here
// but I can't get "findViewById(R.id.btnAddGuest)" here. how this possible
}
}
public class AddPartyActivity extends BaseActivity{
....
}
Here i can get the corresponding view from parameter view, and change backgroundIbageSource. but when it goes to "AddPartyActivity" that inherited from Baseactivity, the new image is replaced by old one. How can I implement the selected feature in BaseActivity itself?
you can hold the state of the Button(clicked or not) using booloean in BaseActivity and check the value of these variables in AddPropertyActivity's onCreate() method.
public class BaseActivity extends Activity {
protected static boolean isButton1Clicked = false;
protected static boolean isButton2Clicked = false;
protected static boolean isButton3Clicked = false;
protected static boolean isButton4Clicked = false;
.....
public void showAddParty(View view) {
isButton1Clicked = true;
//showAddParty is one one of the buttons click method. 4 more buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
}
}
public class AddPartyActivity extends BaseActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
Button button1 = (Button)findViewById(R.id.button1);
if(isButton1Clicked) {
button1.setBackground(R.drawable.clicked);
} else {
button1.setBackground(R.drawable.not_clicked);
}
......
......
}
}
and remember that all boolean variables must be static variables. (every object will have it's own copy of instance variables but all objects will share a single copy of static members).
public class BaseActivity extends Activity {
protected static boolean isButton1Clicked = false;
protected static boolean isButton2Clicked = false;
protected static boolean isButton3Clicked = false;
protected static boolean isButton4Clicked = false;
protected Button button1;
protected Button button2;
protected Button button3;
protected Button button4;
protected void checkButtonsState() {
if (isButton1Clicked) {
button1.setBackgroundResource(R.drawable.image1);
} else {
button1.setBackgroundResource(R.drawable.image2);
}
..........
}
public void showAddParty(View view) {
isButton1Clicked = true;
// showAddParty is one one of the buttons click method. 4 more
// buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
}
}
public class AddPartyActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.item1);
.....
checkButtonsState();
}
}
Your error come from because you are using view.findViewById(), but the view variable correspond of the object that catch the click event (look in your xml, the 'android:onClick="showAddParty"').
So, you have in parameter a view instance that point directly to the btnAddParty button.
Is why you can access with findViewById to btnAddParty id but not btnAddGuest id.
You can access to all the view hierarchy by using direct findViewById as method of the activity class:
View btAddParty = findViewById(R.id.btnAddParty)
View btAddGuest = view.findViewById(R.id.btnAddGuest)
Now, you can have a full solution, by implement a special method (setMyInternalContent in the sample below) in the BaseActivity and keep an instance of each button, after, you just have to update there state on click action:
public class BaseActivity extends Activity {
protected Button mBtAddParty;
protected Button mBtAddGuest;
// ...
protected void setMyContentView(int resId) {
setContentView(resId);
mBtAddParty = (Button)findViewById(R.id.btnAddParty);
mBtAddParty = (Button)findViewById(R.id.btnAddGuest);
// ...
}
public void showAddParty(View view) {
mBtAddParty.setClickable(true);
mBtAddGuest.setClickable(false);
// ...
//showAddParty is one one of the buttons click method. 4 more buttons are there
Intent intent = new Intent(this, AddPartyActivity.class);
startActivity(intent);
}
}
public class AddPartyActivity extends BaseActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setMyContentView(R.layout.activity_layout);
// Do not forget to set initial button state:
mBtAddParty.setClickable(true);
mBtAddGuest.setClickable(false);
// ...
}
}
I had the getpreferencescreen deprecated so I tryed to implement the header preference activity.
here is my code:
public class EditPreferences extends PreferenceActivity {
ListPreference m_list_preference_dive_centre_rating;
ListPreference m_list_preference_dive_region_rating;
ListPreference m_list_preference_wreck;
ListPreference m_list_preference_cave;
MultyChoiceListPlugin m_list_preference_marine_life;
ListPreference m_list_preference_region;
Preference m_order_by_name;
SharedPreferences.Editor m_editor;
static Context m_context;
int m_order_type_val = 0;
boolean m_wreck_selected = false;
boolean m_cave_selected = false;
boolean m_marine_life_selected = false;
boolean m_region_selected = false;
int number_click_wreck = 0;
int number_click_cave = 0;
int number_click_marine_life = 0;
int number_click_region = 0;
boolean m_without_guide_selected = false;
boolean m_without_equipment_selected = false;
boolean m_budget_selected = false;
boolean m_region_rating = false;
boolean m_centre_rating = false;
private ListView m_preferenceView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//m_order_by_name.setOnPreferenceClickListener(onOrderByNamePrefClick);
final Button back_btn = (Button)this.findViewById(R.id.back);
final Button home_btn = (Button)this.findViewById(R.id.home);
//final Button search_btn = (Button)this.findViewById(R.id.search);
final Button info_btn = (Button)this.findViewById(R.id.info);
back_btn.setOnClickListener(onBackBtn);
home_btn.setOnClickListener(onHomeBtn);
// search_btn.setOnClickListener(onSearchBtn);
info_btn.setOnClickListener(onInfoBtn);
}
/**
* Populate the activity with the top-level headers.
*/
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
public static class Prefs1Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.wrap_preferences);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.layout.wrap_preferences, false);
addPreferencesFromResource(R.xml.preferences1);
}
}
public static class Prefs2Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences2);
}
}
public static class Prefs3Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
// PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences3);
}
}
private View.OnClickListener onBackBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","last_from");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
private View.OnClickListener onHomeBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
//set the result to the callback of the parent activitie
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","home");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
I've got the error:No view found for id 0x1020343 (android:id/prefs) for fragment
XML code pref_headers.xml:
<?xml version="1.0" encoding="UTF-8"?>
<preference-headers
xmlns:android="http://schemas.android.com/apk/res/android" >
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs1Fragment"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs2Fragment"
android:title="#string/what_is_your_budget_text"
android:summary="#string/what_is_your_budget_summary" >
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs3Fragment"
android:title="#string/order_by_name_title"
android:summary="#string/order_by_name_summary">
</header>
<!-- <header
android:icon="#drawable/icon_question"
android:title="Blackmoon Info Tech Services"
android:summary="link to BITS blog">
<intent android:action="android.intent.action.VIEW"
android:data="http://www.blackmoonit.com/2012/07/all_api_prefsactivity/" />
</header>
-->
XML code preferences1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
<PreferenceCategory
android:title="#string/who_is_the_best_dive_centre_text"
android:key="who_is_the_best_dive_centre_category">
<ListPreference
android:key="select_dive_centre_rating"
android:title="#string/select_dive_centre_rating_text"
android:summary="#string/select_dive_centre_rating_summary"
android:entries="#array/search_dive_centre_names"
android:entryValues="#array/search_dive_centre_clauses"
android:dialogTitle="#string/search_dive_centre_choice_title"/>
</PreferenceCategory>
</PreferenceScreen>
thanks in advance
The official documentation is misleading:
Removing the onCreate function in public class EditPreferences extends PreferenceActivity resolves the issue.
I just moved what was in onCreate to onBuildHeaders function.
I was having this problem too, until I realized that I had specified the wrong layout in setContentView() of the onCreate() method of the FragmentActivity.
The id passed into FragmentTransaction.add(), in your case R.id.feedContentContainer, must be a child of the layout specified in setContentView().
You didn't show us your onCreate() method, so perhaps this is the same problem.
I want write code once and use in different activities. I have created a Base Activity class for that . Also the header of all the layouts in different activities are same. I have done that with the help of the <include layout > tag.
Now the Problem is my BaseActivity code is not running. I am trying this first time se don't have much idea about that.
1.)The BaseActivity code is below :
package com.waheguru.app;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public abstract class BaseActivityMenu extends Activity {
//action id
private static final int ID_UP = 1;
private static final int ID_DOWN = 2;
private static final int ID_SEARCH = 3;
private static final int ID_INFO = 4;
private static final int ID_ERASE = 5;
private static final int ID_OK = 6;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.header);
ActionItem nextItem = new ActionItem(ID_DOWN, "Book", getResources().getDrawable(R.drawable.menu_down_arrow));
ActionItem prevItem = new ActionItem(ID_UP, "Bookmark", getResources().getDrawable(R.drawable.menu_up_arrow));
ActionItem searchItem = new ActionItem(ID_SEARCH, "Find", getResources().getDrawable(R.drawable.menu_search));
ActionItem infoItem = new ActionItem(ID_INFO, "Info", getResources().getDrawable(R.drawable.menu_info));
ActionItem eraseItem = new ActionItem(ID_ERASE, "Clear", getResources().getDrawable(R.drawable.menu_eraser));
ActionItem okItem = new ActionItem(ID_OK, "OK", getResources().getDrawable(R.drawable.menu_ok));
//use setSticky(true) to disable QuickAction dialog being dismissed after an item is clicked
prevItem.setSticky(true);
nextItem.setSticky(true);
//create QuickAction. Use QuickAction.VERTICAL or QuickAction.HORIZONTAL param to define layout
//orientation
final QuickAction quickAction = new QuickAction(this, QuickAction.VERTICAL);
//add action items into QuickAction
quickAction.addActionItem(nextItem);
quickAction.addActionItem(prevItem);
quickAction.addActionItem(searchItem);
quickAction.addActionItem(infoItem);
quickAction.addActionItem(eraseItem);
quickAction.addActionItem(okItem);
//Set listener for action item clicked
quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
public void onItemClick(QuickAction source, int pos, int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
//here we can filter which action item was clicked with pos or actionId parameter
if (actionId == ID_SEARCH) {
Toast.makeText(getApplicationContext(), "Let's do some search action", Toast.LENGTH_SHORT).show();
} else if (actionId == ID_INFO) {
Toast.makeText(getApplicationContext(), "I have no info this time", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), actionItem.getTitle() + " selected", Toast.LENGTH_SHORT).show();
}
}
});
//set listnener for on dismiss event, this listener will be called only if QuickAction dialog was dismissed
//by clicking the area outside the dialog.
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed", Toast.LENGTH_SHORT).show();
}
});
Button books=(Button)findViewById(R.id.book);
books.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(ExampleActivity.this,List_of_books.class);
startActivityForResult(intent, 0);
}
});
//show on btn1
Button btn1 = (Button) this.findViewById(R.id.menu);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
}
}
2.) The Activity extended the Base Activity
package com.waheguru.app;
import android.app.Activity;
import android.os.Bundle;
public class ABCActivity extends BaseActivityMenu {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
}
}
So can any one help me where I am doing something wrong.
For this you have to create one header.xml which will be included in each and every layout for your activities as follows
header.xml
<RelativeLayout>
<TextView android:id="#+id/txtHeading"
.... />
</RelativeLayout>
activity_main.xml
<RelativeLayout>
<!-- include your header here -->
<include layout="#layout/header"
... />
<!-- Rest of your views -->
</RelativeLayout>
BaseActivity
abstract class BaseActivity extends Activity {
protected TextView txtHeading;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void setHeading(int resId) {
if(txtHeading == null)
txtHeading = findViewById(R.id.txtHeading);
if(txtHeading != null)
txtHeading.setText(resId);
}
}
MainActivity
class MainActivity extends BaseActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setHeading(R.string.heading_main);
}
}
You can put as many views you want and manage common things in BaseActivity or BaseListActivity.
If you are making inheritance with activities and your base activity calls setContentView and after that the real activity calls setContentView the last call will set the layout for activity. So if you are looking for a solution where all activies have the same header component the are 2 ways.
For each activity layout xml you include that component
-You make function for baseActivity e.g. setContent(int layout_id)
-You call that with your activity always.
-Baseactivity inflates a root view with header and inflates layout_id view to that layout.
-Then calls the actual setContentView with that component.
I think you should achieve it using Fragment, this may helps you.
1 - in main.xml, add:
<fragment
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
class="com.package.name.HeaderPanel" />
//remaining is same
2 - the BaseActivity which extends FragmentActivity:
public class BaseActivityMenu extends FragmentActivity {
private static final String TAG = Default.class.getName() + " - ";
private int mResLayoutId;
public void onCreate(Bundle savedInstanceState, int resLayout){
super.onCreate(savedInstanceState);
setContentView(resLayout);
mResLayoutId = resLayout;
switch(mResLayoutId){
// here change with your xml file
case R.layout.home:
// set here common control like header textview
break;
default:
break;
}
}
}
3 - Now, you can extend your Activity with the BaseActivity. This will allow the Activity to be extended by FragmentActivity:
public class ABCActivity extends BaseActivityMenu {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.home);
}
}
In code, your base activity is called ExampleActivity, but in your child class you are extending BaseActivityMenu. Don't know where its coming from.
Perhaps change:
public class ABCActivity extends BaseActivityMenu
To this:
public class ABCActivity extends ExampleActivity
Moreover, I would suggest you to define your base activity (ExampleActivity) as an Abstract class.
For example:
public abstract class ExampleActivity extends Activity
Doing so will not define your base class as concrete and will make it easier to debug in case of problems.
How to Fill ListPreference entry and entryvalues From onPreferenceClick event
I Filled From onPreferenceClick event But When First Clicked Getting Empty List
When Second Clicked is Getting All Item.
Why When First Cliked Then Getting Empty List?
thanks.
When setOnPreferenceClickListener is called the dialog seems already created. A possible solution is to extend ListPreference and intercept the click on the view.
package com.example;
import android.preference.ListPreference;
import android.content.Context;
import android.util.AttributeSet;
public class DynamicListPreference extends ListPreference {
public interface DynamicListPreferenceOnClickListener {
public void onClick(DynamicListPreference preference);
}
private DynamicListPreferenceOnClickListener mOnClicListner;
public DynamicListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onClick(){
if (mOnClicListner != null)
mOnClicListner.onClick(this);
super.onClick();
}
public void setOnClickListner(DynamicListPreferenceOnClickListener l) {
mOnClicListner = l;
}
}
The new class have the public method setOnClickListner, you should use it instead of setOnPreferenceClickListener.
Then you can use DynamicListPreference in your xml preference file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<com.example.DynamicListPreference
android:key="id_list"
android:title="#string/opt_label"
/>
</PreferenceScreen>
In your PreferenceActiviy:
package com.example;
import com.example.DynamicListPreference.DynamicListPreferenceOnClickListener;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.os.Bundle;
public class MyPreferencesActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
DynamicListPreference pref = (DynamicListPreference)findPreference("id_list");
pref.setOnClickListner(onClickListener_mylist);
}
private DynamicListPreferenceOnClickListener onClickListener_mylist = new DynamicListPreferenceOnClickListener() {
#Override
public void onClick(DynamicListPreference preference) {
ListPreference pref = (ListPreference) preference;
pref.setEntryValues(new String[] {"1", "2"});
pref.setEntries(new String[] {"first", "second"});
}
};
}
The first idea that popped in my mind. Looks like a very dirty hack to get around, but anyway:
findPreference("yourPreferenceKey").setOnPreferenceClickListener(new OnPreferenceClickListener() {
private final String[] values = {"1","2","3","4"}; // Data set (as an example)
#Override
public boolean onPreferenceClick(final Preference preference) {
((ListPreference)preference).setEntryValues(values); // Set new values
((ListPreference)preference).setEntries(values); // And new keys
final OnPreferenceClickListener prefClickListener = this; // Store the reference to this click listener for a later use
preference.setOnPreferenceClickListener(null); // And remove it from current preference, so it won't cause a recursion when we will emulate user click later
YourPreferenceActivity.this.runOnUiThread(new Runnable(){ // Do some work after current listener finishes it's stuff
#Override
public void run() {
((ListPreference)preference).getDialog().dismiss(); // Dismiss the dialog that popped up because of our first click (with the old data)
YourPreferenceActivity.this.getPreferenceScreen().onItemClick(null, null, preference.getOrder(), 0); // Emulate user click. System will think that user clicked on the same preference again
preference.setOnPreferenceClickListener(prefClickListener); // Let's return our click listener back, so the whole operation will repeat on the next click (delete thi sline if you need preloading only once.
}
});
return false;
}
});