星期三, 7月 01, 2020

[X.Form] FlexLayout

根據 Xamarin.Forms FlexLayout 範例內的 PhotoWrap 來練習,該範例內示範的 url 練習時還是可以活著的,省去找圖片困惱

Xaml 配置

FlexLayout 使用屬性簡易說明
  • Direction="Row":由左往右排列
  • Wrap="Wrap":當擺不下時,往下折行
  • JustifyContent="SpaceAround":延排列方式各物件兩側各平均留邊
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="FlexLayoutDemo.PhotoWrapping">
    <ContentPage.Content>
        <Grid>
            <ScrollView Orientation="Vertical">
                <FlexLayout x:Name="flexLayout"
                        Direction="Row"
                        Wrap="Wrap"
                        JustifyContent="SpaceAround" />
            </ScrollView>

            <ActivityIndicator x:Name="activityIndicator"
                           IsRunning="True"
                           VerticalOptions="Center" />
        </Grid>
    </ContentPage.Content>
</ContentPage>
C# Code
namespace FlexLayoutDemo
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class PhotoWrapping : ContentPage
    {
        public PhotoWrapping()
        {
            InitializeComponent();

            ImageFillAsync();
        }

        private async void ImageFillAsync()
        {
            var files = await RecordParseAsync();

            foreach (string filepath in files)
            {
                Image image = new Image
                {
                    Source = ImageSource.FromUri(new Uri(filepath))
                };
                flexLayout.Children.Add(image);
            }

            activityIndicator.IsRunning = false;
            activityIndicator.IsVisible = false;
        }

        private async Task<List<string>> RecordParseAsync()
        {
            string rawJson = await DownloadDataAsync();
            JObject jsonObject = JObject.Parse(rawJson);
            var records = jsonObject["photos"]?.ToString();
            return JsonConvert.DeserializeObject<List<string>>(records);
        }

        private async Task<string> DownloadDataAsync()
        {
            string json = string.Empty;

            string url = "https://raw.githubusercontent.com/xamarin/docs-archive/master/Images/stock/small/stock.json";
            using (HttpClient http = new HttpClient())
            {
                json = await http.GetStringAsync(url);
            }
            return json;
        }
    }
}
拉到最下方觀察到 JustifyContent="SpaceAround" 效果

[X.Form] FlexLayout

沒有留言:

張貼留言