android - 如何将 View (例如标签)的高度/宽度设置为其内容的大小?

标签 android layout xamarin.forms view

我想在 Xamarin.Forms 中将 View 的高度精确设置为其内容的大小。例如,我希望 Label 只与其文本一样高。

Android 中,我可以执行类似 layout_height="wrap_content" 的操作。 Xamarin.Forms 中是否有类似的东西?我可以为此使用 HeightRequest 吗?如果可以,如何使用?

最佳答案

当你提到View时,这是一个非常宽泛的问题,而不是像Label这样的具体问题,所以在不同的View场景:-

您可以使用 View 对象的 Horizo​​ntalOptionsVerticalOptions 属性来帮助解决这个问题,即 LayoutOptions.FillAndExpandLayoutOptions.CenterAndExpand

是的 - 您可以在 View 上指定 HeightRequestWidthRequest 以表明您对区域宽度的偏好和 height 通过 layoutview 保留,尽管这不能保证,取决于使用的其他布局控件/ View 。

如果我们专门针对 Label 控件进行对话,这将不会扩展使用的特定 Label 字体大小的文本大小,以适应父级 查看您指定的。为此,您必须适本地设置 Scale 属性,以将 Label 缩放到使用它的容器。

更新 1:-

使用以下示例代码,高度是否已自动更改以适合显示的标签高度文本?

        StackLayout  cobjStackLayout = new StackLayout()
        {
            Orientation = StackOrientation.Vertical
        };

        Label objLabel1 = new Label();
        objLabel1.BackgroundColor = Color.Red;
        objLabel1.Text = "This is a label";
        cobjStackLayout.Children.Add(objLabel1);

        Label objLabel2 = new Label();
        objLabel2.BackgroundColor = Color.Green;
        objLabel2.Text = "This is another label with different font size";
        objLabel2.Font = Font.OfSize("Arial", 48);
        cobjStackLayout.Children.Add(objLabel2);


        this.Content = cobjStackLayout;

更新 2:- 是的 - 在 ContentPage 的末尾有一个意外的垂直填充,当您只使用 一个 Label 时会发生这种情况。

如果您尝试以下操作,您应该只使用1 个标签,在文本周围体验您所追求的:-

        cobjStackLayout = new StackLayout()
        {
            Orientation = StackOrientation.Horizontal,
            VerticalOptions = LayoutOptions.Start
        };

        Label objLabel1 = new Label();
        objLabel1.BackgroundColor = Color.Red;
        objLabel1.Text = "This is a label";
        cobjStackLayout.Children.Add(objLabel1);

        this.Content = cobjStackLayout;

更新 3:-

这是一个不使用父级来设置 Horizo​​ntalOptions/VerticalOptions 的版本,所以当我说在层次结构的不同部分指定的 LayoutOptions 影响输出时,事情可能会更清楚一些:-

        cobjStackLayout = new StackLayout()
        {
            Orientation = StackOrientation.Horizontal,
        };

        Label objLabel1 = new Label();
        objLabel1.BackgroundColor = Color.Red;
        objLabel1.Text = "This is a label";
        objLabel1.HorizontalOptions = LayoutOptions.Start;
        objLabel1.VerticalOptions = LayoutOptions.Start;
        cobjStackLayout.Children.Add(objLabel1);


        this.Content = cobjStackLayout;

请记住,有时仅在您有兴趣控制的View 上设置Horizo​​ntalOptionsVerticalOptions 以获得您想要的效果是不够的.

关于android - 如何将 View (例如标签)的高度/宽度设置为其内容的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530627/

相关文章:

android - 使用附加参数跟踪每个屏幕查看持续时间

安卓通知图标

c# - 如何使用 OnPlatform Xamarin 更改 BackgroundColor

android - 运行项目时如何通过eclipse安装.apk文件

java - 框架布局未显示在主要 Activity 中

jquery - 当使用 JQuery UI 可调整大小调整其容器大小时,想要自动调整 jQuery UI.Layout 的 div 宽度和高度!

java - 为什么我的标题边框面板这么小

xamarin.forms - 使用 xamarin 跨平台应用程序的支付网关

c# - 为使用 Xamarin.Forms 构建的 Android 应用程序实现自动更新的正确方法

android - onClickListener 问题