从网络服务读取数据时,我尝试显示指示器, 在网上搜索并与我的代码匹配后,具有以下代码以返回ListView和显示指示器,但指示器不显示。在主页中,单击“显示新闻”按钮并导航到新表单中的新表单初始形式后应包含以下代码:
private async void GetProduct()
{
var indicator = new ActivityIndicator
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
Color = Color.Black,
IsVisible = true
};
HttpClient httpClient = new HttpClient();
var response = await httpClient.GetStringAsync("http://mySrvice.domain.com/api/news/getlastten");
indicator.IsRunning = true;
indicator.IsVisible = true;
var TProducts = JsonConvert.DeserializeObject<List<News>>(response);
Label header = new Label
{
Text = "Last ten news",
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
HorizontalOptions = LayoutOptions.Center
};
ListView listView = new ListView
{
ItemsSource = TProducts,
ItemTemplate = new DataTemplate(() =>
{
// Create views with bindings for displaying each property.
Label nameLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "Title");
nameLabel.SetBinding(Label.FontFamilyProperty, "BNazanin.ttf#Nazanin");
nameLabel.SetBinding(Label.HorizontalTextAlignmentProperty, "Start");
Image nImage = new Image();
nImage.SetBinding(Image.SourceProperty, "ImageURL");
Label ViewdLabel = new Label();
ViewdLabel.SetBinding(Label.TextProperty, "Viewed");
nameLabel.SetBinding(Label.FontFamilyProperty, "BNazanin.ttf#Nazanin");
// Return an assembled ViewCell.
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(0, 5),
Orientation = StackOrientation.Horizontal,
FlowDirection = FlowDirection.RightToLeft,
Children =
{
nImage,
new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Spacing = 0,
Children =
{
nameLabel,
ViewdLabel
}
}
}
}
};
})
};
listView.ItemSelected += async (sender, e) =>
{
News = (News)e.SelectedItem;
await Navigation.PushAsync(new NewsDetails(News));
};
this.Content = new StackLayout
{
Children =
{
indicator,
header,
listView
}
};
indicator.IsRunning = false;
indicator.IsVisible = false;
}
答案 0 :(得分:0)
正如其他用户在评论中指出的那样,除非您将ActivityIndicator
添加到页面中,否则不会出现。您正在将其添加到GetProduct()
末尾的页面上,并立即使其不可见,因此它从不可见,这是因为尚未添加它,或者是因为它已被添加看不见的。
有几种可能性可以实现您想要的。最简单的方法是将ActivityIndicator
的开头添加GetProducts()
var indicator = new ActivityIndicator
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
Color = Color.Black,
IsVisible = true,
IsRunning = true
};
this.Content = indicator;
HttpClient httpClient = new HttpClient();
var response = await httpClient.GetStringAsync("http://mySrvice.domain.com/api/news/getlastten");
({IsRunning
被立即设置,因为我假设您希望指示器在 期间运行,而您是从服务器而不是之后从服务器获得产品的。)>
您不需要在最终的堆栈布局中使用指示器,因此可以将Content
设置为
this.Content = new StackLayout
{
Children =
{
header,
listView
}
};
附带说明:使用XAML和MVVM对这些事情很有帮助。