AlertDialog with NumberPicker rendered incorrectly

2019-03-30 21:12发布

I' have a problem about 'rendering' with my NumberPicker inside an AlertDialog.
I show to you the code:

                //setup del dialog
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setCancelable(false);

                final NumberPicker picker = new NumberPicker(activity);
                picker.setMinValue(0);
                picker.setMaxValue(5);
                //set bottoni dialog
                builder.setPositiveButton(R.string.dialog_btn_seleziona, seleziona);
                builder.setNegativeButton(R.string.dialog_btn_annulla, null);

                //visualizzo il dialog
                Dialog dialog = builder.create();
                dialog.show();

the problem is that instead of to have a result like this:
enter image description here

I have this result:
enter image description here
The blue line selector is too long, i would like the same lenght of the first picture
i founded this topic:
NumberPicker rendered incorrectly in a Dialog
that explain how to fix this problem, and the solution is:

instead of this

android:layout_width="match_parent"

You should use

android:layout_width="wrap_content"
android:layout_gravity="center"

the problem is that i dont have a layout (made by myself for this numberpicker) so i need to set this parameters programmatically, but i don't know how.

1条回答
我命由我不由天
2楼-- · 2019-03-30 21:30

Sorry, I misunderstood earlier. You just need to create a parent view and put your picker inside of that, using wrap_content. Here is how you do that in code:

final NumberPicker picker = new NumberPicker(activity);
picker.setMinValue(0);
picker.setMaxValue(5);
final FrameLayout parent = new FrameLayout(activity);
parent.addView(picker, new FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.WRAP_CONTENT,
        FrameLayout.LayoutParams.WRAP_CONTENT,
        Gravity.CENTER));
builder.setView(parent);
查看更多
登录 后发表回答