Im using One Gulli Bulls Screen Orientation Change – Saving Focus example to regain focus when orientation changes.
My activity AddGearbox and opens a dialog CustomizeDialog (activity with theme.dialog).
The dialog has some textboxes. In onSaveInstanceState i save what I need and am able to restore it in restoreDialog. But the focus is not restored.
I am logging the id of the view that has focus when orientation changes but I guess that view is in the activity showing the dialog and not in the dialog itself?
What to do?
AddGearbox.java
public class AddGearbox extends FragmentActivity implements
MyListFragment.MyOnClickSelectedListener, DialogInterface.OnDismissListener {
CustomizeDialog customizeDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
customizeDialog = new CustomizeDialog(this);
if(savedInstanceState!=null) {
restoreDialog(savedInstanceState);
}
}
....
....
....
#Override
protected void onSaveInstanceState(Bundle saveState) {
super.onSaveInstanceState(saveState);
saveState.putBoolean("isDialogOpen",isDialogOpen);
if (isDialogOpen) {
// Save a lot of stuff
View focusedChild = getCurrentFocus();
if (focusedChild != null)
{
int focusID = focusedChild.getId();
int cursorLoc = 0;
if (focusedChild instanceof EditText)
{
cursorLoc = ((EditText) focusedChild).getSelectionStart();
}
saveState.putInt("focusID", focusID);
saveState.putInt("cursorLoc", cursorLoc);
}
}
}
private void restoreDialog(Bundle savedInstanceState) {
isDialogOpen=savedInstanceState.getBoolean("isDialogOpen");
if (isDialogOpen) {
customizeDialog = new CustomizeDialog(this);
// Restore a lot of stuff
int focusID = savedInstanceState.getInt("focusID", View.NO_ID);
View focusedChild = findViewById(focusID);
if (focusedChild != null) {
focusedChild.requestFocus();
if (focusedChild instanceof EditText) {
int cursorLoc = savedInstanceState.getInt("cursorLoc", 0);
((EditText) focusedChild).setSelection(cursorLoc);
}
}
customizeDialog.show();
}
CustomizeDialog.java
public class CustomizeDialog extends Dialog implements OnClickListener {
public CustomizeDialog(AddGearbox mainActivity) {
super(mainActivity);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.customizedialog);
Related
I have an AppCompatActivity that, at some point, display a DialogFragment. In this dialog, there are items for which I ask confirmation before deleting them. That confirmation is asked through another Yes/No DialogFragment. When the user clicks Yes in that second dialog, I want the first dialog to refresh its ListView (just need to update the adapter and call its notifyDataSetChanged method). The problem is that I don't know when to update the listview.
Because that delete functionality is called from various sources, I implement a listener Interface at the activity level and call an "onDeleteRequest" event from that interface whenever I need an item to be deleted, and that's the activity who opens up the confirmation dialog and perform the actual delete.
Since I don't care much about refreshing the ListView in unnecessary situations, I tried to update the list in the onResume event, but the event is not called when I come back to the first dialog after the confirmation one is dismissed.
So my question is: how can I know when a dialog B displayed on top of a dialog A has been dismissed so I can refresh dialog A accordingly?
EDIT : A bit of code to support my question:
My activity class:
public class MonthActivity
extends AppCompatActivity
implements OnEditCalendarsDialogListener
{
...
//That's where dialog A is shown
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
...
if (id == R.id.action_select_calendar) {
final CalendarSelection currentSelection = mCalendarSelectionAdapter.getCurrentCalendarSelection();
if (currentSelection != null) {
EditCalendarsDialogFragment dialogFragment = EditCalendarsDialogFragment.newInstance(currentSelection);
dialogFragment.show(getSupportFragmentManager());
}
return true;
}
return super.onOptionsItemSelected(item);
}
...
//OnEditCalendarsDialogListener interface implementation
//That's where Dialog B is shown over Dialog A
#Override
public void onEditCalendarsDialogDelete(long calendarID) {
final Repository repository = Repository.getInstance(this);
final Calendar calendar = repository.fetchOneByID(Calendar.class, calendarID);
if (calendar != null) {
YesNoDialog yesNoDialog = YesNoDialog.newInstance(this, R.string.yes_no_dialog_confirmation, R.string.yes_no_dialog_calendar_delete);
setCurrentOnDecisionClickListener(new OnPositiveClickListener() {
#Override
public boolean onPositiveClick(DialogInterface dialog) {
//Delete calendar
repository.delete(calendar);
//That's where I'd like to notify Dialog A that it needs to be refreshed
return true;
}
});
yesNoDialog.show(getSupportFragmentManager());
}
}
}
My dialog class
public class EditCalendarsDialogFragment
extends DialogFragment
{
private OnEditCalendarsDialogListener mDialogListener;
public static EditCalendarsDialogFragment newInstance(CalendarSelection calendarSelection) {
EditCalendarsDialogFragment dialog = new EditCalendarsDialogFragment();
Bundle arguments = new Bundle();
if (calendarSelection != null) {
arguments.putLong(KEY_ID, calendarSelection.getID());
}
else {
arguments.putLong(KEY_ID, 0L);
}
dialog.setArguments(arguments);
return dialog;
}
...
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mDialogListener = (OnEditCalendarsDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnCalendarSelectionDialogListener");
}
}
...
private View getLayoutView() {
View rootView = getActivity().getLayoutInflater().inflate(R.layout.calendar_list, null, false);
if (rootView != null) {
mCalendars = (ListView) rootView.findViewById(R.id.calendars);
if (mCalendars != null) {
//Create adaptor
mCalendarAdapter = new ArrayAdapter<Calendar>(
getContext(),
android.R.layout.simple_list_item_2,
android.R.id.text1,
new ArrayList<Calendar>()
) {
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
final Calendar calendar = getItem(position);
if (calendar != null && calendar.hasID()) {
...
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mDialogListener != null) {
//That's where I request delete from calling activity
mDialogListener.onEditCalendarsDialogDelete(calendar.getID());
}
return true;
}
});
}
return view;
}
};
mCalendars.setAdapter(mCalendarAdapter);
refreshCalendarList();
}
}
return rootView;
}
}
Use EventBus.
Register your dialog A to listen to events. When you dismiss dialog B post an event and pass the listitem's adapter position or whatever data you want to use to identify which item is to be deleted. Inside your dialog A write a function to receive this event inside which you delete the item.
OK, so I finally used the "over-abusive-callback" method.
I created the following interface:
public interface OnDeletedListener {
void onDeleted();
}
Updated the OnEditCalendarsDialogListener interface so that the callback has a callback to this interface too:
public interface OnEditCalendarsDialogListener {
void onEditCalendarsDialogDelete(long calendarID, OnDeletedListener onDeletedListener);
}
Implemented the OnDeletedListener interface in "Dialog A" class:
public class EditCalendarsDialogFragment
extends DialogFragment
implements OnDeletedListener
{
...
//OnDeletedListener interface implementation
#Override
public void onDeleted() {
//That's where I'm called back after item is deleted
refreshCalendarList();
}
...
private View getLayoutView() {
...
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mDialogListener != null) {
//That's where I request delete from calling activity, asking to call me back once deleted
mDialogListener.onEditCalendarsDialogDelete(calendar.getID(), EditCalendarsDialogFragment.this);
}
return true;
}
});
...
}
}
And finally, call the callback when delete is accepted and performed:
public class MonthActivity
extends AppCompatActivity
implements OnEditCalendarsDialogListener
{
//OnEditCalendarsDialogListener interface implementation
//That's where Dialog B is shown over Dialog A
#Override
public void onEditCalendarsDialogDelete(long calendarID, final OnDeletedListener onDeletedListener) {
final Repository repository = Repository.getInstance(this);
final Calendar calendar = repository.fetchOneByID(Calendar.class, calendarID);
if (calendar != null) {
YesNoDialog yesNoDialog = YesNoDialog.newInstance(this, R.string.yes_no_dialog_confirmation, R.string.yes_no_dialog_calendar_delete);
setCurrentOnDecisionClickListener(new OnPositiveClickListener() {
#Override
public boolean onPositiveClick(DialogInterface dialog) {
//Delete calendar
repository.delete(calendar);
//That's where I notify Dialog A that it needs to be refreshed
if (onDeletedListener != null) {
onDeletedListener.onDeleted();
}
return true;
}
});
yesNoDialog.show(getSupportFragmentManager());
}
}
}
Works smoothly!
Any idea how to illustrate backspace funtion in this code? I try to make some changes but it can't work the backspace function. So, i would like to help me, with the backspace button.
enter code here
public class MainActivity extends AppCompatActivity implements OnClickListener {
private TextView mCalculatorDisplay;
private Boolean userIsInTheMiddleOfTypingANumber = false;
private CalculatorBrain mCalculatorBrain;
private static final String DIGITS = "0123456789.";
DecimalFormat df = new DecimalFormat("############");
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCalculatorBrain = new CalculatorBrain();
mCalculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonBackspace).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonSquared) != null) {
findViewById(R.id.buttonSquared).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonSine) != null) {
findViewById(R.id.buttonSine).setOnClickListener(this);
}
if (findViewById(R.id.buttonCosine) != null) {
findViewById(R.id.buttonCosine).setOnClickListener(this);
}
if (findViewById(R.id.buttonTangent) != null) {
findViewById(R.id.buttonTangent).setOnClickListener(this);
}
}
#Override
public void onClick (View v) {
String buttonPressed = ((Button) v).getText().toString();
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
mCalculatorDisplay.append(buttonPressed);
}
} else {
if (buttonPressed.equals(".")) {
// ERROR PREVENTION
// This will avoid error if only the decimal is hit before an operator, by placing a leading zero
// before the decimal
mCalculatorDisplay.setText(0 + buttonPressed);
} else {
mCalculatorDisplay.setText(buttonPressed);
}
}
userIsInTheMiddleOfTypingANumber = true;
}else{
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation(buttonPressed);
if (new Double(mCalculatorBrain.getResult()).equals(0.0)) {
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", mCalculatorBrain.getResult());
outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
if (new Double(mCalculatorBrain.getResult()).equals(0.0)){
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
In your layout you can add a onClick attribute to each button, say onClick="function", and in your activity you just need to implement a method like this:
public void function(View v) {
switch(v.getId()) {
case R.id.buttonBackspace:
// handle the backspace button
break;
case R.id.xxx:
// handle the button
break;
...
}
}
And for digits, I suggest assign a tag to each digit button in the layout, and do your logic in java based on the tag, instead of the text on the button. Because the text is just a UI, it might change in the future due to other possible requirements.
I have and application in which I am using the Single activity and different fragments let say on activity start I call fragment A , and then after taking inputs I switch to fragment B and then Fragment C .
For Some reasons I have changed the Overflow Icon successfully from styles. But now The only problem is that for some reasons I want to show the overflow icons on Fragment B but not on Fragment A and C . for this I am doing this
public static void setOverflowButtonColor(final Activity activity, final int i) {
final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description);
final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
TintImageView overflow = null;
final ArrayList<View> outViews = new ArrayList<View>();
decorView.findViewsWithText(outViews, overflowDescription,
View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
if (outViews.isEmpty()) {
return;
}
overflow = (TintImageView) outViews.get(0);
//overflow.setColorFilter(Color.CYAN);
overflow.setImageResource(R.drawable.my_overflow_image);
if (i == 1 && overflow!=null) {
overflow.setEnabled(false);
overflow.setVisibility(View.GONE);
} else if (overflow != null) {
overflow.setEnabled(true);
overflow.setVisibility(View.VISIBLE);
}
overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Overflow", Toast.LENGTH_SHORT).show();
}
});
removeOnGlobalLayoutListener(decorView, this);
}
});
}
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
}
else {
v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
}
So from Fragment A I am sending 1 in parameter so to hide the Icon but from Activity B I am sending 0 in parameter to re visible it , but it is not getting call.
Let me tell you this function working when it is called from Fragment A , I mean it is calling one time but not 2nd time or so on .
please tell me how to do this , if you know any other best method
Define an interface like below.
public interface FragmentHost{
public void onFragmentChange(int currentFragment);
}
Activity A should implement this interface.
class A extends Activity implents FragmentHost {
public static final int FRAGMENT_B = 0;
public static final int FRAGMENT_C = 1;
#Override
public void onFragmentChange(int currentFragment) {
if (currentFragment == FRAGMENT_A) {
// enable or disable button
} else if(currentFragment == FRAGMENT_B) {
// enable or disable button
}
}
}
And in each fragment . OnResume function call the onFragmentChange() method and pass the fragment id.
class B extends Fragment {
#Override
public void onResume() {
((FragmentHost) getParentActivity()).onFragmentChange(A.FRAGMENT_B);
}
}
A similar question has been asked before, but my case is different.
I have DialogFragments all over my app. When I rotate the phone, all of the DialogFragments come back without issue except this one.
I've littered the life cycle callbacks with Log messages to see what is going on, and this is the scenario:
My DialogFragment is created and shown
On rotation, I save whatever I want to into a bundle for restoration afterwards.
DialogFragment is successfully recreated. I know because onCreate through to onResume are called.
Immediately after resumption, for some inexplicable reason, onPause, onStop, onDestroyView, onDestroy and onDetach are called in rapid succession. The DialogFragment is destroyed immediately after recreation and I don't know why.
Any help is much appreciated. The DialogFragment starts an activity for result to take a picture. It works well for most phones, but the Galaxy S3 camera causes orientation changes that force the activity to be recreated. I don't mind this, I know how to handle activity recreation, but this I've never encountered.
The DialogFragment is started via a RecyclerView adapter callback from a regular fragment, in the main hosting activity.
I do not show the DialogFragment using the ChildFragmentManger in the fragment hosting the RecyclerView because multiple fragments can show this DialogFragment and the function is always the same. It was much more prudent to have the activity receive the callback regardless of which fragment started it.
From the fragment:
selectionPickAdapter.setAdapterListener(new selectionPickAdapter.AdapterListener() {
#Override
public void onSelectionClicked(Selection selection) {
if (getActivity() instanceof RankingActivity) {
((RankingActivity) getActivity()).onSelectionClicked(selection);
}
}
});
The main hosting activity receives the call back and shows it thus:
#Override
public void onSelectionClicked(Selection selection) {
if (isSignedInUser) {
selectionsToEdit.put(selection.hashCode(), selection);
if (baseCategory != null) {
selection.setCategory(baseCategory);
}
RankingSelectionEditDialogFragment rankingSelectionEditDialogFragment =
RankingSelectionEditDialogFragment.newInstance(SELECTION_EDIT, selection.hashCode(), selection);
rankingSelectionEditDialogFragment.show(getSupportFragmentManager(), EDIT_TAG);
}
else {
Intent i = new Intent(this, BusinessActivity.class);
i.putExtra(Constants.BUSINESS, selection.getBusiness().getId());
startActivity(i);
}
}
These are my lifecycle callbacks:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
selectionToEdit = savedInstanceState.getParcelable(SELECTION_TO_EDIT);
imagePath = savedInstanceState.getString(IMAGE_PATH);
}
else {
selectionToEdit = getArguments().getParcelable(SELECTION_TO_EDIT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState != null) {
Log.i(TAG, "CREATED A SECOND TIME!");
}
else {
Log.i(TAG, "CREATED ONCE!");
}
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_ranking_edit, container, false);
initializeViewComponents(rootView);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupFragment(selectionToEdit);
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume");
Dialog dialog = getDialog();
if (dialog != null) { // Only do this if returning a dialog, not a fragment
Log.i(TAG, "Dialog is not null");
SharedPreferences sharedPreferences
= getActivity().getSharedPreferences(Constants.PREFS, Context.MODE_PRIVATE);
// Get items required to put dialog just under the ActionBar.
int screenWidth = sharedPreferences.getInt(Constants.SCREEN_WIDTH, 720);
int screenHeight = sharedPreferences.getInt(Constants.SCREEN_HEIGHT, 1280);
int screenDPI = sharedPreferences.getInt(Constants.SCREEN_DPI, 320);
Window window = dialog.getWindow();
window.setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
windowLayoutParams.y = -((screenHeight / 2) - 56) * (screenDPI / 160);
window.setAttributes(windowLayoutParams);
if (dialog.isShowing()) {
Log.i(TAG, "Dialog is showing");
}
else {
Log.i(TAG, "Dialog is not showing");
}
}
else {
Log.i(TAG, "Dialog is null");
}
Log.i(TAG, "onResume finished");
}
/**
* The system calls this only when creating the layout in a dialog.
*/
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
SharedPreferences sharedPreferences
= getActivity().getSharedPreferences(Constants.PREFS, Context.MODE_PRIVATE);
// Get items required to put dialog just under the ActionBar.
int screenWidth = sharedPreferences.getInt(Constants.SCREEN_WIDTH, 720);
int screenHeight = sharedPreferences.getInt(Constants.SCREEN_HEIGHT, 1280);
int screenDPI = sharedPreferences.getInt(Constants.SCREEN_DPI, 320);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = dialog.getWindow();
window.setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
windowLayoutParams.y = -((screenHeight / 2) - 56) * (screenDPI / 160);
windowLayoutParams.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(windowLayoutParams);
return dialog;
}
/**
* Restore the previous currentFragment before the dialog was brought up
*/
#Override
public void dismiss() { // Used when the user deliberately dismisses the dialog
Log.i(TAG, "Dismissed");
super.dismiss(); // Ensure Super class method is called
}
/**
* Restore the previous currentFragment before the dialog was brought up
*/
#Override
public void onCancel(DialogInterface dialog) { // Used when the user inadvertently leaves the dialog,
// e.g back pressed or touched outside the dialog
Log.i(TAG, "Cancelled");
super.onCancel(dialog); // Ensure Super class method is called
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(SELECTION_TO_EDIT, selectionToEdit);
outState.putString(IMAGE_PATH, imagePath);
}
#Override
public void onPause() {
Log.i(TAG, "onPause");
super.onPause();
}
#Override
public void onStop() {
Log.i(TAG, "onStop");
super.onStop();
}
#Override
public void onDestroyView() {
Log.i(TAG, "View Destroyed");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
super.onDestroy();
}
#Override
public void onDetach() {
Log.i(TAG, "onDetach");
super.onDetach();
}
EDIT: I've fixed the issue. To show the DialogFragment, I should use the ChildFragmentManager of the hosting fragment and not the activity. That is, changing this:
RankingSelectionEditDialogFragment rankingSelectionEditDialogFragment =
RankingSelectionEditDialogFragment.newInstance(SELECTION_EDIT, selection.hashCode(), selection);
rankingSelectionEditDialogFragment.show(getSupportFragmentManager(), EDIT_TAG);
to this:
RankingSelectionEditDialogFragment rankingSelectionEditDialogFragment =
RankingSelectionEditDialogFragment.newInstance(SELECTION_EDIT, selection.hashCode(), selection);
switch (currentFragment) {
case CATEGORY_PICK:
rankingCategoryPickFragment = (RankingCategoryPickFragment)
getSupportFragmentManager().findFragmentByTag(CATEGORY_PICK_TAG);
if(rankingCategoryPickFragment != null) {
rankingSelectionEditDialogFragment.show
(rankingCategoryPickFragment.getChildFragmentManager(), EDIT_TAG);
}
break;
case BUSINESS_SORT:
rankingBusinessSortParentFragment = (RankingBusinessSortParentFragment)
getSupportFragmentManager().findFragmentByTag(BUSINESS_SORT_TAG);
if(rankingBusinessSortParentFragment != null) {
rankingSelectionEditDialogFragment.show
(rankingBusinessSortParentFragment.getChildFragmentManager(), EDIT_TAG);
}
break;
was the ticket. Hope that helps anybody else with a similar issue.
How to make a preference activity where contain listpreference, where the summary will change based on selected listpreference item, and when certain list item is taped, it will show a edit text dialog which it will also become the the summary string value.
Thank in advance.
as requested, here my current code
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/pref_category_general"
android:key="pref_category_general">
<CheckBoxPreference
android:key="pref_debug_mode"
android:title="#string/pref_debug_mode"
android:summary="#string/pref_debug_mode_summary"
android:defaultValue="false" />
<ListPreference
android:dependency="pref_debug_mode"
android:key="pref_remotehost"
android:title="#string/pref_remotehost"
android:dialogTitle="#string/pref_remotehost_dialog_title"
android:entries="#array/pref_remotehost_entries"
android:entryValues="#array/pref_remotehost_entries_values"
android:defaultValue="#string/pref_remotehost_default" />
</PreferenceCategory>
</PreferenceScreen>
and my activity
public class SettingActivity extends SherlockPreferenceActivity implements View.OnClickListener {
private MainApplication G;
private SherlockPreferenceActivity me;
private Intent intent;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.G = ((MainApplication) getApplicationContext());
assert this.G != null;
super.onCreate(bundle);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// Add a button to the header list.
if (hasHeaders()) {
Button button = new Button(this);
button.setText("Some action");
setListFooter(button);
button.setOnClickListener(this);
}
PreferenceFragment prefFragment = new PreferenceGeneralFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, prefFragment);
fragmentTransaction.commit();
this.intent = getIntent();
this.me = 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);
}
#Override
public void onClick(View v) {
/*
switch (element.getId()) {
default:
return;
case R.id.setting_cancel_config:
onBackPressed();
return;
case R.id.setting_save_config:
int i = this.modeSpinner.getSelectedItemPosition();
boolean flag = true;
if (i == 1) {
flag = false;
};
MainApplication.setDeveloperMode(flag);
MainApplication.setRemoteHost(this.remoteHostEdittext.getText().toString());
SettingActivity.this.finish();
onBackPressed();
return;
}
*/
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
/**
* This fragment shows the preferences for the first header.
*/
public static class PreferenceGeneralFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#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_general, false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_general);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
}
}
i don't know where to start