Display lyrics while playing song in xamarin forms - xamarin.forms

I made audio player in xamarin forms(PCL) as Follows:
Audio.xaml(PCL):
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CPL.pages.audio">
<ContentPage.Content>
<StackLayout>
<ListView x:Name="lstSongsList" ItemSelected="lstSongsList_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label x:Name="lblFileName" Text="{Binding Name}"></Label>
<Label x:Name="lblLength" Text="{Binding Length}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Audio.xaml.cs(PCL):
private void lstSongsList_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var selected = (Entity.File)e.SelectedItem;
try
{
if(selected != null)
{
Navigation.PushAsync(new player(selected));
}
}
catch(Exception ex)
{
}
}
Player.xaml.cs(PCL):
public player(Entity.File entity)
{
InitializeComponent();
_file = entity;
DependencyService.Get<iFile>().PlayFile(entity.FullPath);
}
Files.cs(Android):
public bool PlayFile(string filePath)
{
if(currentFile != filePath)
{
if (_mediaPlayer != null)
{
_mediaPlayer.Stop();
}
_mediaPlayer = MediaPlayer.Create(global::Android.App.Application.Context, Android.Net.Uri.Parse(filePath));
_mediaPlayer.Start();
var file = rootDirectory.GetFiles(".lrc", SearchOption.AllDirectories).FirstOrDefault();
_mediaPlayer.AddTimedTextSource(file.FullName, "application/octet-stream");
_mediaPlayer.SetVolume(100, 100);
currentFile = filePath;
}
return true;
}
It works fine in play and pause but I am unable to display lyrics which is attached in addtimedTextSource file. I have to display lyrics while play the song.
Anyone have idea about displaying lyrics of audio in xamarin forms?

Related

how to change player icon in xamarin forms

Please i need some one to help me on how to change player icon into my player page in xamarin forms
This is my code:
PlayerPage.xaml
<StackLayout>
<Button x:Name="btnpause"
WidthRequest="20"
HeightRequest="20"
HorizontalOptions="Center"
ImageSource="pause.png" />
<Button x:Name="btnPlay"
WidthRequest="20"
HeightRequest="20"
HorizontalOptions="Center"
ImageSource="play.png" />
<Switch x:Name="switchLoop" IsToggled="False" />
</StackLayout>
PlayerPage.xaml.cs
ISimpleAudioPlayer player;
public PlayerPage()
{
InitializeComponent();
var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.Load("music.mp3");
btnPlay.Clicked += BtnPlayClicked;
switchLoop.Toggled += SwitchLoopToggled;
}
private void SwitchLoopToggled(object sender, ToggledEventArgs e)
{
Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Loop = switchLoop.IsToggled;
}
private void BtnPlayClicked(object sender, EventArgs e)
{
Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Play();
}
Thank you.
Take a look at PlaybackEnded , it is raised when audio playback completes successfully .
You can control the button's visibility in the event .
Code example
var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.PlaybackEnded += (sender,e)=>
{
btnPlay.IsVisible = true;
btnpause.IsVisible = false;
};
I think you mean like this ,did not added the image .Use a ImageButton instead.
On start the button play and the loop switch , when the switch is True the sounds repeats it self. When start the pause button is showing push it the Play is showing again to resume. The example project is on Github https://github.com/borisoprit/MusicStackOverflow
<StackLayout>
<ImageButton
x:Name="btnPlay"
HeightRequest="50"
HorizontalOptions="Center"
Source="Play.png"
VerticalOptions="Center"
WidthRequest="50" />
<ImageButton
x:Name="btnPause"
HeightRequest="50"
HorizontalOptions="Center"
Source="pause.png"
VerticalOptions="Center"
WidthRequest="50"
IsVisible="false"/>
<Label
HorizontalOptions="Start"
Text="Loop:"
VerticalOptions="Center" />
<Switch
x:Name="switchLoop"
HorizontalOptions="Start"
IsToggled="False"
VerticalOptions="Center" />
</StackLayout>
PlayerPage.xaml.cs i also place the OnAppearing. This is the state of the btnpause Isvisible = false .Music ended the Play button is there and pause is hiding again.
public HeadProjectAudioPage()
{
InitializeComponent();
btnPause.IsVisible = false;
var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.PlaybackEnded += (sender, e) =>
{
btnPlay.IsVisible = true;
btnPause.IsVisible = false;
};
player.Load("running.mp3");
btnPlay.Clicked += BtnPlayClicked;
btnPause.Clicked += BtnPauseClicked;
switchLoop.Toggled += SwitchLoopToggled;
}
protected override void OnAppearing()
{
base.OnAppearing();
btnPause.IsVisible = false;
}
private void SwitchLoopToggled(object sender, ToggledEventArgs e)
{
Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Loop = switchLoop.IsToggled;
}
private void BtnPlayClicked(object sender, EventArgs e)
{
btnPause.IsVisible = true;
btnPlay.IsVisible = false;
Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Play();
}
private void BtnPauseClicked(object sender, EventArgs e)
{
btnPlay.IsVisible = true;
btnPause.IsVisible = false;
Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Pause();
}
}

Last ListView Items not showing when implementing bottom sheet in Xamarin Forms

I tried to implement bottom sheet for my Xamarin forms app. I have Implemented using couple of methods including nugets. In my main behind view I have a ListView. In the bottom sheet normal Frames and Labels. My problem is last one or two items not displaying or partially displaying in the ListView in almost all option.
<?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:yummy="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView"
x:Class="RSMapp.Views.RSMview">
<ContentPage.ToolbarItems>
<ToolbarItem Name="MenuItem" Command="{Binding filterCommand}" Order="Primary" Icon="filter.png" Text="" Priority="0" IsEnabled="{Binding IsEnabled}" />
</ContentPage.ToolbarItems>
<ContentPage.Content>
<RelativeLayout>
<StackLayout BackgroundColor="#d4d4d4" x:Name="mainView" Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<yummy:PancakeView HeightRequest="55" BackgroundColor="{Binding mainBgColor}" Padding="10" HorizontalOptions="FillAndExpand" x:Name="dropdownLayout" CornerRadius="0,0,15,15" VerticalOptions="CenterAndExpand" Grid.Row="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="AUTO"/>
</Grid.ColumnDefinitions>
<Frame IsVisible="{Binding isMonthVisible}" HasShadow="{OnPlatform Android=true, iOS=false}" HorizontalOptions="FillAndExpand" BackgroundColor="WhiteSmoke" Padding="10,0,10,0" CornerRadius="15" Grid.Column="0">
<Picker
Title="{Binding SelectedItem.mName}"
IsVisible="{Binding isMonthVisible}"
TitleColor="Black"
VerticalTextAlignment="Center"
Margin="0,0,20,0"
Focused="Picker_Focused"
TextColor="#565656"
ItemsSource="{Binding MyList}"
SelectedItem="{Binding SelectedItem}"
ItemDisplayBinding="{Binding mName}" />
</Frame>
<StackLayout WidthRequest="60" IsVisible="{Binding extraBtnVisible}" VerticalOptions="Center" HorizontalOptions="Center" Grid.Column="1">
<ImageButton HeightRequest="50" WidthRequest="30" Command="{Binding regionClassCommand}" VerticalOptions="Center" IsVisible="{Binding extraBtnVisible}" BackgroundColor="#F44336" Source="extra.png"/>
</StackLayout>
</Grid>
</yummy:PancakeView>
<StackLayout BackgroundColor="#d4d4d4" Grid.Row="1" Orientation="Vertical">
<ListView IsVisible="{Binding hasLifeData}" ItemTapped="RSMListView_ItemTapped"
SeparatorVisibility="None"
IsPullToRefreshEnabled="False"
ItemsSource="{Binding rsmLifeRankingList}"
x:Name="RSMListView"
Margin="0,0,0,2"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame Margin="2,4,2,4" BackgroundColor="White" IsVisible="True" HasShadow="{OnPlatform Android='true',iOS='false'}" CornerRadius="10" Padding="2,4,2,4">
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="White" Orientation="Vertical">
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout IsVisible="{Binding noData}" HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand">
<Image Source="nodata" HorizontalOptions="Center"/>
</StackLayout>
</StackLayout>
</Grid>
</StackLayout>
<yummy:PancakeView CornerRadius="10,10,0,0" Padding="0" BackgroundColor="#faf9f8"
x:Name="bottomSheet" RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,
Property=Height,Factor=.96,Constant=0}" RelativeLayout.WidthConstraint="{ConstraintExpression
Type=RelativeToParent,Property=Width,Factor=1,Constant=0}" RelativeLayout.HeightConstraint="{ConstraintExpression
Type=RelativeToParent,Property=Height,Factor=1,Constant=0}">
<yummy:PancakeView.GestureRecognizers>
<PanGestureRecognizer PanUpdated="OnPanUpdated" />
</yummy:PancakeView.GestureRecognizers>
<StackLayout BackgroundColor="Gray" Spacing="0">
<BoxView HeightRequest="5" CornerRadius="2" Margin="0,6,0,8" WidthRequest="80" BackgroundColor="LightGray" HorizontalOptions="Center"/>
<StackLayout Orientation="Vertical">
<StackLayout IsVisible="{Binding hasLifeData}" BackgroundColor="WhiteSmoke" Orientation="Vertical" Grid.Row="1">
<StackLayout IsVisible="{Binding layoutVisible}" Spacing="0" Orientation="Vertical">
<yummy:PancakeView Padding="10,0,10,10" CornerRadius="0,0,15,15" BackgroundColor="{StaticResource colorLife}">
<StackLayout Orientation="Vertical">
</StackLayout>
</yummy:PancakeView>
<ScrollView Padding="0,5,0,5">
<StackLayout Margin="2,0,2,0" Orientation="Vertical">
</StackLayout>
</ScrollView>
</StackLayout>
</StackLayout>
</StackLayout>
</StackLayout>
</yummy:PancakeView>
</RelativeLayout>
</ContentPage.Content>
</ContentPage>
Code behind
public partial class RSMview : ContentPage
{
private RSMViewModel vm;
private string company;
private string lifColor = "#f2b22c";
private double x, y;
public RSMview()
{
InitializeComponent();
}
public RSMview(string company, string userRegion)
{
InitializeComponent();
this.company = company;
BindingContext = new RSMViewModel();
vm = BindingContext as RSMViewModel;
Title = userRegion + " (RSM)";
ToolbarStatusBarTheme.ToolbarWithStatusBar(company);
if (NetworkCheck.IsInternet())
{
if (company.Equals("G"))
{
dropdownLayout.BackgroundColor = Color.FromHex(genColor);
vm.GetGenRSMData(userRegion, "G");
}
else if (company.Equals("L"))
{
dropdownLayout.BackgroundColor = Color.FromHex(lifColor);
vm.GetLifeRSMData(userRegion, "L");
}
}
}
private async void RSMListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var item = (LifeRSMData)e.Item;
await Navigation.PushAsync(new SMviewHead(company, item));
}
protected override void OnAppearing()
{
base.OnAppearing();
if (Device.Idiom == TargetIdiom.Phone)
{
CrossDeviceOrientation.Current.LockOrientation(Plugin.DeviceOrientation.Abstractions.DeviceOrientations.Portrait);
}
}
void OnPanUpdated(object sender, PanUpdatedEventArgs e)
{
// Handle the pan
switch (e.StatusType)
{
case GestureStatus.Running:
// Translate and ensure we don't y + e.TotalY pan beyond the wrapped user interface element bounds.
var translateY = Math.Max(Math.Min(0, y + e.TotalY), -Math.Abs((Height * .25) - Height));
bottomSheet.TranslateTo(bottomSheet.X, translateY, 20);
break;
case GestureStatus.Completed:
// Store the translation applied during the pan
y = bottomSheet.TranslationY;
//at the end of the event - snap to the closest location
var finalTranslation = Math.Max(Math.Min(0, -1000), -Math.Abs(GetClosestLockState(e.TotalY + y)));
//depending on Swipe Up or Down - change the snapping animation
if (isSwipeUp(e))
{
bottomSheet.TranslateTo(bottomSheet.X, finalTranslation, 250, Easing.SpringIn);
}
else
{
bottomSheet.TranslateTo(bottomSheet.X, finalTranslation, 250, Easing.SpringOut);
}
//dismiss the keyboard after a transition
//SearchBox.Unfocus();
y = bottomSheet.TranslationY;
break;
}
}
public bool isSwipeUp(PanUpdatedEventArgs e)
{
if (e.TotalY < 0)
{
return true;
}
return false;
}
//TO-DO: Make this cleaner
private double GetClosestLockState(double TranslationY)
{
//Play with these values to adjust the locking motions - this will change depending on the amount of content ona apge
var lockStates = new double[] { 0, .5, .88 };
//get the current proportion of the sheet in relation to the screen
var distance = Math.Abs(TranslationY);
var currentProportion = distance / Height;
//calculate which lockstate it's the closest to
var smallestDistance = 10000.0;
var closestIndex = 0;
for (var i = 0; i < lockStates.Length; i++)
{
var state = lockStates[i];
var absoluteDistance = Math.Abs(state - currentProportion);
if (absoluteDistance < smallestDistance)
{
smallestDistance = absoluteDistance;
closestIndex = i;
}
}
var selectedLockState = lockStates[closestIndex];
var TranslateToLockState = GetProportionCoordinate(selectedLockState);
return TranslateToLockState;
}
private double GetProportionCoordinate(double proportion)
{
return proportion * Height;
}
private void DismissBottomSheet()
{
//SearchBox.Unfocus();
var finalTranslation = Math.Max(Math.Min(0, -1000), -Math.Abs(GetProportionCoordinate(0)));
bottomSheet.TranslateTo(bottomSheet.X, finalTranslation, 450, Easing.SpringOut);
//SearchBox.Text = string.Empty;
}
private void Picker_Focused(object sender, FocusEventArgs e)
{
DismissBottomSheet();
}
private void OpenBottomSheet()
{
var finalTranslation = Math.Max(Math.Min(0, -1000), -Math.Abs(GetProportionCoordinate(.85)));
bottomSheet.TranslateTo(bottomSheet.X, finalTranslation, 150, Easing.SpringIn);
}
}
ViewModel
public class RSMViewModel : BaseViewModelHelper
{
public RSMViewModel()
{
btnImage = "upbtn.png";
extraBtnVisible = false;
isKpiEnable = false;
}
private void CreateToplayout(string company, string sList)
{
if (company.Equals("L"))
{
if (sList != null)
{
var itemList = JsonConvert.DeserializeObject<List<SummaryLifeRegionalData>>(sList);
//var itemList = mList.rsmLifeData;
if (itemList.Count > 0)
{
foreach (var item in itemList)
{
FYR_NOP_TO_BE_PAID = item.FYR_NOP_TO_BE_PAID.ToString();
....
}
}
else
{
}
}
else
{
}
}
else if (company.Equals("G"))
{
if (sList != null)
{
var mList = JsonConvert.DeserializeObject<SummaryRegionalHeaderData>(sList);
var itemList = mList.rsmMotorData;
if (itemList.Count > 0)
{
foreach (var item in itemList)
{
RENEWAL_VEHICLE_COUNT = item.RENEWAL_VEHICLE_COUNT.ToString();
....
}
}
else
{
}
}
else
{
}
}
}
public void GetLifeRSMData(string p_region, string cType)
{
extraBtnVisible = false;
this.p_region = p_region;
this.companyType = cType;
IsEnabled = false;
SelectedItem = getCurrentMonth(cType);
}
public MonthData SelectedItem
{
get => _selectedItem;
set
{
_selectedItem = value;
Task.Run(async () =>
{
AcrDialogClass.ShowLoadingDialog("Loading...");
if (firstRun)
{
string selectedSelectedItem = _selectedItem.ToString();
string getSubStringMonth = selectedSelectedItem.Substring(1, 2);
string getSubStringYear = selectedSelectedItem.Substring(9, 4);
await ChangeListAsync(getSubStringYear, getSubStringMonth, p_region, companyType);
string sList = null;
if (companyType.Equals("L"))
{
mainBgColor = "#f2b22c";
sList = await _apiServices.GetLifeSummaryDataRM(getSubStringYear, getSubStringMonth, p_region);
}
else if (companyType.Equals("G"))
{
mainBgColor = "#F44336";
sList = await _apiServices.getRSMsummaryData(getSubStringYear, getSubStringMonth, p_region, null);
}
CreateToplayout(companyType, sList);
}
else
{
firstRun = true;
}
AcrDialogClass.HideLoadingDialog();
});
OnPropertyChanged();
}
}
private async Task ChangeListAsync(string getSubStringYear, string getSubStringMonth, string p_region, string companyType)
{
if (companyType.Equals("L"))
{
kpiImage = "kpi_chart.png";
isKpiEnable = false;
IsEnabled = false;
//lifeValue = await _apiServices.getLifeRSMDataList(getSubStringYear, getSubStringMonth, p_region, authenticateData1);
lifeValue = await _apiServices.GetLifeRSMDataList(getSubStringYear, getSubStringMonth, p_region);
if (lifeValue != null)
{
hasLifeData = true;
hasGenData = false;
noData = false;
IsEnabled = true;
layoutVisible = true;
layoutVisibleGen = false;
foreach (LifeRSMData ss in lifeValue)
{
ss.TOTAL_PREM_TO_BE_PAID_STRING = ss.TOTAL_PREM_TO_BE_PAID.ToString("N", CultureInfo.InvariantCulture);
ss.LIFE_TARGET_S = ss.LIFE_TARGET.ToString("N", CultureInfo.InvariantCulture);
ss.LIFE_ACHIVEMENT_S = ss.LIFE_ACHIVEMENT.ToString("N", CultureInfo.InvariantCulture);
Device.BeginInvokeOnMainThread(() =>
{
createChart(ss);
});
}
rsmLifeRankingList = lifeValue;
}
else
{
hasLifeData = false;
hasGenData = false;
noData = true;
IsEnabled = false;
layoutVisible = false;
layoutVisibleGen = false;
rsmLifeRankingList.Clear();
}
}
else if (companyType.Equals("G"))
{
kpiImage = "kpi_chart.png";
isKpiEnable = false;
IsEnabled = false;
genValue = await _apiServices.getGenRSMDataList(getSubStringYear, getSubStringMonth, p_region, null);
if (genValue != null)
{
hasGenData = true;
hasLifeData = false;
noData = false;
IsEnabled = true;
layoutVisible = false;
layoutVisibleGen = true;
foreach (GenRSMData ss in genValue)
{
ss.RENEWAL_PREMIUM_TO_BE_PAID_S = ss.RENEWAL_PREMIUM_TO_BE_PAID.ToString("N", CultureInfo.InvariantCulture);
ss.GENERAL_TARGET_S = ss.GENERAL_TARGET.ToString("N", CultureInfo.InvariantCulture);
ss.GENERAL_ACHIVEMENT_S = ss.GENERAL_ACHIVEMENT.ToString("N", CultureInfo.InvariantCulture);
createChartGen(ss);
}
rsmGenRankingList = genValue;
}
else
{
hasGenData = false;
hasLifeData = false;
noData = true;
IsEnabled = false;
layoutVisible = false;
layoutVisibleGen = false;
rsmGenRankingList.Clear();
}
}
else
{
}
}
private void createChart(LifeRSMData ss)
{
var labels = new List<string>();
var lineEntries = new List<EntryChart>();
float achPercentg = (float)((ss.LIFE_ACHIVEMENT / ss.LIFE_TARGET) * 100);
lineEntries.Add(new EntryChart(0, 100));
lineEntries.Add(new EntryChart(1, achPercentg));
labels.Add("Tar:");
labels.Add("Ach:");
var lineDataSet4 = new BarDataSet(lineEntries, "")
{
Colors = new List<Color>{
Color.FromHex("#248acf"), Color.FromHex("#36DBBB")
}
};
var lineData4 = new BarChartData(new List<IBarDataSet>() { lineDataSet4 });
AxisLeft = new YAxisConfig();
AxisLeft.DrawGridLines = false;
AxisLeft.DrawAxisLine = true;
AxisLeft.Enabled = true;
AxisLeft.AxisMinimum = 0;
AxisLeft.AxisMaximum = 100;
AxisRight = new YAxisConfig();
AxisRight.DrawAxisLine = false;
AxisRight.DrawGridLines = false;
AxisRight.Enabled = false;
XAxis = new XAxisConfig();
XAxis.Granularity = 1f;
XAxis.XAXISPosition = XAXISPosition.BOTTOM;
XAxis.DrawGridLines = false;
XAxis.DrawLabels = true;
XAxis.AxisValueFormatter = new TextByIndexXAxisFormatter(labels);
Legend = new LegendXF();
Legend.Enabled = false;
DescriptionChart = new ChartDescription();
DescriptionChart.Enabled = false;
DescriptionChart.Text = "";
ss.AxisLeft = AxisLeft;
ss.AxisRight = AxisRight;
ss.XAxis = XAxis;
ss.Legend = Legend;
ss.DescriptionChart = DescriptionChart;
ss.chartData = lineData4;
}
public ICommand filterCommand
{
get
{
return new Command(() =>
{
if (IsEnabled)
{
if (companyType != null)
{
if (companyType.Equals("L"))
{
UserDialogs.Instance.ActionSheet(new ActionSheetConfig().SetTitle("Sort using...")
.Add("Due", () => this.SortData("DueA", companyType), "fup.png")
.Add("Due", () => this.SortData("DueD", companyType), "fdown.png")
.Add("Achievement", () => this.SortData("AchA", companyType), "fup.png")
.Add("Achievement", () => this.SortData("AchD", companyType), "fdown.png").SetUseBottomSheet(true));
}
else if (companyType.Equals("G"))
{
UserDialogs.Instance.ActionSheet(new ActionSheetConfig().SetTitle("Sort using...")
.Add("Due", () => this.SortData("DueA", companyType), "fup.png")
.Add("Due", () => this.SortData("DueD", companyType), "fdown.png").SetUseBottomSheet(true));
}
}
}
});
}
}
public ICommand regionClassCommand
{
get
{
return new Command(() =>
{
Application.Current.MainPage.Navigation.PushAsync(new RSMclassView(p_region, SelectedItem));
});
}
}
private void SortData(string caseSwitch, string companyType)
{
}
private MonthData getCurrentMonth(string cType)
{
DateTime now = DateTime.Now;
string currMonth_2 = now.AddMonths(-2).ToString("(MM)/MMM yyyy");
string currMonth_1 = now.AddMonths(-1).ToString("(MM)/MMM yyyy");
string currMonth0 = now.ToString("(MM)/MMM yyyy");
string currMonth1 = now.AddMonths(1).ToString("(MM)/MMM yyyy");
if (cType.Equals("L"))
{
MyList.Add(new MonthData { mName = currMonth_2 });
MyList.Add(new MonthData { mName = currMonth_1 });
MyList.Add(new MonthData { mName = currMonth0 });
MyList.Add(new MonthData { mName = currMonth1 });
}
else
{
MyList.Add(new MonthData { mName = currMonth_2 });
MyList.Add(new MonthData { mName = currMonth_1 });
MyList.Add(new MonthData { mName = currMonth0 });
}
return new MonthData { mName = currMonth0 };
}
}
You can set the ListView to appear above the bottom frame.
Please remove the outer element of the ItemListView and add the following properties for ItemListView:
RelativeLayout.XConstraint="{ConstraintExpression Type=Constant, Constant=0}"
RelativeLayout.YConstraint="{ConstraintExpression Type=Constant, Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1.0}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1.0}"
The whole code is :
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
BackgroundColor="Yellow"
x:Class="TestBottomSheet.MainPage">
<RelativeLayout>
<ListView x:Name="ItemListView" HasUnevenRows="true"
RelativeLayout.XConstraint="{ConstraintExpression Type=Constant, Constant=0}"
RelativeLayout.YConstraint="{ConstraintExpression Type=Constant, Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1.0}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=0.91}"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame HasShadow="True" BackgroundColor="White" CornerRadius="15" Margin="5">
<StackLayout Orientation="Vertical">
<Label Text="{Binding title}" FontSize="Medium"/>
<Label Text="{Binding id}" FontSize="Default"/>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Frame HasShadow="true" CornerRadius="8" Padding="1,4,1,0" BackgroundColor="#faf9f8"
x:Name="bottomSheet" RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,
Property=Height,Factor=.92,Constant=0}" RelativeLayout.WidthConstraint="{ConstraintExpression
Type=RelativeToParent,Property=Width,Factor=1,Constant=0}" RelativeLayout.HeightConstraint="{ConstraintExpression
Type=RelativeToParent,Property=Height,Factor=1,Constant=0}">
<Frame.GestureRecognizers>
<PanGestureRecognizer PanUpdated="OnPanUpdated" />
</Frame.GestureRecognizers>
<StackLayout Spacing="5">
<BoxView HeightRequest="5" CornerRadius="2" WidthRequest="50" BackgroundColor="Gray" HorizontalOptions="Center"/>
<StackLayout BackgroundColor="White" HeightRequest="25">
</StackLayout>
<ListView x:Name="ItemListView2" HasUnevenRows="true" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame HasShadow="True" BackgroundColor="FloralWhite" CornerRadius="15" Margin="5">
<StackLayout Orientation="Vertical">
<Label Text="{Binding id}" FontSize="Default"/>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</Frame>
</RelativeLayout>
</ContentPage>
The result is:

How to change text color and back ground color of Label with databese info In listview?

In my page I use a Listview, which is contains Label;
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
........
........
........
<Label Text="{Binding .}"
TextColor="{DynamicResource Key=textColor}"
VerticalOptions="StartAndExpand"
HorizontalOptions="StartAndExpand"
Grid.Row="1">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</Label.GestureRecognizers>
</Label>
........
........
........
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
I can Change text of Label color with "TapGestureRecognizer_Tapped" metod, which i want;
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
...
...
...
var entity = ((Label)sender);
entity.BackgroundColor = Color.FromHex("54C642");
entity.TextColor = Color.FromHex("FFFFFF"); ;
...
...
...
}
And i save color informations to sqlite database.
Example Data:
ID:01 ||
Colors:1/54C642,2/EA4B3E,3/54C642,4/D8E330.... (As many as the list view item count)
When page is open, i want to Labels color apply with databese info.
(I can change the Listview items colors and save them to the database of the color information. My main problem is; when opening page load the list with the color information (As in the picture))
IMAGE
How can i do?
Thanks.
UPDATE
Here is the problem image: IMAGE
For Label text my data like this ",item1,item2,item3,item4,item5,item6,item7,item8", for backgroundcolor is ",726E6E,EA4B3E,D8E330,54C642,726E6E,726E6E,726E6E,D8E330".
And so i used two list for itemsource.
XAML
<Label Text="{Binding .}"
BackgroundColor="{Binding ., Converter={StaticResource colorconverter}}"
TextColor="{DynamicResource Key=textColor}"
VerticalOptions="StartAndExpand"
HorizontalOptions="StartAndExpand"
Grid.Row="1">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</Label.GestureRecognizers>
</Label>
CS
private async void LstFill()
{
App.Current.Resources["textColor"] = Color.FromHex("FFFFFF");
lstNks.Clear();
lstColors.Clear();
string strNks = "";
string strColors = "";
_sqLiteConnection = await DependencyService.Get<ISQLite>().GetConnection();
var listData = _sqLiteConnection.Table<TBL>().ToList();
strNoksanlar = listData[index].T1NKS;
strRenkler = listData[index].COLOR;
char[] chr = { ',' };
if (strNoksanlar != "")
{
string[] pNks = strNks.Split(chr);
string[] pColors = strColors.Split(chr);
for (int i = 0; i < pNks.Length; i++)
{
if (pNks[i] != "")
{
lstNks.Add(i + ". " + pNks[i]);
}
}
for (int i = 0; i < pColors.Length; i++)
{
if (pColors[i] != "")
{
lstColors.Add(pColors[i]);
}
}
}
lst1Teftis.ItemsSource = null;
lst1Teftis.ItemsSource = lstNks;
lst1Teftis.ItemsSource = lstColors;
}
And i save color informations to sqlite database.Example Data: ID:01
|| Colors:1/54C642,2/EA4B3E,3/54C642,4/D8E330.... (As many as the list
view item count). When page is open, i want to Labels color apply with
databese info.
According to your description, you want to save ListView's Label TextColor in database, I suggest you can create new class that contains two or more string to save ListView's items TextColor, then using DataBinding to display.
I create simple sample using sqlite database that you can take a look.
There are two string properties, one is Label text, another is TextColor.
public class colorclass
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string name { get; set; }
public string color { get; set; }
}
Want to bind color property to Label's TextColor, need to use Xamarin.Forms Binding Value Converters, to convert string to Xamarin.Forms.Color.
<ContentPage.Resources>
<converter:converter1 x:Key="colorconverter" />
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<ListView x:Name="listview1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label
BackgroundColor="Red"
Text="{Binding name}"
TextColor="{Binding color, Converter={StaticResource colorconverter}}"
VerticalOptions="CenterAndExpand">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</Label.GestureRecognizers>
</Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button
x:Name="btninsert"
Clicked="btninsert_Clicked"
Text=" insert data" />
</StackLayout>
</ContentPage.Content>
public class converter1 : IValueConverter
{
Color c;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value!=null)
{
c =Color.FromHex((string)value);
}
return c;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Getting ListView current item by (Label)sender).BindingContext
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var entity = ((Label)sender);
colorclass currentitem = (colorclass)((Label)sender).BindingContext;
currentitem.color = "54C642";
conn.Update(currentitem);
}
Update:
Save listview item color in database, then refresh listview data on contentpage's OnAppearing.
public partial class Page3 : ContentPage
{
public SQLiteConnection conn;
public Page3()
{
InitializeComponent();
conn = GetSQLiteConnection();
// conn.CreateTable<colorclass>();
}
public SQLiteConnection GetSQLiteConnection()
{
var fileName = "colors.db";
var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
var path = Path.Combine(documentPath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var entity = ((Label)sender);
colorclass currentitem = (colorclass)((Label)sender).BindingContext;
currentitem.color = "54C642";
conn.Update(currentitem);
}
protected override void OnAppearing()
{
base.OnAppearing();
listview1.ItemsSource = conn.Table<colorclass>().ToList();
}
}

Xamarin forms webview covers every element in xaml page

I have a webview and a label inside one of my xaml page. I am loading a local html file to the webview inside OnAppearing(). Problem is I cannot see the label. Webview takes whole screen. I tested in Android.
<?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="Test.Views.MyWebView">
<ContentPage.Content>
<StackLayout BackgroundColor="Red" VerticalOptions="FillAndExpand" Orientation="Vertical">
<Label HeightRequest="100" TextColor="Black" Text="Sample"/>
<StackLayout>
<ScrollView>
<other:HybridWebView x:Name="hybridWebView" VerticalOptions="FillAndExpand"
Navigating="webView_Navigating" HeightRequest="400" Navigated="MywebView_Navigated" />
</ScrollView>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Code behind
OnAppearing
protected override void OnAppearing()
{
base.OnAppearing();
NavigationPage.SetHasNavigationBar(this, false);
if (isFirstRun)
{
jsonOutput = JsonConvert.SerializeObject(payData);
//var htmlSource = new HtmlWebViewSource();
var urlSource = new UrlWebViewSource();
string url = DependencyService.Get<IBaseUrl>().Get();
TempUrl = Path.Combine(url, "xamarinhtmlmotor.html");
urlSource.Url = TempUrl;
hybridWebView.Source = urlSource;
isFirstRun = false;
Content = hybridWebView;
}
}
webView_Navigating
private void webView_Navigating(object sender, WebNavigatingEventArgs e)
{
UserDialogs.Instance.ShowLoading("Loading...", MaskType.Black);
}
Here I am currently checking for the android devices
MywebView_Navigated
private async void MywebView_Navigated(object sender, WebNavigatedEventArgs e)
{
UserDialogs.Instance.HideLoading();
if (Device.RuntimePlatform == Device.Android)
{
if (e.Url.Equals("file:///android_asset/web/xamarinhtmlmotor.html"))
{
getResult();
}
else if (e.Url.Equals("http://localhost/receipt_motor.aspx"))
{
string rtNo = "receiptNo";
string cvNo = "<%= hdntxtbxTaksit.ClientID %>";
receiptNo = await hybridWebView.EvaluateJavaScriptAsync($"document.getElementById('{rtNo}').value;");
cvNoteNo = await hybridWebView.EvaluateJavaScriptAsync($"document.getElementById('{cvNo}');");
if (receiptNo != null && !receiptNo.Equals(""))
{
}
if (cvNoteNo != null && !cvNoteNo.Equals(""))
{
}
}
}
}
}
Why don't you try with grid?
<Grid RowSpacing="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="Sample" FontSize="Large" HorizontalOptions="CenterAndExpand"></Label>
<StackLayout Grid.Row="1" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<other:HybridWebView x:Name="hybridWebView" VerticalOptions="FillAndExpand"
Navigating="webView_Navigating" Navigated="MywebView_Navigated" />
</StackLayout>
</Grid>

How to change the Text color of placeholder in Xamarin forms

Is it possible to change the Text color of part of the placeholder.
<Controls:BorderlessEntry Grid.Row="1" Grid.Column="0"
x:Name="ABS_ID"
Placeholder="Enter Name Here *"/>
I want to change the asterisk "*" Color to red and rest of the text will have default color.
Any help is appreciated!
You can try the following workaround:
Wrap an Entry and a Label into a StackLayout. And make the StackLayout like an Entry with placeholder.
The code is like this:
MainPage.xaml:
<StackLayout Orientation="Horizontal" HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<Entry x:Name="ABS_ID"
Text="Enter Name Here "
HorizontalOptions="Start"
Focused="OnEntryFocused"
Unfocused="OnEntryUnFocused"/>
<Label x:Name="ABS_ID2"
Text="*"
TextColor="Red"
HorizontalOptions="StartAndExpand"
VerticalTextAlignment="Center"
Margin="-20"/>
</StackLayout>
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
bool showPlaceHolder = true;
public MainPage()
{
InitializeComponent();
}
void OnEntryFocused(object sender, EventArgs e)
{
if (showPlaceHolder) {
ABS_ID.Text = "";
ABS_ID2.Text = "";
}
}
void OnEntryUnFocused(object sender, EventArgs e)
{
if ((ABS_ID.Text == "") && (ABS_ID2.Text == ""))
{
ABS_ID.Text = "Enter Name Here ";
ABS_ID2.Text = "*";
showPlaceHolder = true;
}
else {
showPlaceHolder = false;
}
}
}
And the result is:

Resources