class BottomBarFragment : BottomSheetDialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val contextThemeWrapper = ContextThemeWrapper(getActivity(), R.style.Theme_BaseDarkTheme)
val localInflater = inflater.cloneInContext(contextThemeWrapper)
binding = FragmentBottomBarBinding.inflate(localInflater, container, false)
// tried setStyle also
setStyle(0, R.style.Theme_BaseDarkTheme)
}
}
style
<style name="Theme.BaseDarkTheme" parent="Theme.AppCompat">
<item name="dividerColor">#color/divider_dark</item>
</style>
in fragment dialog layout
<LinearLayout
style="#style/llParent"
android:background="?attr/dividerColor"
>
According to this, my layout should be dark, but it is light always. What am I doing wrong?
The documentation for setStyle() says this:
Call to customize the basic appearance and behavior of the fragment's
dialog. This can be used for some common dialog behaviors, taking care
of selecting flags, theme, and other options for you. The same effect
can be achieve by manually setting Dialog and Window attributes
yourself. Calling this after the fragment's Dialog is created will
have no effect.
Fragment's Dialog will be created after onCreate() and before onCreateView().
Try calling setStyle() from the onCreate() method
Basicly, if you are trying to use something, what have "dialog" in name, you should build dialog. To do this, there is one method like onCreateDialog().
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),your_style);
...
return builder.create();
}
Otherwise, you should extend just a Fragment, and there you can call in onCreateView() something like this:
Context contextThemeWrapper = new ContextThemeWrapper(getActivity(),your_style);
LayoutInflater newInflater = inflater.cloneInContext(contextThemeWrapper);
View view = newInflater.inflate(your_layout,container,false);
Sorry for java code, but there should be similar code.
Related
I have a DialogFragment with a custom layout. Everything shows properly when the fragment is embedded in my activity using a FragmentTransaction, like so:
getSupportFragmentManager()
.beginTransaction()
.add(
R.id.fragment_container,
exampleDialogFragment,
ExampleDialogFragment.TAG)
.commit();
but when I do:
exampleDialogFragment.show(getSupportFragmentManager(), exampleDialogFragment.TAG);
the dialog only shows the 'Cancel' button. The stuff in the custom layout doesn't appear.
This is what my ExampleDialogFragment class looks like:
public class ExampleDialogFragment extends DialogFragment {
#Override
public View onCreateView(
#NonNull LayoutInflater layoutInflater,
#Nullable ViewGroup viewGroup,
#Nullable Bundle bundle) {
// Inflate layout and init views
}
This documentation https://developer.android.com/guide/topics/ui/dialogs#FullscreenDialog seems to imply that we don't need to override onCreateDialog, so I'm not doing that. However, it still doesn't look right. Am I missing something?
For anyone looking at this, my dialog had an outer ConstraintLayout. Changing it to a RelativeLayout fixed the issue.
I would like to change dynamically the theme of my Fragment.
I have tried these solutions:
1st try, set the getTheme method on the activity. It only changes the colors of the activity:
#Override
public Resources.Theme getTheme() {
Resources.Theme theme = super.getTheme();
theme.applyStyle(R.style.AppTheme_RED, true);
return theme;
}
2nd try not changing anything:
final Context contextThemeWrapper = new
ContextThemeWrapper(getActivity(), R.style.AppTheme_RED);
LayoutInflater localInflater = inflater.from(contextThemeWrapper);
final View view = localInflater.inflate(R.layout.fragment_workout_list, container, false);
3rd try work only for activity, not fragment:
setTheme(R.style.AppTheme_RED);
Any help is welcomed.
Thanks in advance.
Edit: I have found that floatingbutton have the good color when i apply theme to fragment.
as google says we must inflate our theme before super.oncreate()
inside your activity or fragment and in oncreate() or on oncreateview() simply add the code below:
setTheme(R.style.AppTheme_RED);
What I want to achieve
From a FragmentActivity show a dialog when clicking an Action Button in the Action Bar
DialogFragment - A Dialog without title
TabHost - Tabs at the top of the dialog
ViewPager with FragmentPagerAdapter - Swipable, which content is connected to the Tabs
2-3 Dialog Buttons (different subclasses of the Dialog, different buttons) - Are not supposed to be in one of the ViewPager's Fragment, meaning the same buttons should remain at the bottom of the Dialog regardless of what Fragment the ViewPager is showing.
The problem
IllegalStateException: Fragment does not have a view
What I have tried/done so far
Using the android.support.v4 package for necessary classes
Calling getChildFragmentManager() instead of getSupportedFragmentManager()
Implemented what post #10 suggested from this link https://code.google.com/p/android/issues/detail?id=42601. I copy/paste the code directly into my two Fragment classes, which the ViewPager is suppose to be showing, plus the DialogFragment class.
In my custom DialogFragment I first tried to override onCreateView, then onCreateDialog and then both at the same time. All of which I got to run but with unexpected results.
Only onCreateView: Can't reach the AlertDialog.Builder to create the needed buttons, other than that the Dialog's results were great.
Only onCreateDialog: the error message shown above. I still imagine this method to be as close as I've gotten to what I want to achieve.
Both onCreateView and onCreateDialog: Inflated the Dialog layout in onCreateView and added the Dialog buttons to the AlertDialog.Builder in onCreateDialog. This displayed the dialog, but the added buttons from the AlertDialog.Builder were not visable. Plus the keyboard didn't show up when clicking on a EditText field.
Source code
Most come from Tutorial to implement the use of TabHost in Android 2.2 + ViewPager and Fragments. The code of the ActivityFragment is instead in a DialogFragment. However I replaced its ViewPager with a modified one from the source code from this answer https://stackoverflow.com/a/18167273/2375978. This was to be able to wrap_content on height.
The faulty code in my project is in DialogFragment's onCreateDialog method, I believe.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_HOLO_DARK);
LayoutInflater inflater = getActivity().getLayoutInflater();
view = inflater.inflate(R.layout.dialog_test, null);
addActionButtons(builder, view);
builder.setView(view);
mViewPager = (WrapContentHeightViewPager) view.findViewById(R.id.viewpager);
initialiseTabHost();
List<Fragment> fragments = getFragments();
pageAdapter = new DialogPageAdapter(getChildFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(this);
Dialog dialog = builder.create();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
dialog.show();
return dialog;
}
Stack trace LogCat log
FATAL EXCEPTION: main
java.lang.IllegalStateException: Fragment does not have a view
at android.support.v4.app.Fragment$1.findViewById(Fragment.java:1425)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:901)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1374)
at my.app.package.name.WrapContentHeightViewPager.onMeasure(WrapContentHeightViewPager.java:31)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15481)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15481)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5059)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2377)
at android.view.View.measure(View.java:15481)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1982)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1200)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1398)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1118)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4525)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:525)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4946)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.jav
Also...
I have unsuccessfully been able to try the other possible solution mentioned in https://code.google.com/p/android/issues/detail?id=42601, mentioned in post #2 and #13, because I haven't understood how and where I can use it in my code (I guess I'm in the same boat as the person who wrote #18).
I think I just ran into this same problem and learned a few things by looking at the source for DialogFragment.
It looks like even though overriding onCreateDialog(...) is a valid way to create a custom dialog, it will result in the DialogFragment having a null View, just like the error message says. In most cases this is fine - the DialogFragment doesn't need a View to show a Dialog, but if you want to nest fragments further (like you do), this won't fly.
Considering that you want to interact with an AlertDialog.Builder, there is really no perfect solution that I can see, but you've got a few options:
Create the buttons in your dialog as part of the View (not using AlertDialog.Builder). You do this by overriding onCreateView instead of onCreateDialog. You should be able to get the functionality you mention by putting the buttons in their own fragment. We do something similar at my gig, and I very much prefer this method.
Implement your own type that inherits from Fragment and that mirrors the DialogFragment in every way except allowing what you need. This shouldn't be too scary as DialogFragment is only ~400 and is heavily commented. Could be fun.
Use a regular PagerAdapter instead of a FragmentPagerAdapter. This way it won't matter that your DialogFragment doesn't have a View.
Use the
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
instead of onCreateDialog(Bundle savedInstanceState). Don't create an alert dialog, use the inflater provided by the method, and build your view. It works for me.
Best regards!
If you implement onCreateDialog to use AlertDialog, you will bump into IllegalStateException: Fragment does not have a view when accessing getChildFragmentManager or something equivalent.
To solve this issue, implement both onCreateDialog and onCreateView, where onCreateView return the view inflated in onCreateDialog.
class LocationPickerDialog : DialogFragment() {
lateinit var customView: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return customView
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
Log.d(TAG, "onCreateDialog")
// StackOverflowError
// customView = layoutInflater.inflate(R.layout.dialog_location_picker, null)
customView = activity!!.layoutInflater.inflate(R.layout.dialog_location_picker, null)
val builder = AlertDialog.Builder(context!!)
.setView(customView)
.setPositiveButton(android.R.string.ok) { _, _ ->
// do something
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
// do something
}
val dialog = builder.create()
return dialog
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
// if onCreateView doesn't return a view
// java.lang.IllegalStateException: Fragment does not have a view
mapFragment = childFragmentManager.findFragmentByTag("map") as SupportMapFragment?
}
}
https://code.luasoftware.com/tutorials/android/android-alertdialog-in-dialogfragment-fragment-does-not-have-a-view/
Thanks to #Tommy Visic for writing a really good description it worked.
Posting the code which worked for me.
I have removed the Dialog building code from the onCreateDialog method infact removed onCreateDialog method and the dialog view which I have been implementing in the Dialog's custom view I have included it as a View in the onCreateView method and all the things started working.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_sigup_screen, null, false);
bind = ButterKnife.bind(this, view);
initViewPager();
return view;
}
Faced one more problem with this implementation is:
When a Activity has Toolbar/ActionBar then it is also displayed into the DialogFragment to avoid that what is to be done is:
Implement onViewCreated method of Fragment and add below code
Dialog dialog = getDialog();
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
float dimAmount = 0.6f;
dialog.getWindow().setDimAmount(dimAmount);
This will remove the Toolbar from the DialogFragment and Activity will be displayed as it is.
Cheers
Thanks #Tommy
Regards
Zeus
I ran into same issue and achieve the following solution :
class MyDialogFragment: DialogFragment {
private lateinit var dialog: AlertDialog
private lateinit var dialogView: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// return the view inflated for your dialog fragment
return dialogView
}
// this is called before onCreateView
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
dialogView = LayoutInflater
.from(ContextThemeWrapper(requireContext(), R.style.MyAlertDialogStyle))
.inflate(R.layout.fragment_dialog, null, false)
dialog = AlertDialog
.Builder(requireContext())
.setView(dialogView)
.create()
dialog.setOnShowListener {
childFragmentManager
.beginTransaction()
.replace(R.id.container, MyNestedFragmentInsideTheDialog())
.commit()
// retrieve dialog buttons if any to manage onClickListener yourself
// dialog.getButton(AlertDialog.BUTTON_POSITIVE)
}
}
}
The idea is to inflate the dialog content yourself and to keep a reference on it so it can be returned into onCreateView and then used by the childfragmentManager ;-)
you can make variable and put the condition between try and catch same that
val comeFrom = try {
args.comeFrom.toString()
}catch (e:Exception){
"0"
}
I'm trying to setStyle to my custom dialog that extends dialogFragment,
constructor looks like:
MyCustomDialog() {
super();
setStyle(STYLE_NO_FRAME, 0);
}
and I still see the frame around my layout.
Does anyone have any ideas?
Try calling in onCreate(...) instead and not in the constructor.
According to the setStyle() description in the DialogFragment documentation:
Calling this after the fragment's Dialog is created will have no
effect
In my opinion, it is better to override theme getter
override fun getTheme(): Int {
return R.style.BottomSheetDialogTheme
}
try adding this to the onCreate method in DialogFragment:
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Material_Dialog_MinWidth);
If you want to set a custom theme for your a dialog you can do it this way...
AlertDialog.Builder(context, R.style.MyDialogTheme) ...
This should be a simple task, but for some reason I can find a way to set the title of a DialogFragment. (I am setting the dialog contents using onCreateView overload).
The default style leaves a place for the title, but I can't find any method on the DialogFragment class to set it.
The title is somehow magically set when the onCreateDialog method is used to set the contents, so I wonder if this is by design, or there is a special trick to set it when using the onCreateView overload.
You can use getDialog().setTitle("My Dialog Title")
Just like this:
public static class MyDialogFragment extends DialogFragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Set title for this dialog
getDialog().setTitle("My Dialog Title");
View v = inflater.inflate(R.layout.mydialog, container, false);
// ...
return v;
}
// ...
}
Does overriding onCreateDialog and setting the title directly on the Dialog work? Like this:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setTitle("My Title");
return dialog;
}
Jason's answer used to work for me, but now it needs the following additions to get the title to show.
Firstly, in your MyDialogFragment's onCreate() method, add:
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogFragmentStyle);
Then, in your styles.xml file, add:
<style name="MyDialogFragmentStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">false</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">false</item>
</style>
After hours of trying different things, this is the only one that has done the trick for me.
NB - You may need to change the Theme.AppCompat.Light.Dialog.Alert to something else in order to match the style of your theme.
DialogFragment could be represented as dialog and as Activity. Use code below that would work properly for both
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getShowsDialog()) {
getDialog().setTitle(marketName);
} else {
getActivity().setTitle(marketName);
}
}
You can take a look at the official docs.
The way i did is like this:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("My Title");
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.my_layout, null);
builder.setView(view);
return builder.create();
}
Similar to Ban Geoengineering's answer, but with a few modifications, so instead of coding what specific theme to use in the DialogFragment, I override the default style used by DialogFragments in my styles.xml.
set the title in the androidx.fragment.app.DialogFragment.
class EditBatteryLevelFragment:DialogFragment(),SelfClosingFragment.Host
{
override fun onCreateView(
inflater:LayoutInflater,container:ViewGroup?,savedInstanceState:Bundle?
):View
{
// set dialog title
requireDialog().setTitle(R.string.edit_battery_level__title)
// .....
return someView
}
}
in your app theme in styles.xml, override android:dialogTheme, which is the default style used by DialogFragment instances.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents">
<!-- BONUS READING: override material colors here, too https://material.io/develop/android/theming/color -->
<!-- override DialogFragment theme of those spawned by activities with this theme -->
<item name="android:dialogTheme">#style/AppTheme.Dialog</item>
</style>
<!-- ... -->
also in styles.xml, declare the dialog theme that will be used by DialogFragment instances. it's important for this style to inherit from ThemeOverlay so that it will preserve your app's theme colors.
<!-- ... -->
<!-- define the style for your dialog -->
<style name="AppTheme.Dialog" parent="ThemeOverlay.MaterialComponents.Dialog">
<!-- add a minimun width to the dialog, so it's not too narrow -->
<item name="android:windowMinWidthMajor">#dimen/abc_dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">#dimen/abc_dialog_min_width_minor</item>
<!-- display the title for dialogs -->
<item name="android:windowNoTitle">false</item>
</style>
</resources>
make sure that the activity that is spawning the DialogFragment is using the defined AppTheme.
If you are using view binding:
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
binding = YourDialogXmlBinding.inflate(getLayoutInflater());
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
builder.setTitle("Your title here")
.setView(binding.getRoot());
return builder.create();
}