I have something like this so far for my view:
public StackLayout OffersSlideViewCarouselChild(Offer offer)
{
Image productImage = new Image
{
Source = ImageSource.FromUri(new Uri(offer.Image.Replace("https://", "http://"))),
HeightRequest = 270,
WidthRequest = 270,
Aspect = Aspect.AspectFit
};
var topStackLayout = new StackLayout
{
Spacing = 0
};
topStackLayout.Children.Add(productImage);
StackLayout contentStackLayout = new StackLayout
{
Spacing = 0,
Padding = new Thickness(5, 10, 5, 10),
Orientation = StackOrientation.Vertical
};
var savedBtn = SavedButtonLayout(offer.IsSelected, offer.Id);
var redeemBtn = RedeemBtnLayout(offer.Id);
var timeRemainingLabel = TimeRemainingLayout(offer, offer.Id);
contentStackLayout.Children.Add(new UILabel(16) {
Text = offer.ProductName,
TextColor = ColorHelper.FromHex(CoreTheme.COLOR_OFFERCELL_PRODUCT_TEXT),
FontFamily = CoreTheme.FONT_FAMILY_DEFAULT_BOLD,
WidthRequest = DeviceDisplaySettings.defaultwidth,
VerticalTextAlignment = TextAlignment.Center
});
contentStackLayout.Children.Add(new UILabel(14)
{
Text = offer.Headline,
TextColor = ColorHelper.FromHex(CoreTheme.COLOR_OFFERCELL_PRODUCT_TEXT),
FontFamily = CoreTheme.FONT_FAMILY_DEFAULT_BOLD,
WidthRequest = DeviceDisplaySettings.defaultwidth,
VerticalTextAlignment = TextAlignment.Center
});
contentStackLayout.Children.Add(new UILabel(14) {
Text = offer.LongRewardsMessage,
TextColor = ColorHelper.FromHex(CoreTheme.COLOR_DEAL_PAGE_LONG_REWARD_MESSAGE_RED),
FontFamily = CoreTheme.FONT_FAMILY_DEFAULT_BOLD,
WidthRequest = DeviceDisplaySettings.defaultwidth,
VerticalTextAlignment = TextAlignment.Center
});
if (!string.IsNullOrEmpty(offer.PowerMessage)) {
var htmlText = string.Format("<html><body style='color:#9b9b9b'>{0}</body></html>", offer.PowerMessage.Replace(#"\", string.Empty));
var browser = new WebView() {
//HeightRequest = (DeviceDisplaySettings.defaultheight > 600) ? 500 : 400,
HeightRequest = 800,
Source = new HtmlWebViewSource() { Html = htmlText },
};
browser.Navigating += OnNavigating;
contentStackLayout.Children.Add(browser);
}
var nestedStackLayout = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand
};
nestedStackLayout.Children.Add(topStackLayout);
nestedStackLayout.Children.Add(timeRemainingLabel);
nestedStackLayout.Children.Add(contentStackLayout);
var mainScrollView = new ScrollView()
{
Padding = new Thickness(0, 0, 0, 10),
VerticalOptions = LayoutOptions.FillAndExpand,
Orientation = ScrollOrientation.Vertical,
Content = nestedStackLayout
};
var mainStackLayout = new StackLayout()
{
Spacing = 5,
Padding = new Thickness(0, 0, 0, 0),
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.Fill,
Orientation = StackOrientation.Vertical,
Children = { savedBtn, mainScrollView, redeemBtn }
};
return mainStackLayout;
}
private StackLayout SavedButtonLayout(bool isSelected, int offerid)
{
int buttonsToShow = 2;
bool displaySaveButton = true;
if (IsPremisesOffer (offerid)) {
buttonsToShow = 3;
displaySaveButton = false;
}
btnShare = new UIFieldDefinition(_pageFieldDefinition.ShareButtonDefinition);
btnShare.Text = "SHARE";
btnShare.ClassId = offerid.ToString();
btnShare.WidthRequest = (DeviceDisplaySettings.defaultwidth / buttonsToShow) - 40;
btnShare.BackgroundColor = Color.FromRgb(167, 188, 33);
btnShare.VerticalContentAlignment = TextAlignment.Center;
btnShare.HandleClick(btnShare_Clicked);
btnSave = new UIFieldDefinition(_pageFieldDefinition.SaveButtonDefinition);
btnSave.Text = isSelected ? "UNSAVE" : "SAVE";
btnSave.ClassId = offerid.ToString();
btnSave.WidthRequest = (DeviceDisplaySettings.defaultwidth / buttonsToShow) - 40;
btnSave.BackgroundColor = Color.FromRgb(167, 188, 33);
btnSave.VerticalContentAlignment = TextAlignment.Center;
btnSave.HandleClick(btnSave_Clicked);
rl = new StackLayout {
Spacing = 10,
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.FromRgb(196, 221, 57),
Padding = new Thickness(40, 5, 5, 5),
WidthRequest = DeviceDisplaySettings.defaultwidth
};
rl.Children.Add(btnShare);
if (displaySaveButton) rl.Children.Add(btnSave);
return rl;
}
public UIFieldDefinition RedeemBtnLayout(int offerid)
{
int buttonsToShow = 1;
btnRedeem = new UIFieldDefinition(_pageFieldDefinition.RedeemButtonDefinition);
btnRedeem.Text = "REDEEM NOW";
btnRedeem.ClassId = offerid.ToString();
btnRedeem.WidthRequest = (DeviceDisplaySettings.defaultwidth / buttonsToShow) - 10;
// btnRedeem.HorizontalOptions = LayoutOptions.FillAndExpand;
// btnRedeem.VerticalOptions = LayoutOptions.EndAndExpand;
btnRedeem.HandleClick(btnRedeem_Clicked);
return btnRedeem;
}
However, I am noticing that the Redeem button does not even display on the view (It's supposed to be fixed on the bottom).
The scrollview works but the buttom is missing. Why?
Please let me know if you need further code details.
Moving here from comments above. There are two separate issues from what I can tell, and as far as I can tell, are unrelated:
The WebView, nested inside the ScrollView, is not big enough to fully display the content.
The button that is supposed to be at the bottom of the screen is not displaying.
For both of them, the answer is probably in how you are setting HeightRequest. There have been a lot of suggestions by myself and other commenters to change or get rid of some of the HeightRequest settings, and I'm not sure of the current state of your source code. So assuming those are still there:
For solving the WebView issue, read How can I add HTML to a Stacklayout inside a Scrollview in Xamarin forms?. This will let you figure out the right HeightRequest to use. The short answer is that depending on exactly what you want to happen, you may need a custom renderer. Note that the HeightRequest for the WebView will not affect any layout outside of the ScrollView.
For solving the issue of the button not appearing, get rid of the HeightRequest setting on the ScrollView, and the VerticalOptions on the StackLayout created in SavedButtonLayout.
I am assuming you did the experiment suggested above to make sure that the redeemBtn will render if placed before the ScrollView, and it does show up then. If not, you first need to fix that.
If you have "fixed" this by changing the HeightRequest then your real problem is the fixed pixel size of all your views and layouts, I recommend you DON'T use fixed pixel sizes for different screen resolution this will be a bigger problem later, What you can do is get the Screen size and do the math to fit all your elements of the view, one way to get the width and height of the screen is on the OnSizeChanged event of Pages (Like ContentPage), something like this:
SizeChanged += SizeChanged;
void SizeChanged (object sender, EventArgs e)
{
Layout.WidthRequest = Width * 0.3;
Layout.HeightRequest = Height * 0.35;
}
Your layout is pretty busy. A few things:
Set VerticalOptions to EndAndExpand for redeemBtn.
Set VerticalOptions to StartAndExpand for savedBtn.
Set VerticalOptions to Fill for mainScrollView.
Set VerticalOptions to FillAndExpand for mainRelLayout.
Set VerticalOptions and HorizontalOptions to Fill for
mainStackLayout.
I think that will get you to where you want to be.
The options that include "Expand" will grow the element to accommodate the desired height of its contents.
Related
I have made side menu using Rg.Plugins.Popups for Xamarin.
Everything is ok, but appearing animation doesn't work for some reason. As you can see menu just appears out of nowhere when it should look like disappearing animation.
FilterMenuCommand = new Command(() =>
{
var contentView = new ReportsPageFilterMenuContentView(this);
PopupNavigation.Instance.PushAsync(new ReportsPageFilterMenuPopupPage(contentView, this));
});
My PopupPage class:
public partial class ReportsPageFilterMenuPopupPage : PopupPage
{
public ReportsPageFilterMenuPopupPage(ReportsPageFilterMenuContentView contentView, ReportsViewModel viewModel)
{
InitializePageComponent(contentView, viewModel);
}
protected void InitializePageComponent(ReportsPageFilterMenuContentView contentView, ReportsViewModel viewModel, float width = 340.0f)
{
BindingContext = viewModel;
var moveAnimation = new MoveAnimation
{
DurationIn = 800,
DurationOut = 600,
EasingIn = Easing.SinIn,
EasingOut = Easing.SinOut,
HasBackgroundAnimation = true,
PositionIn = MoveAnimationOptions.Right,
PositionOut = MoveAnimationOptions.Right,
};
Animation = moveAnimation;
Resources["DecimalConverter"] = new DecimalConverter();
var frame = new Frame
{
WidthRequest = width,
CornerRadius = 0,
Padding = new Thickness(24, 20, 24, 20),
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.StartAndExpand,
BackgroundColor = Color.White
};
var gridRowDefinitions = new RowDefinitionCollection
{
new RowDefinition {Height = GridLength.Auto}, new RowDefinition {Height = GridLength.Star}
};
var grid = new Grid
{
RowDefinitions = gridRowDefinitions
};
var stackLayout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
Grid.SetRow(stackLayout, 0);
Grid.SetRow(contentView, 1);
var label = new Label
{
FontFamily = "Roboto",
FontAttributes = FontAttributes.Bold,
FontSize = 20,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Start,
Margin = new Thickness(1),
Text = MainResource.Filters
};
var imageButton = new ImageButton
{
Source = (FileImageSource)#"Assets/cross.png",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.EndAndExpand,
Margin = new Thickness(1),
Command = viewModel.CloseCommand
};
stackLayout.Children.Add(label);
stackLayout.Children.Add(imageButton);
grid.Children.Add(stackLayout);
grid.Children.Add(contentView);
frame.Content = grid;
Content = frame;
}
}
Xamarin.Forms version: 4.6.0.800
Rg.Plugins.Popup version: 2.0.0.3
If you have any clue or idea where to even start fixing this problem, please, share it with me in comments.
I use your code and test on the following simulators
Android phone
Android tablet
iOS iPhone
iOS iPad
It works fine , the appearing and disappearing animation works as expected .
I would suggest you update Xamarin.Forms and Rg.Plugins.Popup version package to the latest .
Here is my code:
List<Entry> entries = new List<Entry>
{
new Entry(7)
{
Color = SKColor.Parse("#166DA3"),
},
new Entry(3)
{
Color = SKColors.Transparent,
}
};
public RoundScore2()
{
Content = _contentLayout; // layout inherited from a different class
Label congrats = new Label
{
Text = "Congratulations!",
FontAttributes = FontAttributes.Bold,
FontSize = 30,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Start,
TextColor = Color.Black
};
_contentStack.Children.Add(congrats); // _contentStack inherited from same class, _contentStack is added to _contentLayout
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = 80
};
_contentStack.Children.Add(Chart1);
Chart1.Chart = new DonutChart() { Entries = entries, HoleRadius = 5 };
Button nextRound = new Button
{
Text = "Start Round " + roundCounter.ToString(),
Margin = new Thickness(10, 20, 10, 10),
TextColor = Color.Black,
BackgroundColor = Color.FromHex("48AADF"),
FontFamily = "Source Sans Pro",
FontSize = 20,
FontAttributes = FontAttributes.Bold,
CornerRadius = 8,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.StartAndExpand,
WidthRequest = 180
};
_contentStack.Children.Add(nextRound);
}
Stack overflow is not letting me add the photo right now ("Failed to upload image; couldn't reach imgur")...but basically, I can only see the horizontal middle section of the pie chart. There is enough space for the chart to show, but it is just cut off. I have tried setting VerticalOptions = LayoutOptions.FillAndExpand along with LayoutOptions.CenterAndExpand and no luck. Does anyone know why this is happening?
Edit: even with the Label and Button taken out, the view is still cut off.
but basically, I can only see the horizontal middle section of the pie chart.
From shared code of ChartView, I'm guessing that whether the width of chart view is too small.
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = 80
};
If so , you can add HorizontalOptions as follow:
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 80
};
In addition , also can add HorizontalOptions for StackLayout:
_contentStack.HorizontalOptions = LayoutOptions.FillAndExpand;
_contentStack.VerticalOptions = LayoutOptions.FillAndExpand;
It worked after changing VerticalOptions = LayoutOptions.Center and HorizontalOptions = LayoutOptions.Fill as well as changing HoleRadius = .5f.
I am working on a simple app that keeps track of life for a card game. I am very new to xamarin so I am starting small and just slowly adding more functionality. Currently, I have two pages; One page (the page it starts on (root page?) that has only one lifetotal number, two buttons for incrementing and decrementing, and one button to switch to a two player layout, and then a second page with two lifetotals and 4 buttons (an increment and decrement for each lifetotal). I am writing all of this in C# and I would like to keep it that way, however, I am having trouble finding a way to make it so that button that switches to the two player layout will present the second page. Everything ive googled seems to point back to xml which I want to avoid. Can anyone help me understand how to do this?
I am building off an app my buddy made for to understand how xamarin works so thats what all the weird comments are
code: (the delegate i need to fill in is at the bottom, called moreplayers)
namespace SampleApp
{
//contentpage is the base class for all pages.
//You should make a base class for this page that isn't contentpage, but inherits from content page, then you can add custom methods that extend across all pages.
//Like adding a progress spinner, or disabling all UI elements.
public class MainPage : ContentPage
{
public MainPage()
{
CreateUI();
}
private void CreateUI()
{
Stats Player1 = new Stats();
Player1.LifeTotal = 20;
//abstracting out a function to build UI is good, but breaking this down further is better.
var MainGrid = new Grid()//grids are the bread and butter of xamarin forms, the documentation has lots of good examples I won't try to replicate here.
{
HorizontalOptions = LayoutOptions.FillAndExpand,//these are on all UI elements, gotta specify them or the default values will probably screw up.
VerticalOptions = LayoutOptions.FillAndExpand
};
//I usually make a bunch of nice extensions on the Grid to add rows and columns easily
MainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
MainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
MainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
//grid where life total label will live
var GridForLifeTotal = new Grid()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
GridForLifeTotal.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
GridForLifeTotal.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
GridForLifeTotal.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
//grid where buttons will live
var GridForButtons = new Grid()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
GridForButtons.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
GridForButtons.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
GridForButtons.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
MainGrid.Children.Add(GridForLifeTotal, 0, 0); //add items to the grid based on position
MainGrid.Children.Add(GridForButtons, 0, 1);
//Add labels
var lifeLabel = new Label()
{
Text = Player1.LifeTotal.ToString(),
FontAttributes = FontAttributes.Bold,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
FontSize = 60
};
GridForLifeTotal.Children.Add(lifeLabel, 0, 0);
//Add buttons
var UpButton = new Button()
{
Text = "+",
FontAttributes = FontAttributes.Bold,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
FontSize = 30
};
UpButton.Clicked += delegate {
//delegates are bad form but it's late and I'm tired you should put this login in a view model class and have that view model be a private property on this view.
//View (this), View Model (the logic layer) then a Model to hold the life total and any other user data?
Player1.LifeTotal += 1;
lifeLabel.Text = Player1.LifeTotal.ToString();
};
var DownButton = new Button()
{
Text = "-",
FontAttributes = FontAttributes.Bold,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
FontSize = 30
};
DownButton.Clicked += delegate {
//delegates are bad form but it's late and I'm tired
Player1.LifeTotal -= 1;
lifeLabel.Text = Player1.LifeTotal.ToString();
};
var MorePlayers = new Button()
{
Text = "2 Player Game",
FontAttributes = FontAttributes.Bold,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.End,
FontSize = 30
};
MorePlayers.Clicked += delegate
{
//need to figure out what goes here
};
GridForButtons.Children.Add(UpButton, 0, 0);
GridForButtons.Children.Add(DownButton, 1, 0);
GridForButtons.Children.Add(MorePlayers, 0, 1);
Content = MainGrid;//very important, otherwise you don't actually see anything you've built
}
}
}
first, you need to wrap MainPage in a NavigationPage when you first assign it in your App.xaml.cs
MainPage = new NavigationPage(new MainPage());
then, to navigate to the next page in your delegate
this.Navigation.PushAsync(new Page2());
I am trying to make a gallery style grid view in Xamarin forms for iOS and Android but have an issue where layout options seem to be ignored and I get different results for iOS and Android.
Basic layout is:
frame with a border(red) containing a stack layout (pink) set to FillAndExpand for both horizontal and vertical options which contains a label at the top and an image below set to fill the rest of the stack.
The image seems to just expand outside of the stack and the frame and ignore the vertical options set.
I have tried setting these vertical options to Fill, FillAndExpand, CentreAndExpand but all have the same result.
If i remove the Stack layout and label and have the image as the only child element in the frame then it works as expected but I am required to also show a label.
The result is the same in landscape and portrait orientations.
Results on platform with iOS being the main issue here:
Code for adding an image to the grid:
var imageSource = ImageSource.FromStream(() => new MemoryStream(imageData));
var framedImage = new Frame
{
Padding = 0,
Margin = 3,
GestureRecognizers = { tapGesture },
Content = new StackLayout
{
Padding = 10,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.Pink,
Children =
{
textLabel,
new Image
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Source = imageSource,
Aspect = Aspect.AspectFit
},
}
},
BackgroundColor = StyleSheet.BackgroundColorLight,
BorderColor = StyleSheet.OutlineColorDark,
CornerRadius = 5,
HasShadow = false
};
grid.Children.Add(framedImage, columnCounter, rowCounter);
Thanks in advance!
Fixed it by doing this:
var image = new Image
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Source = imageSource,
Aspect = Aspect.AspectFit
};
var framedImage = new Frame
{
Padding = 2,
Margin = 1,
GestureRecognizers = { tapGesture },
Content = image,
HasShadow = false,
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand
};
var innergrid = new Grid
{
RowDefinitions =
{
new RowDefinition {Height = new GridLength(20, GridUnitType.Auto)},
new RowDefinition {Height = new GridLength(20, GridUnitType.Star)},
}
};
innergrid.Children.Add(textLabel, 0, 0);
innergrid.Children.Add(framedImage, 0, 1);
var frame = new Frame
{
Padding = 5,
Margin = 3,
GestureRecognizers = { tapGesture },
Content = innergrid,
BackgroundColor = StyleSheet.BackgroundColorLight,
BorderColor = StyleSheet.OutlineColorDark,
CornerRadius = 5,
HasShadow = true
};
grid.Children.Add(frame, columnCounter, rowCounter);
I might have a go with the new FlexLayout to see if i can have simpler code
I'm trying to detect a collision between two Xamarin. Forms Controls (BoxViews), but I can't find a way to do it. I have a button that what it does is to decrease the TranslationY of a BoxView until it collides with the other BoxView. I remember that with WinForms this could be done with IntersectsWith, but apparently here does not work, I currently have this:
public class Main : ContentPage
{
public BoxView pjOne = new BoxView { BackgroundColor = Color.Red, HeightRequest = 100, WidthRequest = 100, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.StartAndExpand };
public BoxView pjTwo = new BoxView { BackgroundColor = Color.Green, HeightRequest = 100, WidthRequest = 100, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand };
public Button btnDown = new Button { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.End, Text = "Down", TextColor = Color.White };
public Main()
{
btnDown.Clicked += (s, e) =>
{
if(!pjOne.Bounds.IntersectsWith(pjTwo.Bounds))
{
pjOne.TranslationY -= 100; //If it does not detect collision it decreases the TranslationY
}
else
{
pjOne.TranslationY += 100; //If it detects collision it increases the TranslationY
}
};
Content = new StackLayout
{
Children =
{
pjOne,
pjTwo,
btnDown
}
};
}
}
But this doesn't work, it never detects the collision between the two BoxView.
Bounds do not get updated when a Translation is applied.
From the docs:
Bounds is assigned during the Layout cycle by a call to Layout(Rectangle).
I would try
calling Layout with the new location you want to translate the BoxView to
create a rectangle for pjOne and pjTwo. Then you could use the Xamarin.Forms.Rectangle.IntercectsWith method.
Here is an untested example of how to do this:
var pjRectOne = new Rectangle(pjOne.X + pjOne.TranslationX, pjOne.Y + pjOne.TranslationY, pjOne.Width, pjOne.Height);
var pjRectTwo = new Rectangle(pjTwo.X + pjTwo.TranslationX, pjTwo.Y + pjTwo.TranslationY, pjTwo.Width, pjTwo.Height);
if (pjRectOne.IntercectsWith(pjRectTwo))
{
}
Note: if pjOne or pjTwo are children of a view, their X and Y positions will be relative to the parent. To get the absolute X and Y, loop through all their parents by doing something like this
var y = pjOne.Y;
var parent = pjOne.ParentView;
while (parent != null)
{
y += parent.Y;
parent = parent.ParentView;
}
Hope this helped you out :)