对话框片段的宽度和高度被忽略

时间:2019-07-10 21:38:58

标签: c# android xamarin visual-studio-2017

如何设置对话框片段的宽度和高度?我读过的所有内容都说要像这样重写OnStart方法:

    public override void OnStart()
    {
        if (Dialog == null)
        {
            return;
        }
        int dialogWidth = 300;
        int dialogHeight = 75;
        Dialog.Window.SetLayout(dialogWidth, dialogHeight);
    }

执行此操作时,应用程序崩溃,由于无法在我编写的代码之外失败,因此我无法捕获该错误。没有此替代,对话框将出现并按预期运行。

这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    android:minWidth="300dp" 
    android:minHeight="75dp">
    <TextView
        android:text="Select section."
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center" 
        android:textStyle="bold"
        android:id="@+id/textView2" />
    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:id="@+id/my_spinner" />
    <Button
        android:text="Ok"
        android:layout_width="200px"
        android:layout_gravity="center"
        android:layout_height="34.5dp"
        android:id="@+id/button_ok" />
</LinearLayout>

显然,android:minWidthandroid:minHeight设置被忽略了,因为我得到的只是一个很小的对话框。

2 个答案:

答案 0 :(得分:1)

与Mehmed代码等效的c#:

    public override void OnResume()
    {
        int width = 300; 
        int height = 75; 
        base.OnResume();
    }

我发现Xamarin所关注的Stack Overflow上发布的许多代码都是Java代码,我使用c#(Visual Studio 2017),对Java完全一无所知,很难转换为c#。当我在答案中看到Java代码时,通常只是跳过它。但是看到我提出问题的方式和Mehmed足够好以提供可行的解决方案后,我感到不得不发布c#转换。

您会注意到,我选择不将值放在dimens.xml中,我不喜欢将值存储在“代码文件外部”中,然后在代码中检索它们,这往往使有时调试起来要困难得多。当您执行此操作时,所有发生的事情就是编译器将代码行替换为生成的obj文件中的值,所以..为什么呢?

鉴于这些价值观永远不会改变,我认为将它们放入dimens.xml毫无意义,否则一定会让我信服!

答案 1 :(得分:0)

最好在dimens.xml文件夹下的values中定义尺寸:

<resources>
    ...
    <dimen name="dialog_min_width">300dp</dimen>
    <dimen name="dialog_min_height">75dp</dimen>
    ...
</resources>

您可以按以下方式更新onResume()的{​​{1}}方法并尝试:

DialogFragment
相关问题