Android版本5.0中的Dialog无法使用开关控制

时间:2015-04-24 06:12:32

标签: android android-layout android-5.0-lollipop android-switch

我在我的应用程序中使用了以下switch

<Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text=""
        android:thumb="@drawable/toggle_button_color"
        android:textOff="@string/text_estimate"
        android:textOn="@string/text_accurate" 
        android:textColor="@color/white" />

switch以上我toggle_button_color.xml使用switch分别在<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="false" android:drawable="@color/red" /> <item android:state_checked="true" android:drawable="@color/green" /> </selector> 开启和关闭时将拇指颜色更改为绿色和红色。

switch

如果我将此switch添加到活动布局中,然后将其完美地填充到下面的图像中。 enter image description here enter image description here

但如果我使用Dialogm_dialog.setContentView(R.layout.mylayout);上添加此mylayout.xml,则切换如下所示。 请注意,此处layoutswitch文件,我在其中添加了switch

enter image description here

对于低于5.0的Android版本,lollipop Theme.Holo.Light正常工作正常。请注意,出于某些原因,我在我的应用中使用了SwitchCompat,因此我无法使用activity layout

我知道这里有一个类似的问题Switch crashes when clicked on Android 5.0

此处也报道https://code.google.com/p/android-developer-preview/issues/detail?id=1704。 我也尝试过上面提到的工作,为拇指和轨道添加可绘制的图像,但我不明白为什么同一个开关在Dialog上工作但在{{1}}上没有。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

谢谢大家的回复,但我自己解决了。之前我使用Dialog类实现了对话框,这导致了问题。

Dialog mDialog= new Dialog(getActivity(),android.R.style.Theme_Dialog);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.mylayout);

我甚至尝试更改themes,但它没有帮助。

然后我尝试使用DialogFragment来解决问题。

public class MyDialog extends DialogFragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    View v = inflater.inflate(R.layout.mylayout, container, false);
    return v;
    }
}

从我的Activity课程中,我调用此Dialog,如下所示。

MyDialog mDialog = new MyDialog();
mDialog .show(getFragmentManager(), "Hello");