Using a custom BottomSheetDialog class means I can't touchOutside to cancel - android

So I made a custom class that does basically nothing except boilerplate code plus customizing the callback. For whatever reason, I can't seem to make it cancel when I touch outside the bounds of the bottom sheet.
public class CustomBottomSheetDialog extends AppCompatDialog {
public CustomBottomSheetDialog(Context context) {
super(context, R.style.Theme_Design_Light_BottomSheetDialog);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
#Override
public void setContentView(View view) {
final CoordinatorLayout coordinator = (CoordinatorLayout) View.inflate(getContext(),
R.layout.design_bottom_sheet_dialog, null);
FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setBottomSheetCallback(mBottomSheetCallback);
bottomSheet.addView(view);
super.setContentView(coordinator);
}
private BottomSheetBehavior.BottomSheetCallback mBottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
cancel(); // The only not boilerplate code here, woo
}
}
#Override
public void onSlide(View bottomSheet, float slideOffset) { }
};
Things I've tried:
bottomSheetDialog.setCancelable(true);
bottomSheetDialog.setCanceledOnTouchOutside(true);
Overriding dispatchTouchEvent, but I can't get the rectangle to equal anything besides the size of the entire screen.
If I don't use the custom class (ie simply change my CustomBottomSheetDialog call to just BottomSheetDialog), I get the cancel on touch outside, but then I don't get a cancel when I drag to hide the dialog, which I am required to have.

Finally got it. In the onCreate, I added a single line of code to find the touch_outside view and add a click listener to cancel the dialog. The touch_outside view is generated by default. I did not need to add it in my bottom sheet's XML.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.touch_outside).setOnClickListener(v -> cancel()); // <--- this guy
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
Thanks goes to this tutorial.

Related

How to block the click event to the background of DialogFragment around Samsung S9 Edge button

I have a UI requirement showing a blocking DialogFragment, which can not be dismissed by clicking on the background.
Also when the DialogFragment is showing, any view under it cannot be clicked.
Things are working well except on the Samsung S9 device.
On Samsung S9, which has an edge button, when clicking around the edge button's edge, the view under the DialogFragment got clicked and the event performed, which is not as expected.
Here is a sample code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyDialogFragment myDialogFragment = new MyDialogFragment();
myDialogFragment.show(getSupportFragmentManager(), MyDialogFragment.TAG);
}
});
findViewById(R.id.background).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("wrong", "clicked!!!!---------------");
Toast.makeText(MainActivity.this, "Click!", Toast.LENGTH_LONG).show();
}
});
}
}
The layout is quite simple, just a LinearLayout with a button inside it.
Clicking button will show the blocking dialog.
The LinearLayout id is background, which should not be clicked after the dialog has shown.
The dialog code:
public class MyDialogFragment extends DialogFragment {
public static final String TAG = "Dialog";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(false);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_dialog_layout, container, false);
getDialog().setCanceledOnTouchOutside(false);
return view;
}
#Override
public void onResume() {
Window window = getDialog().getWindow();
Point size = new Point();
Display display = window.getWindowManager().getDefaultDisplay();
display.getSize(size);
window.setLayout((int) (size.x * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
super.onResume();
}
}
But now when the dialog is showing, click the area on the edge button, the background click listener can be entered, I can get the log and toast.
How to prevent this?
In the event that is firing I'd do
Fragment currentFrag = getSupportFragmentManager().findFragmentByTag(MyDialogFragment_TAG);
if (!(currentFrag instanceof MyDialogFragment))
{
// your code for when you're dialog fragment is not visible
}
setcancelable(false); can be used to block clicking on background till task completes
Give the root node an id
<androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/constraintlayoutRoot"
Add an empty OnClickListener
public View onCreateView(...) {
View view = _inflater.inflate(R.layout.fragment_xyz, _container, false);
view.findViewById(R.id.constraintlayoutRoot).setOnClickListener(view1 -> {
});

BottomSheetDialog remains hidden after dismiss by dragging down

I am pretty curious about the behavior of the BottomSheetDialog when it is dismissed : when the user draggs it down to hide it, it will remain hidden, even if bottomSheetDialog#show() is called after. This only happens when it is dragged down, not when the user touches outside or when bottomSheetDialog#dismiss() is called programatically.
It is really annoying because I have a pretty big bottomSheetDialog with a recyclerview inside, and I have to create a new one every time I want to show the bottomSheetDialog.
So instead of just doing this :
if(bottomSheetDialog != null){
bottomSheetDialog.show();
else{
createNewBottomSheetDialog();
}
I have to create one every time.
Am I missing something or is it the normal behavior ? (Btw I use appcompat-v7:23.2.1)
So I finally managed to solve this problem by looking directly into the BottomSheetDialog implementation, and I discovered it was nothing but a simple Dialog wrapped into a regular BottomSheet.
The problem was in the BottomSheetCallBack :
#Override
public void onStateChanged(#NonNull View bottomSheet,
#BottomSheetBehavior.State int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
}
}
The problem occurs when the state HIDDEN is reached which happens when the dialog is dismissed by being dragged down. After that the dialog stays hidden even if bottomSheetDialog.show() is called. The most simple fix I found was to remove this state and replace it by the COLLAPSED state.
I create a classCustomBottomSheetDialog, copied the entire BottomSheetDialog class and added a single line to fix the problem :
#Override
public void onStateChanged(#NonNull View bottomSheet,
#BottomSheetBehavior.State int newState) {
if (newState == CustomBottomSheetBehavior.STATE_HIDDEN) {
dismiss();
bottomSheetBehavior.setState(CustomBottomSheetBehavior.STATE_COLLAPSED);
}
}
Here is the final code:
public class CustomBottomSheetDialog extends AppCompatDialog {
public CustomBottomSheetDialog (#NonNull Context context) {
this(context, 0);
}
public CustomBottomSheetDialog (#NonNull Context context, #StyleRes int theme) {
super(context, getThemeResId(context, theme));
// We hide the title bar for any style configuration. Otherwise, there will be a gap
// above the bottom sheet when it is expanded.
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
}
protected CustomBottomSheetDialog (#NonNull Context context, boolean cancelable,
OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
}
#Override
public void setContentView(#LayoutRes int layoutResId) {
super.setContentView(wrapInBottomSheet(layoutResId, null, null));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setLayout(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
#Override
public void setContentView(View view) {
super.setContentView(wrapInBottomSheet(0, view, null));
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
super.setContentView(wrapInBottomSheet(0, view, params));
}
private View wrapInBottomSheet(int layoutResId, View view, ViewGroup.LayoutParams params) {
final CoordinatorLayout coordinator = (CoordinatorLayout) View.inflate(getContext(),
R.layout.design_bottom_sheet_dialog, null);
if (layoutResId != 0 && view == null) {
view = getLayoutInflater().inflate(layoutResId, coordinator, false);
}
FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setBottomSheetCallback(mBottomSheetCallback);
if (params == null) {
bottomSheet.addView(view);
} else {
bottomSheet.addView(view, params);
}
// We treat the CoordinatorLayout as outside the dialog though it is technically inside
if (shouldWindowCloseOnTouchOutside()) {
coordinator.findViewById(R.id.touch_outside).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isShowing()) {
cancel();
}
}
});
}
return coordinator;
}
private boolean shouldWindowCloseOnTouchOutside() {
if (Build.VERSION.SDK_INT < 11) {
return true;
}
TypedValue value = new TypedValue();
//noinspection SimplifiableIfStatement
if (getContext().getTheme()
.resolveAttribute(android.R.attr.windowCloseOnTouchOutside, value, true)) {
return value.data != 0;
}
return false;
}
private static int getThemeResId(Context context, int themeId) {
if (themeId == 0) {
// If the provided theme is 0, then retrieve the dialogTheme from our theme
TypedValue outValue = new TypedValue();
if (context.getTheme().resolveAttribute(
R.attr.bottomSheetDialogTheme, outValue, true)) {
themeId = outValue.resourceId;
} else {
// bottomSheetDialogTheme is not provided; we default to our light theme
themeId = R.style.Theme_Design_Light_BottomSheetDialog;
}
}
return themeId;
}
private BottomSheetBehavior.BottomSheetCallback mBottomSheetCallback
= new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet,
#BottomSheetBehavior.State int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
bottomSheetBehavior.setState(CustomBottomSheetBehavior.STATE_COLLAPSED);
}
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
}
};
}
Update: The problem has been resolved at some version of the support library. I don't really know the exact version that fixes it but in 27.0.2 it is fixed.
Note: The URL does no longer refer to the issue described due to some modification on the URL schema by Google.
A workaround better than copying the whole class just to add a single line
// Fix BottomSheetDialog not showing after getting hidden when the user drags it down
myBottomSheetDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
BottomSheetDialog bottomSheetDialog = (BottomSheetDialog) dialogInterface;
FrameLayout bottomSheet = (FrameLayout) bottomSheetDialog
.findViewById(android.support.design.R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_COLLAPSED);
}
});
see: https://code.google.com/p/android/issues/detail?id=202396#c7
I have sample demo I hope that is useful.
public class BottomListMenu extends BottomSheetDialog {
private List<MenuDTO> menuList;
private OnMenuItemTapped menuTapListener;
public BottomListMenu(#NonNull Context context, List<MenuDTO> menuList, OnMenuItemTapped menuTapListener) {
super(context);
this.menuList = menuList;
this.menuTapListener = menuTapListener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_menu_list);
RecyclerView rcvList = (RecyclerView) findViewById(R.id.rcv_menu_list);
rcvList.setLayoutManager(new LinearLayoutManager(getContext()));
BottomSheetMenuListAdapter adapter = new BottomSheetMenuListAdapter(getContext(), this, menuList, menuTapListener);
rcvList.setAdapter(adapter);
}
}
--- Use ---
BottomListMenu menu = new BottomListMenu(MainActivity.this, MenuUtils.getListMenu(MainActivity.this), new OnMenuItemTapped() {
#Override
public void onClickMenuItem(MenuDTO menu) {
if (menu.getMenuTitle().equals(getString(R.string.menu_edit))) {
Toast.makeText(MainActivity.this, "Edit Clicked", Toast.LENGTH_SHORT).show();
} else if (menu.getMenuTitle().equals(getString(R.string.menu_delete))) {
Toast.makeText(MainActivity.this, "Delete Clicked", Toast.LENGTH_SHORT).show();
} else if (menu.getMenuTitle().equals(getString(R.string.menu_attach))) {
Toast.makeText(MainActivity.this, "Attach Clicked", Toast.LENGTH_SHORT).show();
}
}
});
menu.show();
-- Full Sample Code Available Here --
https://github.com/bita147/BottomSheetDialog

How to dim background when using the BottomSheet from the support library?

How can the background be dimmed just like it is shown here?
I've set it up normally using the CoordinatorLayout and the BottomSheetBehavior.
This will simply show a bottom sheet.
public class MyBottomSheet extends BottomSheetDialogFragment {
private static final String TAG = "MyBottomSheet";
#NonNull
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
final BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
final View view = View.inflate(getContext(), R.layout.my_custom_view, null);
dialog.setContentView(view);
behavior = BottomSheetBehavior.from((View) view.getParent());
return dialog;
}
public void show(final FragmentActivity fragmentActivity) {
show(fragmentActivity.getSupportFragmentManager(), TAG);
}
}
To close the dialog simply as normal call close().
bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
(your_layout/view).setAlpha(1 - slideOffset);
}
});
use BottomSheetDialog
basically it's a dialog (i.e support dim) and support modal bottom sheets behaviour give it a try

Catch dismissal of BottomSheetDialogFragment

Is there any way to catch the dismissal/cancel of a BottomSheetDialogFragment?
Bottom sheet class
public class ContactDetailFragment extends BottomSheetDialogFragment
{
private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback()
{
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState)
{
if (newState == BottomSheetBehavior.STATE_HIDDEN)
{
dismiss();
}
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset)
{
}
};
#Override
public void setupDialog(Dialog dialog, int style)
{
super.setupDialog(dialog, style);
View contentView = View.inflate(getContext(), R.layout.fragment_contactdetail, null);
dialog.setContentView(contentView);
BottomSheetBehavior mBottomSheetBehavior = BottomSheetBehavior.from(((View) contentView.getParent()));
if (mBottomSheetBehavior != null)
{
mBottomSheetBehavior.setBottomSheetCallback(mBottomSheetBehaviorCallback);
mBottomSheetBehavior.setPeekHeight((int) DisplayUtils.dpToPixels(CONTACT_DETAIL_PEEK_HEIGHT, getResources().getDisplayMetrics()));
}
}
}
What I've tried that doesn't work
in setupDialog adding either of dialog.setOnCancelListener(); or dialog.setOnDismissListener(); never gets triggered
the bottomsheet behavior's onStateChanged only gets triggered if the user drags the bottomsheet down passed the collapsed state, and there is no state for dismissed/cancelled
adding the same oncancel/ondismiss listeners to the instantiation of the BottomSheetDialogFragment, by using ContactDetailFragment.getDialog().setOnCancelListener() does not get triggered
Given that it's essentially a dialog fragment, there must be some way to catch the dismissal?
Found a simple solution.
Using onDestroy or onDetach in the BottomSheetDialogFragment allows me to get the dismissal correctly

Why to inflate layout into another layout in Android?

I'm new in Android development and I wanted to make application that has header, body and footer and by clicking on one of the buttons in footer some layout will be loaded into body. I used some kind of "MasterPage" as described here.
When the button is pressed neither new_exercise layout nor exercises layout is loaded. Why? Maybe instead of all of this I should use any kind of tabs? Or maybe I can't inflate layout and should create new activity?
Here the code of the BaseActivity and NewExercise activity:
public class BaseActivity extends Activity{
LinearLayout linBaseBody;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.base_layout);
linBaseBody = (LinearLayout)findViewById(R.id.base_body);
initButtons();
}
#Override
public void setContentView(int id) {
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(id, linBaseBody);
}
private void initButtons()
{
Button btn1 = (Button) findViewById(R.id.newEx);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setContentView(R.layout.new_exercise);
}
});
Button btn2 = (Button) findViewById(R.id.showAllEx);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setContentView(R.layout.exercises);
}
});
}
public class NewExercise extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.new_exercise);
}
}
public class Exercises extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercises);
}
}
How your code is written, it would make more sense to use a new Activity. However, If you wanted to keep all of the view in one Activity, you could walk through all of your layouts calling mLayout.setVisible(View.VISIBLE); or you could use ViewStubs.
As to answer your question, why, what you are doing is adding the view (and their layouts) directly to your already created and inflated content view (the one you created in onCreate). You will need to clear the Activities contentView first to see the changes you are making with the button.

Categories

Resources