How to set rounded corners for Spinner DropDown? - android

I need to customize spinner DropDown. It should be wits rounded corners.
Now it looks like this:
Closed
Open
This solution doesn't work.
Layout:
<androidx.appcompat.widget.AppCompatSpinner
android:id="#+id/messageSubject"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="#style/Text.Default.Normal"
android:background="#color/transparent"
android:minHeight="#dimen/grid_6_25"
android:layout_marginTop="#dimen/grid_1_75"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/supportQuestion" />
Fragment:
class SupportFragment : Fragment(R.layout.fragment_support) {
private val viewBinding by viewBinding<FragmentSupportBinding>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
}
private fun initView() {
val adapter = ArrayAdapter.createFromResource(
requireContext(),
R.array.message_subject,
R.layout.spinner_selected
).also { adapter ->
adapter.setDropDownViewResource(R.layout.spinner_dropdown)
}
viewBinding.messageSubject.adapter = NothingSelectedSpinnerAdapter(requireContext(), adapter, R.layout.spinner_hint)
}
companion object {
fun newInstance() = SupportFragment()
}
}

Create a Round Background spinnerbg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#3B3B3B" />
<corners android:radius="#dimen/_4sdp" />
</shape>
Add it to Styles.
<style name="SpinnerTheme" parent="android:Widget.Material.Spinner.Underlined">
<item name="android:background">#drawable/spinnerbg
</item>
<item name="android:popupBackground">#drawable/spinnerbg
</item>
<item name="android:textAlignment">textStart</item>
</style>
Use the style
<androidx.appcompat.widget.AppCompatSpinner
android:id="#+id/spinner_season"
style="#style/SpinnerTheme"
android:layout_width="#dimen/_100sdp"
android:layout_height="#dimen/_30sdp"
android:layout_alignParentEnd="true"
android:layout_gravity="end"
android:layout_marginEnd="#dimen/_10sdp"
android:spinnerMode="dropdown" />
In the java file Add your custom layout if you need.
ArrayAdapter aa = new ArrayAdapter(context, R.layout.item_spinner, R.id.textview, season1);
aa.setDropDownViewResource(R.layout.item_spinner_dropdown);

Create a background.xml finl and set this to the spinner background
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="30dp"/>
<solid
android:color="#color/colorWhite"/>
<stroke
android:color="#color/colorGray"
android:width="2dp"/>
</shape>
#color/colorWhite and #color/colorGray you can choose accordingly to your needs.
Then set it like this:
<androidx.appcompat.widget.AppCompatSpinner
android:id="#+id/messageSubject"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="#style/Text.Default.Normal"
android:background="#drawable/background"
android:minHeight="#dimen/grid_6_25"
android:layout_marginTop="#dimen/grid_1_75"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/supportQuestion" />

Related

Android progressbar set different background drawable on progress 0 and progress 100

I am trying to implement a circular download progress bar which can show different drawable
when the progress is 0(download not started)
when the progress is > 0 && < 100 (download in progress)
when the progress is 100(download complete)
I was able to implement the showing of circular progress bar when the progress is > 0 && < 100
with the below code
circle.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="ring"
android:thicknessRatio="16"
android:useLevel="false">
<solid android:color="#DDD" />
</shape>
</item>
<item>
<rotate
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:shape="ring"
android:thicknessRatio="16"
android:useLevel="true">
<gradient
android:endColor="#color/colorPrimary"
android:startColor="#color/colorAccent"
android:type="sweep" />
</shape>
</rotate>
</item>
</layer-list>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:id="#+id/progress_bar"
style="#style/CircularDeterminateProgressBar"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:progress="60" />
<TextView
android:id="#+id/text_view_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintBottom_toBottomOf="#+id/progress_bar"
app:layout_constraintEnd_toEndOf="#+id/progress_bar"
app:layout_constraintStart_toStartOf="#+id/progress_bar"
app:layout_constraintTop_toTopOf="#+id/progress_bar"
tools:text="60%" />
<Button
android:id="#+id/button_decr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- 10%"
app:layout_constraintStart_toStartOf="#+id/progress_bar"
app:layout_constraintTop_toBottomOf="#+id/progress_bar" />
<Button
android:id="#+id/button_incr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+ 10%"
app:layout_constraintEnd_toEndOf="#+id/progress_bar"
app:layout_constraintTop_toBottomOf="#+id/progress_bar" />
</androidx.constraintlayout.widget.ConstraintLayout>
and my activity as below
class MainActivity : AppCompatActivity() {
private var progr = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
updateProgressBar()
button_incr.setOnClickListener {
if (progr <= 90) {
progr += 10
updateProgressBar()
}
}
button_decr.setOnClickListener {
if (progr >= 10) {
progr -= 10
updateProgressBar()
}
}
}
private fun updateProgressBar() {
progress_bar.progress = progr
text_view_progress.text = "$progr%"
}
}
I am not sure how to set a different drawable(download icon) when the download progress is 0 (not started) and other different drawable(download complete icon) when the download progress is 100.
Any pointers or solution would be really helpful?
Solution 1 : Use a LevelListDrawable. You will be able to define the different drawables to be used for different levels.
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:maxLevel="0" android:drawable="#drawable/ic_wifi_signal_1" />
<item android:maxLevel="1" android:drawable="#drawable/ic_wifi_signal_2" />
<item android:maxLevel="2" android:drawable="#drawable/ic_wifi_signal_3" />
<item android:maxLevel="3" android:drawable="#drawable/ic_wifi_signal_4" />
</level-list>
Documentation :
https://developer.android.com/reference/android/graphics/drawable/LevelListDrawable
Solution 2 : Update the drawable dynamically using ProgressBar.setIndeterminateDrawable() whenever you update the progress bar level.
Documentation :
https://developer.android.com/reference/android/widget/ProgressBar#setIndeterminateDrawable(android.graphics.drawable.Drawable)

Toggle Button View Retains State

In one of my App's fragments the layout uses a toggle button defined as:
<ToggleButton
android:id="#+id/custom_toggle_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="4dp"
android:minWidth="110dp"
android:minHeight="36dp"
android:background="#drawable/toggle_button_bg_bw"
android:textColor="#drawable/toggle_color_bw"
android:textOff="#string/text_off"
android:textOn="#string/text_on"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/stm"
app:layout_constraintTop_toTopOf="parent" />
Background drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="#drawable/black_button_selected"
android:state_checked="true" />
<item
android:drawable="#drawable/white_button_unselected" />
</selector>
black_button_selected:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="2dp"
android:color="#color/colorGreen" />
<solid
android:color="#color/colorBlack" />
<corners android:radius="3dp" />
</shape>
white_button_unselected:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="2dp"
android:color="#color/colorGreen" />
<solid
android:color="#color/colorWhite" />
<corners android:radius="3dp" />
</shape>
TextColor drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="false"
android:color="#color/colorBlack" />
<item
android:state_checked="true"
android:color="#color/colorWhite" />
</selector>
In createView following code is called. options_view contains other buttons and view elements, which is attached to editorView and editorView is a part of this fragment layout.
optionsViewBinding = DataBindingUtil.inflate(
inflater,
R.layout.options_view,
binding.editorView,
true
)
optionsViewBinding.run {
customToggleButton.isChecked = false
customToggleButton.setOnClickListener {
someFunction(customToggleButton.isChecked)
}
}
Problem I am facing is, when I toggle the switch to 'on' and move on to some other fragment and come back to fragment with this toggle button, while the state of the toggle button has reset to 'false'/OFF state and yet the view on display shows it in its 'on' state.
What am I missing here?
You could try a few diferrent things but I dont guarantee they will work.
I personally try to avoid setting things in onCreateView, because views are not always created there. The problem could be that you change the state of the button before the view is fully initialized and it then kind of overrides the state of the ToggleButton so you have certain state set and wrong view. So put this lines in OnViewCreated:
customToggleButton.isChecked = false
customToggleButton.setOnClickListener {
someFunction(customToggleButton.isChecked)
}
Also, if you can leave the toggleButtonstate when you change fragments, you could just omit below line and it should be keeping the state fine and the background showing should be correct:
customToggleButton.isChecked = false
I have not been able to solve this issue, however I have been able to work out an alternative, it may not be the most elegant alternative but it works.
Create a custom button class:
class CustomToggleButton #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatButton(context, attrs, defStyleAttr) {
var isChecked = false
var onOffResID = Array<Int>(2) { 0 }
var onOffTextColorId = Array<Int>(2) { 0 }
fun initButton() {
// Should crash if resource ID invalid
background = AppCompatResources.getDrawable(context, onOffResID[0])
setTextColor(context.resources.getColor(onOffTextColorId[0]))
}
fun onClick() {
isChecked = !isChecked
val index = if (isChecked) 1 else 0
background = AppCompatResources.getDrawable(context, onOffResID[index])
setTextColor(context.resources.getColor(onOffTextColorId[index]))
}
}
In fragment onCreateView or onViewCreated:
customToggleButton.onOffResID = arrayOf(R.drawable.white_button_unselected, R.drawable.black_button_selected)
customToggleButton.onOffTextColorId = arrayOf(R.color.colorBlack, R.color.colorWhite)
customToggleButton.initButton()
customToggleButton.setOnClickListener {
customToggleButton.onClick()
someFunction(customToggleButton.isChecked)
}

Small balls native component to show current page [duplicate]

Probably many of you (as me), have problem with creating ViewPager with bottom dots, like this:
How do you create such an Android ViewPager?
All we need are: ViewPager, TabLayout and 2 drawables for selected and default dots.
Firstly, we have to add TabLayout to our screen layout, and connect it with ViewPager. We can do this in two ways:
Nested TabLayout in ViewPager
<androidx.viewpager.widget.ViewPager
android:id="#+id/photos_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.viewpager.widget.ViewPager>
In this case TabLayout will be automatically connected with ViewPager, but TabLayout will be next to ViewPager, not over it.
Separate TabLayout
<androidx.viewpager.widget.ViewPager
android:id="#+id/photos_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
In this case, we can put TabLayout anywhere, but we have to connect TabLayout with ViewPager programmatically
ViewPager pager = (ViewPager) view.findViewById(R.id.photos_viewpager);
PagerAdapter adapter = new PhotosAdapter(getChildFragmentManager(), photosUrl);
pager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(pager, true);
Once we created our layout, we have to prepare our dots. So we create three files: selected_dot.xml, default_dot.xml and tab_selector.xml.
selected_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="8dp"
android:useLevel="false">
<solid android:color="#color/colorAccent"/>
</shape>
</item>
</layer-list>
default_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="8dp"
android:useLevel="false">
<solid android:color="#android:color/darker_gray"/>
</shape>
</item>
</layer-list>
tab_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/selected_dot"
android:state_selected="true"/>
<item android:drawable="#drawable/default_dot"/>
</selector>
Now we need to add only 3 lines of code to TabLayout in our XML layout.
app:tabBackground="#drawable/tab_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
First Create a layout, in that give one LinerLayout for Dots which show over your View Pager
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="#+id/pager_dots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:background="#android:color/transparent"
android:gravity="center_horizontal"
android:orientation="horizontal">
</LinearLayout>
</RelativeLayout>
After that create 2 drawables
1. Unselected Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#android:color/transparent"/>
<size android:width="12dp" android:height="12dp"/>
<stroke android:width="1dp" android:color="#ffffff"/>
</shape>
2. Selected Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#android:color/transparent"/>
<size android:width="12dp" android:height="12dp"/>
<stroke android:width="1dp" android:color="#000000"/>
</shape>
After that set adapter
private LinearLayout llPagerDots;
private ViewPager viewPager;
private ArrayList<String> eventImagesUrl;
private HomeViewPagerAdapter homeViewPagerAdapter;
private ImageView[] ivArrayDotsPager;
public void setUpViewPager() {
viewPager = (ViewPager) findViewById(R.id.view_pager);
llPagerDots = (LinearLayout) findViewById(R.id.pager_dots);
homeViewPagerAdapter = new HomeViewPagerAdapter(mContext, eventImagesUrl);
viewPager.setAdapter(homeViewPagerAdapter);
setupPagerIndidcatorDots();
ivArrayDotsPager[0].setImageResource(R.drawable.page_indicator_selected);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < ivArrayDotsPager.length; i++) {
ivArrayDotsPager[i].setImageResource(R.drawable.page_indicator_unselected);
}
ivArrayDotsPager[position].setImageResource(R.drawable.page_indicator_selected);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Create a method setupPagerIndidcatorDots() :
private void setupPagerIndidcatorDots() {
ivArrayDotsPager = new ImageView[eventImagesUrl.size()];
for (int i = 0; i < ivArrayDotsPager.length; i++) {
ivArrayDotsPager[i] = new ImageView(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 0, 5, 0);
ivArrayDotsPager[i].setLayoutParams(params);
ivArrayDotsPager[i].setImageResource(R.drawable.page_indicator_unselected);
//ivArrayDotsPager[i].setAlpha(0.4f);
ivArrayDotsPager[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.setAlpha(1);
}
});
llPagerDots.addView(ivArrayDotsPager[i]);
llPagerDots.bringToFront();
}
You can check out my library to handle your request : https://github.com/tommybuonomo/dotsindicator
In your XML layout
<com.tbuonomo.viewpagerdotsindicator.DotsIndicator
android:id="#+id/dots_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
app:dotsColor="#color/colorPrimary"
app:dotsSize="16dp"
app:dotsWidthFactor="3"
/>
In your Java code
dotsIndicator = (DotsIndicator) findViewById(R.id.dots_indicator);
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ViewPagerAdapter();
viewPager.setAdapter(adapter);
dotsIndicator.setViewPager(viewPager);
When you want something similar to this with the latest ViewPager2 and Kotlin
Everything is self-explaining, no need to explain!
1. Your Activity or Fragment
val imageList = listOf(
ImageModel(R.drawable.offer1),
ImageModel(R.drawable.splash),
ImageModel(R.drawable.offer1),
ImageModel(R.drawable.splash2)
)
val adapter = HomeOffersAdapter()
adapter.setItem(imageList)
photos_viewpager.adapter = adapter
TabLayoutMediator(tab_layout, photos_viewpager) { tab, position ->
}.attach()
}
2. Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_200">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/photos_viewpager"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_200" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom|center"
app:tabBackground="#drawable/tab_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
app:tabSelectedTextColor="#android:color/transparent"
app:tabTextColor="#android:color/transparent" />
3. Drawable: tab_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/dot_selected" android:state_selected="true" />
<item android:drawable="#drawable/dot_default" />
4. Drawable: dot_selected.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thickness="#dimen/dp_8"
android:useLevel="false">
<solid android:color="#color/colorPrimary" />
<stroke
android:width="#dimen/dp_1"
android:color="#android:color/white" />
5. Drawable: dot_default.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thickness="#dimen/dp_8"
android:useLevel="false">
<solid android:color="#android:color/transparent" />
<stroke
android:width="#dimen/dp_1"
android:color="#android:color/white" />
6. Adapter
class HomeOffersAdapter : RecyclerView.Adapter<HomeOffersAdapter.HomeOffersViewHolder>() {
private var list: List<ImageModel> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeOffersViewHolder {
return HomeOffersViewHolder(parent)
}
override fun onBindViewHolder(holder: HomeOffersViewHolder, position: Int) {
holder.bind(list[position])
}
fun setItem(list: List<ImageModel>) {
this.list = list
notifyDataSetChanged()
}
override fun getItemCount(): Int = list.size
class HomeOffersViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
constructor(parent: ViewGroup) : this(
LayoutInflater.from(parent.context).inflate(
R.layout.pager_item,
parent, false
)
)
fun bind(imageModel: ImageModel) {
itemView.offerImage.setImageResource(imageModel.image)
}
}
}
7. Layout: pager_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/offerImage"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_200"
android:adjustViewBounds="true"
android:scaleType="fitXY"
tools:src="#drawable/offer1" />
2021, how to actually do it. ViewPager2 only.
Refer to this excellent short article, which has a couple of problems:
https://medium.com/#adrian.kuta93/android-viewpager-with-dots-indicator-a34c91e59e3a
Starting with a normal Android Studio default project as of 2021, with a reasonably new minimum (24 currently)...
General concept:
Make a standard TabLayout, but replace each "tab unit" with "a little dot" rather than the usual text.
In TabLayout, you can indeed replace each "tab unit" using "tabBackground":
app:tabBackground="#drawable/tab_selector"
So add the following to the XML of your screen, which has a ViewPager2:
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:background="#00FFFFFF"
app:tabBackground="#drawable/tab_selector"
app:tabIndicatorGravity="center"
app:tabIndicatorHeight="0dp"/>
Notice carefully we are replacing each and every one of the "tab units" in the TabLayout, with our own "tab_selector".
To be completely clear, "tabBackground" means the individual little "tab units", not the whole tab bar system.
(Aside, note that the two tricks tabIndicatorGravity and tabIndicatorHeight will indeed get rid of the "boxes" that are the usual "tab units".)
Next create three drawables in the obvious way, tab_selector and the two different dots. See the above article or 100s of examples on this page.
The magic code:
In your onCreate have the expected code ...
viewPager = findViewById(R.id.simple_slide_pager);
tab_layout = findViewById(R.id.tab_layout);
viewPager.setAdapter(new ScreenSlidePagerAdapter(this));
and then here at last is the magic code fragment to make it work. Follow the above by:
Up to date for 2021:
TabLayoutMediator tabLayoutMediator =
new TabLayoutMediator(tab_layout, viewPager, true,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(
#NonNull TabLayout.Tab tab, int position) { }
}
);
tabLayoutMediator.attach();
It's done.
(Inside onConfigureTab you can do any sound effects or whatever the heck might be needed. For shorter syntax see the key comment by #F1iX above.)
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="#+id/vpImage"
android:layout_width="match_parent"
android:layout_height="#dimen/_150sdp" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tlImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#drawable/selector_product_image"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
app:tabMaxWidth="12dp"
app:tabRippleColor="#null" />
</androidx.appcompat.widget.LinearLayoutCompat>
ImageAdapter imageAdapter = new ImageAdapter(getActivity(), arrayListSlider);
binding.vpImage.setOffscreenPageLimit(1);
binding.vpImage.setAdapter(imageAdapter);
binding.tlImage.setupWithViewPager(binding.vpImage);
selector_product_image.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/image_selected" android:state_selected="true" />
<item android:drawable="#drawable/image_unselected" />
</selector>
image_selected.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false">
<solid android:color="#color/colorAccent" />
</shape>
</item>
</layer-list>
image_unselected.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false">
<solid android:color="#color/colorPrimary" />
</shape>
</item>
</layer-list>
ImageAdapter.java
class ImageAdapter extends PagerAdapter {
private Context context;
private ArrayList<ImageModel> arrayList;
private LayoutInflater layoutInflater;
public ImageAdapter(Context context, ArrayList<ImageModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view == ((View) o);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = layoutInflater.inflate(R.layout.row_slider_image, container, false);
AppCompatImageView ivProductImage = view.findViewById(R.id.ivProductImage);
if (!TextUtils.isEmpty(arrayList.get(position).getImage())) {
Glide.with(context)
.load(arrayList.get(position).getImage())
.apply(new RequestOptions().placeholder(R.drawable.no_image).error(R.drawable.no_image))
.into(ivProductImage);
}
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
row_slider_image.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/ivProductImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/no_image" />
</androidx.appcompat.widget.LinearLayoutCompat>
For Viewpager2, follow the same steps which suggested by #RediOne1 and in the activity or fragment use below code to attach tablayout with viwpager2
val tabLayoutMediator = TabLayoutMediator(binding.tabLayout,binding.offersVp) { _, _ -> }
tabLayoutMediator.attach()
Your xml
<RelativeLayout
android:id="#+id/rl_speed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/ll_dashboard_buttons"
android:layout_below="#+id/ib_menu">
<com.smart.gps.speedometer.app.utils.SmartViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</com.smart.gps.speedometer.app.utils.SmartViewPager>
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#drawable/tab_selector"
app:tabIndicatorHeight="0dp"
app:tabGravity="center"
/>
create a drawable. right click on drawable -> new -> Drawable file resource
name that file
tab_selector.xml
<item android:drawable="#drawable/selected_tab"
android:state_selected="true"/>
<item android:drawable="#drawable/unselected_tab"/>
Now there is two more xml files. create two more xml files with respected name. these are the selecter indicator and unselected indicator
selected_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false">
<solid android:color="#color/highspeed"/>
</shape>
</item>
</layer-list>
unselected_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="2dp"
android:useLevel="false">
<solid android:color="#android:color/darker_gray"/>
</shape>
</item>
</layer-list>
Place ViewFlipper and viewFlipper_linear_dot_lay(Linearlayout) on samebaseline and follow the below one
viewFlipper_linear_dot_lay= (LinearLayout) findViewById(R.id.dots_lay);
setupDotsOnViewPager(images_viewFlipper);
for (int i = 0; i < images_viewFlipper.size(); i++) {
//Add Images to ViewFlipper
}
private void setupDotsOnViewPager(ArrayList images_viewFlipper) {
images_linear = new ImageView[images_viewFlipper.size()];
for (int i = 0; i < images_linear.length; i++) {
images_linear[i] = new ImageView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 0, 5, 0);
params.gravity = Gravity.BOTTOM | Gravity.CENTER;
images_linear[i].setLayoutParams(params);
images_linear[i].setImageResource(R.drawable.unselected);
viewFlipper_linear_dot_lay.addView(images_linear[i]);
viewFlipper_linear_dot_lay.bringToFront();
}
}
And OnRight & OnLeft getsures place the below code
for (int i = 0; i < images_linear.length; i++) {
images_linear[i].setImageResource(R.drawable.unselected);
}
images_linear[viewFlipper.getDisplayedChild()].setImageResource(R.drawable.selected);
Add dependencies > Sync the Gradle
implementation 'com.tbuonomo.andrui:viewpagerdotsindicator:4.1.2'
In your java code
dotsIndicator = (DotsIndicator) findViewById(R.id.dots_indicator3);
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
dotsIndicator.setViewPager(viewPager);
In your layout
<com.tbuonomo.viewpagerdotsindicator.SpringDotsIndicator
android:id="#+id/spring_dots_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:dampingRatio="0.5"
app:dotsColor="#color/material_white"
app:dotsStrokeColor="#color/material_yellow"
app:dotsCornerRadius="2dp"
app:dotsSize="16dp"
app:dotsSpacing="6dp"
app:dotsStrokeWidth="2dp"
app:stiffness="300"
/>

How to make custom dialog with rounded corners in android

What I am trying to do: I am trying to make a custom dialog in android With rounded corners.
What is happening: I am able to make custom dialog but it doesn't have rounded corners. I tried adding a selector but still I couldn't achieve rounded corners.
Below is my code for the same:
Java code:
private void launchDismissDlg() {
dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dlg_dismiss);
dialog.setCanceledOnTouchOutside(true);
Button btnReopenId = (Button) dialog.findViewById(R.id.btnReopenId);
Button btnCancelId = (Button) dialog.findViewById(R.id.btnCancelId);
btnReopenId.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnCancelId.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
dialog.show();
}
xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text=""I WOULD LIKE TO DISMISS THE VENDOR""
android:textColor="#color/col_dlg_blue_light"
android:textSize="14sp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="BECAUSE"
android:textColor="#android:color/black"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnReopenId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#color/col_dlg_green_light"
android:text="REOPEN"
android:padding="5dp"
android:textSize="14sp"
android:textColor="#android:color/white"
android:textStyle="bold" />
<Button
android:id="#+id/btnCancelId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#color/col_dlg_pink_light"
android:text="CANCEL"
android:padding="5dp"
android:textSize="14sp"
android:textColor="#android:color/white"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</LinearLayout>
Create an XML file in drawable, say dialog_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#color/white"/>
<corners
android:radius="30dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
set it as the background in your layout XML:
android:background="#drawable/dialog_bg"
Set the background of the dialog's root view to transparent, because Android puts your dialog layout within a root view that hides the corners in your custom layout.
Java:
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Kotlin:
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
With the Androidx library and Material Components Theme you can override the getTheme() method:
import androidx.fragment.app.DialogFragment
class RoundedDialog: DialogFragment() {
override fun getTheme() = R.style.RoundedCornersDialog
//....
}
with:
<style name="RoundedCornersDialog" parent="#style/Theme.MaterialComponents.Dialog">
<item name="dialogCornerRadius">16dp</item>
</style>
Or you can use the MaterialAlertDialogBuilder included in the Material Components Library:
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class RoundedAlertDialog : DialogFragment() {
//...
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return MaterialAlertDialogBuilder(requireActivity(), R.style.MaterialAlertDialog_rounded)
.setTitle("Test")
.setMessage("Message")
.setPositiveButton("OK", null)
.create()
}
}
with:
<style name="MaterialAlertDialog_rounded" parent="#style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="shapeAppearanceOverlay">#style/DialogCorners</item>
</style>
<style name="DialogCorners">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">16dp</item>
</style>
If you don't need a DialogFragment just use the MaterialAlertDialogBuilder.
You need to do the following:
Create a background with rounded corners for the Dialog's background:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#fff" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
Now in your Dialog's XML file in the root layout use that background with required margin:
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:background="#drawable/dialog_background"
finally in the java part you need to do this:
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(layoutResId);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
This works perfectly for me.
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
this works for me
Setting
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
will prevent dialog to cast a shadow.
Solution is to use
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_rounded_background);
where is R.drawable.dialog_rounded_background
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" android:padding="10dp">
<solid
android:color="#color/dialog_bg_color"/>
<corners
android:radius="30dp" />
</shape>
</item>
</layer-list>
If you use Material Components:
CustomDialog.kt
class CustomDialog: DialogFragment() {
override fun getTheme() = R.style.RoundedCornersDialog
}
styles.xml
<style name="RoundedCornersDialog" parent="Theme.MaterialComponents.Dialog">
<item name="dialogCornerRadius">dimen</item>
</style>
dimen.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="weight">1</integer>
<dimen name="dialog_top_radius">21dp</dimen>
<dimen name="textview_dialog_head_min_height">50dp</dimen>
<dimen name="textview_dialog_drawable_padding">5dp</dimen>
<dimen name="button_dialog_layout_margin">3dp</dimen>
</resources>
styles.xml
<style name="TextView.Dialog">
<item name="android:paddingLeft">#dimen/dimen_size</item>
<item name="android:paddingRight">#dimen/dimen_size</item>
<item name="android:gravity">center_vertical</item>
<item name="android:textColor">#color/black</item>
</style>
<style name="TextView.Dialog.Head">
<item name="android:minHeight">#dimen/textview_dialog_head_min_height</item>
<item name="android:textColor">#color/white</item>
<item name="android:background">#drawable/dialog_title_style</item>
<item name="android:drawablePadding">#dimen/textview_dialog_drawable_padding</item>
</style>
<style name="TextView.Dialog.Text">
<item name="android:textAppearance">#style/Font.Medium.16</item>
</style>
<style name="Button" parent="Base.Widget.AppCompat.Button">
<item name="android:layout_height">#dimen/button_min_height</item>
<item name="android:layout_width">match_parent</item>
<item name="android:textColor">#color/white</item>
<item name="android:gravity">center</item>
<item name="android:textAppearance">#style/Font.Medium.20</item>
</style>
<style name="Button.Dialog">
<item name="android:layout_weight">#integer/weight</item>
<item name="android:layout_margin">#dimen/button_dialog_layout_margin</item>
</style>
<style name="Button.Dialog.Middle">
<item name="android:background">#drawable/button_primary_selector</item>
</style>
dialog_title_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="#color/primaryDark"
android:startColor="#color/primaryDark" />
<corners
android:topLeftRadius="#dimen/dialog_top_radius"
android:topRightRadius="#dimen/dialog_top_radius" />
</shape>
dialog_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/backgroundDialog" />
<corners
android:topLeftRadius="#dimen/dialog_top_radius"
android:topRightRadius="#dimen/dialog_top_radius" />
<padding />
</shape>
dialog_one_button.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/dailog_background"
android:orientation="vertical">
<TextView
android:id="#+id/dialogOneButtonTitle"
style="#style/TextView.Dialog.Head"
android:text="Process Completed" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/dialogOneButtonText"
style="#style/TextView.Dialog.Text"
android:text="Return the main menu" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/dialogOneButtonOkButton"
style="#style/Button.Dialog.Middle"
android:text="Ok" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
OneButtonDialog.java
package com.example.sametoztoprak.concept.dialogs;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.example.sametoztoprak.concept.R;
import com.example.sametoztoprak.concept.models.DialogFields;
/**
* Created by sametoztoprak on 26/09/2017.
*/
public class OneButtonDialog extends Dialog implements View.OnClickListener {
private static OneButtonDialog oneButtonDialog;
private static DialogFields dialogFields;
private Button dialogOneButtonOkButton;
private TextView dialogOneButtonText;
private TextView dialogOneButtonTitle;
public OneButtonDialog(AppCompatActivity activity) {
super(activity);
}
public static OneButtonDialog getInstance(AppCompatActivity activity, DialogFields dialogFields) {
OneButtonDialog.dialogFields = dialogFields;
return oneButtonDialog = (oneButtonDialog == null) ? new OneButtonDialog(activity) : oneButtonDialog;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_one_button);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialogOneButtonTitle = (TextView) findViewById(R.id.dialogOneButtonTitle);
dialogOneButtonText = (TextView) findViewById(R.id.dialogOneButtonText);
dialogOneButtonOkButton = (Button) findViewById(R.id.dialogOneButtonOkButton);
dialogOneButtonOkButton.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
dialogOneButtonTitle.setText(dialogFields.getTitle());
dialogOneButtonText.setText(dialogFields.getText());
dialogOneButtonOkButton.setText(dialogFields.getOneButton());
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dialogOneButtonOkButton:
break;
default:
break;
}
dismiss();
}
}
I made a new way without having a background drawable is that make it have CardView as parent and give it a app:cardCornerRadius="20dp" and then add this in the java class dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
It's another way to make it .
You can simply use MaterialAlertDialogBuilder to create custom dialog with rounded corners.
First create a style for the material dialog like this :
<style name="MyRounded.MaterialComponents.MaterialAlertDialog" parent="#style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="shapeAppearanceOverlay">#style/ShapeAppearanceOverlay.App.CustomDialog.Rounded
</item>
<item name="colorSurface">#color/YOUR_COLOR</item>
</style>
<style name="ShapeAppearanceOverlay.App.CustomDialog.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">10dp</item>
</style>
then create a Alert Dialog object in Java class like this :
AlertDialog alertDialog = new MaterialAlertDialogBuilder(this,R.style.MyRounded_MaterialComponents_MaterialAlertDialog) // for fragment you can use getActivity() instead of this
.setView(R.layout.custom_layout) // custom layout is here
.show();
final EditText editText = alertDialog.findViewById(R.id.custom_layout_text); // access to text view of custom layout
Button btn = alertDialog.findViewById(R.id.custom_layout_btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: " + editText.getText().toString());
}
});
That's all you need to do.
For anyone who like do things in XML, specially in case where you are using Navigation architecture component actions in order to navigate to dialogs
You can use:
<style name="DialogStyle" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<!-- dialog_background is drawable shape with corner radius -->
<item name="android:background">#drawable/dialog_background</item>
<item name="android:windowBackground">#android:color/transparent</item>
</style>
simplest way is to use from
CardView and its card:cardCornerRadius
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="#+id/cardlist_item"
android:layout_width="match_parent"
android:layout_height="130dp"
card:cardCornerRadius="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="#color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="12sp"
android:orientation="vertical"
android:weightSum="1">
</RelativeLayout>
</android.support.v7.widget.CardView>
And when you are creating your Dialog
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
You can use the shape for the background as-
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/transparent"/>
<corners android:radius="10dp" />
<padding android:left="10dp" android:right="10dp"/>
</shape>
Have a look on this for the details.
Here is a Basic Solution:
<style name="Style_Dialog_Rounded_Corner" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowBackground">#drawable/dialog_rounded_corner</item>
<item name="android:windowMinWidthMinor">85%</item>
</style>
in Drawable create shape:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="12dp" />
</shape>
Pass style in Builder Constructor
AlertDialog alert = new AlertDialog.Builder(MainActivity.this,R.style.Style_Dialog_Rounded_Corner).create();
Here is the complete solution if you want to control the corner radius of the dialog and preserve elevation shadow
Dialog:
class OptionsDialog: DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View {
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return inflater.inflate(R.layout.dialog_options, container)
}
}
dialog_options.xml layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="40dp"
app:cardElevation="20dp"
app:cardCornerRadius="12dp">
<androidx.constraintlayout.widget.ConstraintLayout
id="#+id/actual_content_goes_here"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</FrameLayout>
The key is to wrap the CardView with another ViewGroup (here FrameLayout) and set margins to create space for the elevation shadow.
For API level >= 28 available attribute android:dialogCornerRadius . To support previous API versions need use
<style name="RoundedDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowBackground">#drawable/dialog_bg</item>
</style>
where dialog_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape >
<solid android:color="#android:color/transparent" />
</shape>
</item>
<item
android:left="16dp"
android:right="16dp">
<shape>
<solid
android:color="#color/white"/>
<corners
android:radius="8dp" />
<padding
android:left="16dp"
android:right="16dp" />
</shape>
</item>
</layer-list>
In Kotlin, I am using a class DoubleButtonDialog.Java with line window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) as important one
class DoubleButtonDialog(context: Context) : Dialog(context, R.style.DialogTheme) {
private var cancelableDialog: Boolean = true
private var titleDialog: String? = null
private var messageDialog: String? = null
private var leftButtonDialog: String = "Yes"
// private var rightButtonDialog: String? = null
private var onClickListenerDialog: OnClickListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
//requestWindowFeature(android.view.Window.FEATURE_NO_TITLE)
setCancelable(cancelableDialog)
setContentView(R.layout.dialog_double_button)
// val btnNegative = findViewById<Button>(R.id.btnNegative)
// btnNegative.visibility = View.GONE
// if (rightButtonDialog != null) {
// btnNegative.visibility = View.VISIBLE
// btnNegative.text = rightButtonDialog
// btnNegative.setOnClickListener {
// dismiss()
// onClickListenerDialog?.onClickCancel()
// }
// }
val btnPositive = findViewById<Button>(R.id.btnPositive)
btnPositive.text = leftButtonDialog
btnPositive.setOnClickListener {
onClickListenerDialog?.onClick()
dismiss()
}
(findViewById<TextView>(R.id.title)).text = titleDialog
(findViewById<TextView>(R.id.message)).text = messageDialog
super.onCreate(savedInstanceState)
}
constructor(
context: Context, cancelableDialog: Boolean, titleDialog: String?,
messageDialog: String, leftButtonDialog: String, /*rightButtonDialog: String?,*/
onClickListenerDialog: OnClickListener
) : this(context) {
this.cancelableDialog = cancelableDialog
this.titleDialog = titleDialog
this.messageDialog = messageDialog
this.leftButtonDialog = leftButtonDialog
// this.rightButtonDialog = rightButtonDialog
this.onClickListenerDialog = onClickListenerDialog
}
}
interface OnClickListener {
// fun onClickCancel()
fun onClick()
}
In layout, we can create a dialog_double_button.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="#dimen/dimen_10"
android:background="#drawable/bg_double_button"
android:orientation="vertical"
android:padding="#dimen/dimen_5">
<TextView
android:id="#+id/title"
style="#style/TextViewStyle"
android:layout_gravity="center_horizontal"
android:layout_margin="#dimen/dimen_10"
android:fontFamily="#font/campton_semi_bold"
android:textColor="#color/red_dark4"
android:textSize="#dimen/text_size_24"
tools:text="#string/dial" />
<TextView
android:id="#+id/message"
style="#style/TextViewStyle"
android:layout_gravity="center_horizontal"
android:layout_margin="#dimen/dimen_10"
android:gravity="center"
android:textColor="#color/semi_gray_2"
tools:text="#string/diling_police_number" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimen_10"
android:gravity="center"
android:orientation="horizontal"
android:padding="#dimen/dimen_5">
<!--<Button
android:id="#+id/btnNegative"
style="#style/ButtonStyle"
android:layout_width="0dp"
android:layout_height="#dimen/dimen_40"
android:layout_marginEnd="#dimen/dimen_10"
android:layout_weight=".4"
android:text="#string/cancel" />-->
<Button
android:id="#+id/btnPositive"
style="#style/ButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/red_dark4"
android:fontFamily="#font/campton_semi_bold"
android:padding="#dimen/dimen_10"
android:text="#string/proceed"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="#dimen/text_size_20" />
</LinearLayout>
</LinearLayout>
then use drawable.xml as
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#color/white"/>
<corners
android:radius="#dimen/dimen_10" />
<padding
android:left="#dimen/dimen_10"
android:top="#dimen/dimen_10"
android:right="#dimen/dimen_10"
android:bottom="#dimen/dimen_10" />
</shape>
Create a xml in drawable ,say customd.xml.
then set it at background in your custom Dialog layout xml:
android:background="#drawable/customd"
finally in the java part for custom Dialog class you need to do this:
public class Customdialoque extends DialogFragment {
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
View view = inflater.inflate(R.layout.activity_customdialoque, container, false);
return view;
}
I implemented rounded dialog using CardView in the custom layout and setting its corner radius.
Here's my xml code.
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/bottomSheet"
android:layout_width="match_parent"
android:layout_margin="#dimen/padding_5dp"
app:cardCornerRadius="#dimen/dimen_20dp"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/main_gradient_bg"
android:paddingBottom="32dp">
<TextView
android:id="#+id/subdomain_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin_32dp"
android:layout_marginLeft="#dimen/margin_32dp"
android:layout_marginTop="#dimen/margin_50dp"
android:fontFamily="#font/nunito_sans"
android:text="#string/enter_subdomain"
android:textColor="#color/white"
android:textSize="#dimen/size_18sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimen_45dp"
app:layout_constraintLeft_toRightOf="#id/subdomain_label"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_info_24" />
<EditText
android:id="#+id/subdomain_edit_text_bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/dimen_20dp"
android:layout_marginLeft="#dimen/dimen_20dp"
android:layout_marginEnd="#dimen/dimen_20dp"
android:layout_marginRight="#dimen/dimen_20dp"
android:textColor="#color/white"
android:theme="#style/EditTextTheme"
app:layout_constraintTop_toBottomOf="#id/subdomain_label" />
<Button
android:id="#+id/proceed_btn"
android:layout_width="#dimen/dimen_150dp"
android:layout_height="#dimen/margin_50dp"
android:layout_marginTop="#dimen/margin_30dp"
android:background="#drawable/primary_btn_bg"
android:text="#string/proceed"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="#dimen/size_18sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/subdomain_edit_text_bottom_sheet" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
After that, i called it in Kotlin as follows :-
val builder = AlertDialog.Builder(mContext)
val viewGroup: ViewGroup = findViewById(android.R.id.content)
val dialogView: View =
LayoutInflater.from(mContext).inflate(R.layout.subdomain_bottom_sheet,
viewGroup, false)
val alertDialog: AlertDialog = builder.create()
alertDialog.setView(dialogView,0,0,0,0)
alertDialog.show()
val windowParam = WindowManager.LayoutParams()
windowParam.copyFrom(alertDialog.window!!.attributes)
windowParam.width = AppConstant.getDisplayMetricsWidth(mContext) - 100
windowParam.height = WindowManager.LayoutParams.WRAP_CONTENT
windowParam.gravity = Gravity.CENTER
alertDialog.window!!.attributes = windowParam
alertDialog.window!!.setBackgroundDrawable
(ColorDrawable(Color.TRANSPARENT))
Where last line is very important. Missing that would cause a color(mostly white) to show behind the corners.
The accepted answer did round the corners for me, but unless I switched to a Material design theme, making the window background transparent had no effect and I still saw a square, shadowed background of the dialog inside my rounded background. And I don't want to switch to a Material theme because that changes the functionality of date and time pickers.
Instead, I had to hide the backgrounds of several subviews of the dialog in order to see the rounded background. And after doing all that, it was easier just to add the rounded background in code, too. So here's a fully programmatic (no XML) solution. This is in the onStart method of my DialogFragment subclass:
// add rounded corners
val backgroundShape = GradientDrawable()
backgroundShape.cornerRadius = 10.0f
backgroundShape.setColor(Color.BLUE)
this.dialog.window?.decorView?.background = backgroundShape
// make the backgrounds of the dialog elements transparent so we can see the rounded corner background
val topPanelId = this.context.resources.getIdentifier("topPanel", "id", "android")
val topPanel = this.dialog.findViewById<View>(topPanelId)
topPanel?.setBackgroundColor(Color.TRANSPARENT)
val contentPanelId = this.context.resources.getIdentifier("contentPanel", "id", "android")
val contentPanel = this.dialog.findViewById<View>(contentPanelId)
contentPanel?.setBackgroundColor(Color.TRANSPARENT)
val customPanelId = this.context.resources.getIdentifier("customPanel", "id", "android")
val customPanel = this.dialog.findViewById<View>(customPanelId)
customPanel?.setBackgroundColor(Color.TRANSPARENT)
val buttonPanelId = this.context.resources.getIdentifier("buttonPanel", "id", "android")
val buttonPanel = this.dialog.findViewById<View>(buttonPanelId)
buttonPanel?.setBackgroundColor(Color.TRANSPARENT)
Here is another way in kotlin:
val model = ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED, 32.0f)
.build()
val shape = MaterialShapeDrawable(model)
shape.fillColor = ContextCompat.getColorStateList(context, R.color.white)
ViewCompat.setBackground(dialogContentView, shape)
And then change the dialog window
dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)

Custom FragmentDialog with round corners and not 100% screen width

I am creating a custom fragment dialog with round corners and with layout that would not fill the screen width (I would prefer if it just wrapped its content).
this is my rounded_dialog.xml in drawable folder, which is called by my Custom ThemeWithCorners as a background for the dialog. I also tried to set it as background to the linear layout which creates its content but nothing works.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="#android:color/white"/>
<corners android:radius="20dp"
/>
</shape>
and this is how i call the dialog:
final String FTAG = "TAG_FRAGMENT_DIALOG_CALENDAR";
dialog = (CalendarDialog) fm.findFragmentByTag(FTAG);
ft = fm.beginTransaction();
if (dialog != null)
{
ft.remove(dialog);
}
dialog = CalendarDialog.newInstance(this);
dialog.setCancelable(true);
ft.add(dialog, FTAG);
ft.show(dialog);
ft.commit();
In onCreate method of the dialog I set the style and theme:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.ThemeWithCorners);
}
This is the onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setCanceledOnTouchOutside(true);
v = (MyCalendar)inflater.inflate(R.layout.calendar_dialog, container, true)
return v;
}
I also tried to add this to onCreateDialog method as other answers on SO suggested but did not work either:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog d = super.onCreateDialog(savedInstanceState);
LayoutParams lp=d.getWindow().getAttributes();
d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
lp.width=-2;lp.height=-2;lp.gravity=Gravity.CENTER;
lp.dimAmount=0;
lp.flags=LayoutParams.FLAG_LAYOUT_NO_LIMITS | LayoutParams.FLAG_NOT_TOUCH_MODAL;
return d;
}
So to sum it up, I want round corners, not 100% width of the screen, it preferably should wrap its content. Please, please, I need some help, I am really desperate about this, I´v ebeen trying it for days!
Dialog background: dialog_rounded_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/white" />
<corners android:radius="12dp" />
</shape>
Dialog layout: dialog_rounded.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/dialog_rounded_bg"
android:minWidth="260dp"
android:orientation="vertical"
android:padding="24dp">
...
</LinearLayout>
Dialog fragment: RoundedDialog.java
public class RoundedDialog extends DialogFragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_rounded, container, false);
// Set transparent background and no title
if (getDialog() != null && getDialog().getWindow() != null) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
return view;
}
...
}
Update: If you don't set the flag Window.FEATURE_NO_TITLE, a blue line appears on top of the dialog in devices with Android ≤ 4.4.
Well, I just found a solution, I am not really happy with it though.
I set the background (rounded_dialog.xml) for the dialog like this:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/transparent"/>
<corners android:radius="10dp" />
<padding android:left="10dp" android:right="10dp"/>
</shape>
Then I set this to my dialog in its ´onCreateView´ method this way below. The rounded corners are not really necessary in this piece of code as the background is transparent, but the padding is important, because the dialog is still in fact as wide as the screen, but the padding makes it look like it is not.
getDialog().getWindow().setBackgroundDrawableResource(R.drawable.rounded_dialog);
And in the end I set background of the dialog´s components to another custom drawable which makes the corners round. I have a LinearLayout with RelativeLayout at the top and TextView at the bottom, so I set #null to the parent LinearLayout and set two different custom drawables to the two parts, one of which has rounded bottomCorners and the other one topCorners.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/title_round"
>
<RelativeLayout
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/blue_title_round_top"
android:paddingTop="4dp"
android:paddingBottom="4dp"
>
<TextView
android:id="#+id/calendarHint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/rounded_bottom"
android:layout_gravity="center"
android:gravity="center"
/>
</LinearLayout>
I believe there is a more proper solution to this as this is correct just visually, not really functionally, but enough correct for this case.
Updated 2022 answer with Kotlin and View Binding -
class InternetLostDialog : DialogFragment() {
private lateinit var binding: DialogInternetLostBinding
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
binding = DialogInternetLostBinding.inflate(LayoutInflater.from(context))
val builder = AlertDialog.Builder(requireActivity())
isCancelable = false
builder.setView(binding.root)
binding.root.setOnClickListener {
requireActivity().finish()
}
val dialog = builder.create()
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return dialog
}
}
Another way:
Use setStyle() in onCreate() method to apply a style to your DialogFragment.Then, you can use android:background same as always in the root view of your_layout.xml file.
Steps:
style.xml file (in res folder) :
<style name="DialogTheme_transparent" parent="Theme.AppCompat.Dialog">
<item name="android:windowBackground">#android:color/transparent</item>
<!--You can set other style items also, such as animations and etc-->
</style>
Create your_layout.xml file in the layout folder:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:background="#drawable/bg_corner_dialog">
...
</LinearLayout>
Create bg_corner_dialog.xml file in the drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:dither="true">
<solid android:color="#ffffff"/>
<corners android:radius="16dp"/>
</shape>
Finally apply style and layout to the your DialogFragment:
public class CustomDialogFragment extends DialogFragment {
...
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, R.style.DialogTheme_transparent);
...
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_layout, container, false);
ButterKnife.bind(this, v);
//init UI Elements...
return v;
}
}
I hope this helps you.
Best wishes
An updated solution that works for me using Kotlin.
I set the background (rounded_dialog.xml) for the dialog like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="28dp" />
<solid android:color="#color/white"/>
</shape>
then calculating the screen width programmatically then subtract the Margin value from it, using this code snippet.
val displayMetrics = DisplayMetrics()
requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
val width = displayMetrics.widthPixels
then inside onStart callback I applied that width minus Margin.
here is the full code.
#AndroidEntryPoint
class CancelDialogFragment : DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
if (dialog != null && dialog?.window != null) {
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE);
}
return inflater.inflate(R.layout.fragment_cancel_dialog, container, false)
}
override fun onStart() {
super.onStart()
val displayMetrics = DisplayMetrics()
requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
dialog?.window?.setLayout(width-64, ViewGroup.LayoutParams.WRAP_CONTENT)
}
}
XML Layout fragment_cancel_dialog
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingVertical="32dp"
android:padding="8dp"
android:layout_marginHorizontal="8dp"
android:background="#drawable/rounded_dialog"
tools:context=".ui.orders.CancelDialogFragment">
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Reason of cancellation"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="#+id/firstNameTIL"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/firstNameTIL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="24dp"
android:layout_marginTop="16dp"
app:hintAnimationEnabled="false"
app:hintEnabled="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView9">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/firstNameET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/edit_text_bg"
android:drawablePadding="12dp"
android:inputType="textPersonName"
android:paddingHorizontal="16dp"
android:paddingVertical="16dp"
android:textAlignment="viewStart"
android:textColor="#color/textColor"
android:textColorHint="#color/black" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/signUpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:layout_marginBottom="32dp"
android:background="#drawable/button_bg"
android:paddingHorizontal="56dp"
android:text="#string/confirmStr"
android:textAllCaps="false"
android:inputType="text"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firstNameTIL" />
</androidx.constraintlayout.widget.ConstraintLayout>
There is a quick fix for DialogFragment. For example, in the method onCreateDialog() add style in AlertDialog.Builder(context, style):
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_dialog_lauout, null);
return new AlertDialog.Builder(getActivity(), R.style.custom_alert_dialog)
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// do something
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}
In styles folder custom_alert_dialog
<style name="custom_alert_dialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowBackground">#drawable/corner_background</item>
</style>
In drawable folder corner_background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="8dp" />
It's tested for API >= 21
For Any One who wants to Use the AlertDialogBuilder and transparent the background and set the Drawable in XML file.
<style name="DialogStyle" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<item name="android:background">#drawable/dialog_background</item>
<item name="android:windowBackground">#android:color/transparent</item>
Set this Theme on Builder like below
private val builder: AlertDialog.Builder = AlertDialog.Builder(context,R.style.DialogStyle)
.setView(dialogView)
where is R.drawable.dialog_background
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" android:padding="10dp">
<solid
android:color="#color/dialog_bg_color"/>
<corners
android:radius="30dp" />
</shape>
</item>
I think to make rounded corners, its much easier if u make cardview as the root of your layout and add below code in onCreateView():
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transpare‌​nt)
This is an old question and it misses the simplest way of achieving rounded edges in a DialogFragment component. You can achieve this with one liner:
override fun getTheme() = R.style.RoundedCornersDialog

Categories

Resources