how to load multiple URL in android using visual studio c# - c#

I am a developing an application (apk) it is nothing but a display of stored images & bitmap images (url).This is my first application & I am using code by watching different tutorials that i need to code over youtube and searching websites to get help.
Below here is the whole code for application.
namespace androidapk
{
[Activity(Label = "android", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity : Android.App.Activity
{
private ImageView ImageContainer;
// private ImageView UrlContainer;
private int CurrentImage = 0;
// private int CurrentUrl = 0;
private Button nextClick;
private Button backClick;
int[] images = { Resource.Drawable.orange, Resource.Drawable.Icon, Resource.Drawable.images02, Resource.Drawable.buttonarrow, Resource.Drawable.images };
// string[] Urls = { "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRiFsZgrhpFIx496REDS7XimTQVo07W6zFwULlNFIO3OpgPNCMc,https://www.google.com.pk/imgres?imgurl=http%3A%2F%2Fpngimg.com%2Fupload%2Fwater_PNG3290.png&imgrefurl=http%3A%2F%2Fpngimg.com%2Fimg%2Fnature%2Fwater&docid=egiWzVBWw_5-bM&tbnid=geXqbWHLhH-PPM%3A&w=1280&h=798&bih=667&biw=1366&ved=0ahUKEwitguqNm8POAhWHWhQKHc_TBewQMwgxKAEwAQ&iact=mrc&uact=8" };
public Action<object, EventArgs> Click { get; private set; }
public int FindViewByIddemoImageview { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
nextClick = (Button)FindViewById(Resource.Id.Btnup);
backClick = (Button)FindViewById(Resource.Id.Btnback);
ImageContainer = (ImageView)FindViewById(Resource.Id.demoImageView);
// UrlContainer = (ImageView)FindViewById();
//Android.Net.Uri url = Android.Net.Uri.Parse("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRiFsZgrhpFIx496REDS7XimTQVo07W6zFwULlNFIO3OpgPNCMc");
var imageBitmap = GetImageBitmapFromUrl("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRiFsZgrhpFIx496REDS7XimTQVo07W6zFwULlNFIO3OpgPNCMc");
RunOnUiThread(() => ImageContainer.SetImageBitmap(imageBitmap));
nextClick.Click += delegate {
NextImagePic();
// NextImageUrl();
};
backClick.Click += delegate {
BackImagePic();
};
//HapticFeedbackConstants
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
private void NextImagePic()
{
if (CurrentImage == 0)
{
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage + 1]));
CurrentImage++;
}
else
{
if (CurrentImage < images.Count() - 1)
{
CurrentImage++;
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage]));
}
else
{
Toast.MakeText(this, "This is last image.", ToastLength.Long).Show();
}
}
}
private void BackImagePic()
{
if (CurrentImage == 0)
{
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage]));
Toast.MakeText(this, "This is first image.", ToastLength.Long).Show();
}
else
{
CurrentImage--;
RunOnUiThread(() => ImageContainer.SetImageResource(images[CurrentImage]));
}
}
}
}
i have displayed successfully images stored using arrays [] but i want to display multiple images in arrays using URL's I have displayed single image using single URL.

Related

How to get current progress when printing using PrintDialog?

I want to keep showing the currently ongoing Page out of the entire page on the UI thread.
However, no event can be referenced.
I've seen these links:
WPF - How to update ProgressBar based on the progress of a method from a different class?
https://learn.microsoft.com/en-us/answers/questions/1165557/wpf-download-file-with-progress-bar
I have the following code now, but I don't know how to do it.
Is there any better way?
<StackPanel Orientation="Horizontal" >
<Button HorizontalAlignment="Center" Width="80" Click="PrintButtonClick">print</Button>
<ProgressBar x:Name="progressbar" Margin="10,0" Maximum="100" Width="140" Height="20" Value="{Binding Progress}"/>
<TextBox IsReadOnly="True" Width="50" Text="{Binding ProgressValue}"/>
</StackPanel>
<DocumentViewer Name="viewer" Grid.Row="1">
<FixedDocument x:Name="fd">
</FixedDocument>
</DocumentViewer>
</StackPanel>
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Xps.Packaging;
using Window = System.Windows.Window;
using System.Windows.Markup;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using PrintDialog = System.Windows.Controls.PrintDialog;
namespace DocumentViewerPrintProgressbar
{
public partial class MainWindow : Window, ICommand, INotifyPropertyChanged
{
TextBlock page1Text = new TextBlock();
public MainWindow()
{
InitializeComponent();
PrintDialog pd = new PrintDialog();
fd.DocumentPaginator.PageSize = new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight);
for (int i = 0; i <= 5; i++)
{
FixedPage page1 = new FixedPage();
page1.Width = fd.DocumentPaginator.PageSize.Width;
page1.Height = fd.DocumentPaginator.PageSize.Height;
UIElement page1Text = pages();
page1.Children.Add(page1Text);
PageContent page1Content = new PageContent();
((IAddChild)page1Content).AddChild(page1);
fd.Pages.Add(page1Content);
}
}
private UIElement pages()
{
Canvas pcan = new Canvas();
TextBlock page1Text = new TextBlock();
page1Text.TextWrapping = TextWrapping.Wrap;
for (int i = 1; i < 1200; i++)
{
page1Text.Text += i.ToString() + "This is a testssssssssssssssssssssssssssssssssssssssssssss";
}
page1Text.FontSize = 40;
page1Text.Margin = new Thickness(96);
pcan.Children.Add(page1Text);
return pcan;
}
void PrintButtonClick(object sender, RoutedEventArgs e)
{
var dlg = new PrintDialog();
// Allow the user to select a PageRange
dlg.UserPageRangeEnabled = true;
if (dlg.ShowDialog() == true)
{
DocumentPaginator paginator = fd.DocumentPaginator;
dlg.PrintDocument(paginator, "Just a test");
}
}
public string ProgressValue { get; set; }
public int Status { get; set; }
public double Progress { get; set; }
public void Execute(object parameter)
{
Progress = 0;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
public static bool PrintWholeDocument(string xpsFilePath, bool hidePrintDialog = false)
{
PrintDialog printDialog = new PrintDialog();
if (!hidePrintDialog)
{
bool? isPrinted = printDialog.ShowDialog();
if (isPrinted != true)
return false;
}
try
{
XpsDocument xpsDocument = new XpsDocument(xpsFilePath, FileAccess.Read);
FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence();
DocumentPaginator docPaginator = fixedDocSeq.DocumentPaginator;
printDialog.PrintDocument(docPaginator, $"Printing {System.IO.Path.GetFileName(xpsFilePath)}");
return true;
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message);
return false;
}
}
}
}
Update:
private void btnPrint_Click(object sender, RoutedEventArgs e)
{
this.Topmost = false;
PrintDialog printDialog = new PrintDialog();
CancellationTokenSource printServerWatchTaskCancellationTokenSource = new CancellationTokenSource();
PrintServer printServer = new PrintServer(PrintSystemDesiredAccess.AdministrateServer);
if (printDialog.ShowDialog() == true)
{
Task printServerTask = new Task(async () =>
{
await this.Dispatcher.InvokeAsync(async () =>
{
PrintQueue _queue = new PrintQueue(printServer, printDialog.PrintQueue.FullName);
StringBuilder sb = new StringBuilder();
PrintSystemJobInfo job;
while (true)
{
_queue.Refresh();
if (_queue.NumberOfJobs > 0)
{
sb.Clear();
job = _queue.GetPrintJobInfoCollection().Where(x => x.Name.Equals("AbleSoft PostDocument2.0")).SingleOrDefault();
if (job != null)
{
switch (job.JobStatus)
{
case PrintJobStatus.Spooling:
sb.AppendLine($"Spooling");
sb.AppendLine($"{job.NumberOfPages} / {PrintTargetFileInfo.Count}");
break;
case PrintJobStatus.Printing:
case (PrintJobStatus.Printing | PrintJobStatus.Retained):
sb.AppendLine($"Printing");
sb.AppendLine($"{job.NumberOfPagesPrinted} / {PrintTargetFileInfo.Count}");
break;
}
ProgressText.Dispatcher.Invoke(() =>
{
ProgressText.Text = sb.ToString();
});
}
}
await Task.Delay(1);
}
}, System.Windows.Threading.DispatcherPriority.Background);
await Task.Delay(1);
}, printServerWatchTaskCancellationTokenSource.Token);
printServerTask.Start();
printDialog.PrintDocument(documentViewer.Document.DocumentPaginator, "AbleSoft PostDocument2.0");
printServerWatchTaskCancellationTokenSource.Cancel();
}
}
The PrintDialog is not using any async API. So printing is synchronous. This means you can't update the UI in realtime.
As a solution you would have to print the document manually. This allows to use asynchronous APIs. In addition, you get more control over the process (for example you can pick a printer or configure the print job explicitly).
To allow the user to pick a printer, you would have to create your own custom small dialog.
A custom DocumentPaginator implementation (RangeDocumentPaginator) is used to support printing page ranges.
MainWindow.xaml.cs
private CancellationTokenSource CancellationTokenSource { get; set; }
private async void OnPrintButtonClickedAsync(object sender, EventArgs e)
{
DocumentPaginator documentPaginator = ((IDocumentPaginatorSource)this.Document).DocumentPaginator;
var progressReporter = new Progress<(int PageNumber, int Percentage)>(ReportProgress);
using var printer = new DocumentPrinter();
this.ProgressBar.Maximum = await printer.GetPageCountAsync(documentPaginator);
this.CancellationTokenSource = new CancellationTokenSource();
try
{
// Print complete document
await printer.PrintFullDocumentAsync(documentPaginator, progressReporter, this.CancellationTokenSource.Token);
// Print document pages 1 to 10.
// The page numbers must be converted to indices 0 to 9.
// The method takes a 'Range' as argument.
// 'Range' is defined as inclusive start index and exclusive end index.
// Therefore the 'Range' for the pages 1 to 10 is '0..10'.
await printer.PrintDocumentPageRangeAsync(documentPaginator, 0..10, progressReporter, this.CancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
}
finally
{
this.CancellationTokenSource.Dispose();
this.CancellationTokenSource = null;
}
}
private void OnCancelButtonClicked(object sender, RoutedEventArgs e)
=> this.CancellationTokenSource?.Cancel();
private void ReportProgress((int PageCount, int Percentage) progress)
=> this.ProgressBar.Value = progress.PageCount;
DocumentPrinter.cs
public class DocumentPrinter : IDisposable
{
private TaskCompletionSource PrintTaskCompletionSource { get; set; }
private TaskCompletionSource<int> ComputePagesTaskCompletionSource { get; set; }
private PrintServer PrintServer { get; }
private IProgress<(int PageNumber, int Percentage)> CurrentProgressReporter { get; set; }
private bool IsPrintJobPending { get; set; }
private CancellationToken CancellationToken { get; set; }
public DocumentPrinter() => this.PrintServer = new LocalPrintServer();
public Task<int> GetPageCountAsync(DocumentPaginator documentPaginator)
{
this.CancellationToken = CancellationToken.None;
if (!documentPaginator.IsPageCountValid)
{
this.ComputePagesTaskCompletionSource = new TaskCompletionSource<int>(TaskCreationOptions.None);
documentPaginator.ComputePageCountCompleted += OnCountingPagesCompleted;
documentPaginator.ComputePageCountAsync();
return this.ComputePagesTaskCompletionSource.Task;
}
return Task.FromResult(documentPaginator.PageCount);
}
public async Task PrintFullDocumentAsync(DocumentPaginator documentPaginator, IProgress<(int PageNumber, int Percentage)> progressReporter, CancellationToken cancellationToken)
=> await PrintDocumentPageRangeAsync(documentPaginator, .., progressReporter, cancellationToken);
public Task PrintDocumentPageRangeAsync(DocumentPaginator documentPaginator, Range pageIndexRange, IProgress<(int PageNumber, int Percentage)> progressReporter, CancellationToken cancellationToke)
{
this.CancellationToken = cancellationToken;
this.CancellationToken.ThrowIfCancellationRequested();
this.IsPrintJobPending = true;
this.CurrentProgressReporter = progressReporter;
this.PrintTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.None);
var rangeDocumentPaginator = new RangeDocumentPaginator(documentPaginator, pageIndexRange);
if (!rangeDocumentPaginator.IsPageCountValid)
{
this.ComputePagesTaskCompletionSource = new TaskCompletionSource<int>(TaskCreationOptions.None);
rangeDocumentPaginator.ComputePageCountCompleted += OnCountingPagesCompleted;
rangeDocumentPaginator.ComputePageCountAsync();
return this.PrintTaskCompletionSource.Task;
}
StartPrintJob(rangeDocumentPaginator);
this.IsPrintJobPending = false;
return this.PrintTaskCompletionSource.Task;
}
private void StartPrintJob(DocumentPaginator documentPaginator)
{
this.CancellationToken.ThrowIfCancellationRequested();
/* Select the destination printer */
// Optionally show a custom printer picker dialog
PrintQueue destinationPrinter = GetPrintQueueFromUser(printServer);
// Alternatively use the default printer
PrintQueue destinationPrinter = printServer.DefaultPrintQueue;
// Alternatively, pick a particular printer explicitly e.g., native PDF printer
PrintQueue destinationPrinter = this.PrintServer.GetPrintQueue("Microsoft Print to PDF");
/* Start the printing */
// Create a XpsDocumentWriter that writes to the printer queue
XpsDocumentWriter documentWriter = PrintQueue.CreateXpsDocumentWriter(destinationPrinter);
documentWriter.WritingProgressChanged += OnPrintProgressChanged;
documentWriter.WritingCompleted += OnPrintingCompleted;
documentWriter.WriteAsync(documentPaginator);
}
private PrintQueue GetPrintQueueFromUser(PrintServer printServer)
{
PrintQueueCollection printers = printServer.GetPrintQueues();
// TODO::Implement MyPrinterPickerDialog (extend Window)
var myPrinterPickerDialog = new MyPrinterPickerDialog(printers);
myPrinterPickerDialog.ShowDialog();
return myPrinterPickerDialog.SelectedPrintQueue;
}
private void OnCountingPagesCompleted(object sender,
System.ComponentModel.AsyncCompletedEventArgs e)
{
var documentPaginator = sender as DocumentPaginator;
documentPaginator.ComputePageCountCompleted -= OnCountingPagesCompleted;
if (this.CancellationToken.IsCancellationRequested)
{
this.ComputePagesTaskCompletionSource.TrySetCanceled(this.CancellationToken);
this.CancellationToken.ThrowIfCancellationRequested();
}
else
{
_ = this.ComputePagesTaskCompletionSource.TrySetResult(documentPaginator.PageCount);
}
if (this.IsPrintJobPending)
{
StartPrintJob(documentPaginator);
}
}
private void OnPrintProgressChanged(object sender, WritingProgressChangedEventArgs e)
{
var documentPrinter = sender as XpsDocumentWriter;
this.CurrentProgressReporter.Report((e.Number, e.ProgressPercentage));
if (this.CancellationToken.IsCancellationRequested)
{
documentPrinter.WritingCancelled += OnPrintingCancelled;
documentPrinter.CancelAsync();
}
}
private void OnPrintingCancelled(object sender, WritingCancelledEventArgs e)
{
var documentPrinter = sender as XpsDocumentWriter;
documentPrinter.WritingCancelled -= OnPrintingCancelled;
this.PrintTaskCompletionSource.TrySetCanceled(this.CancellationToken);
this.CancellationToken.ThrowIfCancellationRequested();
}
private void OnPrintingCompleted(object sender, WritingCompletedEventArgs e)
{
// TODO::Handle errors by checking event args
documentWriter.WritingCompleted -= OnPrintingCompleted;
documentWriter.WritingProgressChanged -= OnPrintProgressChanged;
_ = this.PrintTaskCompletionSource.TrySetResult();
}
private bool disposedValue;
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if (disposing)
{
this.PrintServer.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
this.disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~DocumentPrinter()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
RangeDocumentPaginator.cs
internal class RangeDocumentPaginator : DocumentPaginator
{
protected RangeDocumentPaginator() : base() { }
public RangeDocumentPaginator(DocumentPaginator documentPaginator, Range pageNumberRange)
{
this.DocumentPaginator = documentPaginator;
this.PageIndexRange = pageNumberRange;
if (!this.DocumentPaginator.IsPageCountValid)
{
this.DocumentPaginator.ComputePageCountCompleted += OnPageCountCompleted;
this.DocumentPaginator.ComputePageCountAsync();
}
else
{
ThrowIfPageRangeIsInvalid();
}
}
private void ThrowIfPageRangeIsInvalid()
{
if (this.PageIndexRange.Start.Value < 0
|| this.PageIndexRange.End.Value > this.DocumentPaginator.PageCount)
{
throw new IndexOutOfRangeException();
}
}
private void OnPageCountCompleted(object sender, AsyncCompletedEventArgs e)
=> ThrowIfPageRangeIsInvalid();
public override DocumentPage GetPage(int pageIndex)
{
// XpsDocumentWriter will always start with page index 0.
// We have to use the start page index as offset
// to return the correct pages of the range from the underlying document.
// XpsDocumentWriter will use the PageCount property to know how many pages it can fetch.
// We have manipulated the PageCount property to return the count of the pages contained within the range.
int pageOffset = this.PageIndexRange.Start.Value;
pageIndex += pageOffset;
return pageIndex < this.PageIndexRange.Start.Value
|| (pageIndex >= this.PageIndexRange.End.Value && !this.IsRangeFullDocument)
? DocumentPage.Missing
: this.DocumentPaginator.GetPage(pageIndex);
}
public override bool IsPageCountValid => this.DocumentPaginator.IsPageCountValid;
public override int PageCount
{
get
{
int range = this.PageIndexRange.End.Value - this.PageIndexRange.Start.Value;
return this.IsRangeFullDocument
? this.DocumentPaginator.PageCount
: range;
}
}
public override Size PageSize { get => this.DocumentPaginator.PageSize; set => this.DocumentPaginator.PageSize = value; }
public override IDocumentPaginatorSource Source => this.DocumentPaginator.Source;
public Range PageIndexRange { get; set; }
public bool IsRangeFullDocument => this.PageIndexRange.Equals(Range.All);
private DocumentPaginator DocumentPaginator { get; }
}

Music Player in C# Does Tot Play The Song I Added Later

I made an mp3 player in C#. If I select the songs at once, they automatically play one after the other, but when it comes to a song I added later, I get a "System.IndexOutOfRangeException" error. When I add music later, I want the song to play automatically one after the other, how can I do that?
string[] yol, dosya;
private void Btn_Muzik_Ekle_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
dosya = ofd.SafeFileNames;
yol = ofd.FileNames;
for (int x = 0; x < dosya.Length; x++)
{
Lb_Muzik_Listesi.Items.Add(dosya[x]);
}
}
}
private void Lb_Muzik_Listesi_SelectedIndexChanged(object sender, EventArgs e)
{
//This Is Where I Got The Error
OynatmaEkranı.URL = yol[Lb_Muzik_Listesi.SelectedIndex];
OynatmaEkranı.Ctlcontrols.play();
try
{
var file = TagLib.File.Create(yol[Lb_Muzik_Listesi.SelectedIndex]);
var bin = (byte[])(file.Tag.Pictures[0].Data.Data);
Pb_Muzik_Kapak.Image = Image.FromStream(new MemoryStream(bin));
}
catch
{
}
}
private void Zamanlayıcı_Tick(object sender, EventArgs e) //Timer
{
if (OynatmaEkranı.playState==WMPLib.WMPPlayState.wmppsPlaying)
{
Pb_Muzik.Maximum=(int)OynatmaEkranı.Ctlcontrols.currentItem.duration;
Pb_Muzik.Value = (int)OynatmaEkranı.Ctlcontrols.currentPosition;
try
{
Lbl_Muzik_Sure.Text = OynatmaEkranı.Ctlcontrols.currentPositionString;
Lbl_Muzik_Bitis.Text = OynatmaEkranı.Ctlcontrols.currentItem
.durationString.ToString();
}
catch
{
}
}
if (Pb_Muzik.Value==Pb_Muzik.Maximum)
{
if (Lb_Muzik_Listesi.SelectedIndex<Lb_Muzik_Listesi.Items.Count-1)
{
Lb_Muzik_Listesi.SelectedIndex = Lb_Muzik_Listesi.SelectedIndex + 1;
}
}
}
You can avoid this problem managing your data in the ListBox. Create a class with your required info (the file and the name):
public class MuzikItem
{
public MuzikItem(string file)
{
this.Text = System.IO.Path.GetFileNameWithoutExtension(file);
this.Url = file;
}
public string Text { get; set; }
public string Url { get; set; }
public override string ToString()
{
// This is the text to show in ListBox
return this.Text;
}
}
Add items to the ListBox using this class:
foreach (var file in ofd.FileNames)
{
var item = new MuzikItem(file);
Lb_Muzik_Listesi.Items.Add(item);
}
And use it:
var item = Lb_Muzik_Listesi.SelectedItem as MuzikItem;
if (item != null)
{
OynatmaEkranı.URL = item.Url;
OynatmaEkranı.Ctlcontrols.play();
try
{
var file = TagLib.File.Create(item.Url);
var bin = (byte[])file.Tag.Pictures[0].Data.Data;
Pb_Muzik_Kapak.Image = Image.FromStream(new MemoryStream(bin));
}
catch
{
}
}
You try to get the selected item as a MuzikItem (all your items are of this class so this return null only when no item is selected) and with this, you have the Url.
UPDATE
I like manage this things with events. In your Ticks methods:
if (Pb_Muzik.Value == Pb_Muzik.Maximum)
{
OnSongFinished();
}
And create a method to manage this event:
private void OnSongFinished()
{
if (Lb_Muzik_Listesi.SelectedIndex < Lb_Muzik_Listesi.Items.Count - 1)
{
Lb_Muzik_Listesi.SelectedIndex = Lb_Muzik_Listesi.SelectedIndex + 1;
}
else
{
// Stop the player
OynatmaEkrani.Ctlcontrols.stop();
}
}

How to change FreshTabbedNavigationContainer tabbed page to top and change icon and font size for ios in xamarin forms

I have using freshmvvm for my xamarin forms application. FreshTabbedNavigationContainer tabbed page is working fine with android. I have customized the android tabbed page font size, font color, image size. But in IOS I don't know how to change the tab bar from bottom to top like in android and how to change the size of the icon and font. Please anyone suggest me to done this. My tabbed page code is below,
var tabbedPage = new FreshTabbedNavigationContainer();
tabbedPage.AddTab<FirstPageModel>("One", "icon.png");
tabbedPage.AddTab<SecondPageModel>("Two", "icon.png");
await Application.Current.MainPage.Navigation.PushAsync(tabbedPage);
NavigationPage.SetHasNavigationBar(tabbedPage, false);
I have changed the tabbar scrollable using custom renderer for android like this,
public override void OnViewAdded(Android.Views.View child)
{
base.OnViewAdded(child);
var tabLayout = child as TabLayout;
if (tabLayout != null)
{
tabLayout.TabMode = TabLayout.ModeScrollable;
}
}
How to change the tab bar as scrollable for ios. In my tabbed page, the space between text and icon is zero. Please refer the screenshot.
Naxam's GitHub has sort of a similar implementation using a Customized version of Xamarin Forms TabbedPage, But since FreshTabbedNavigationContainer inherits from the same(TabbedPage) you can just use it instead and it should work like a charm.
public class TopTabbedPage : FreshTabbedNavigationContainer
{
public TopTabbedPage()
{
//BarBackgroundColor = Color.Blue;
//BarTextColor = Color.White;
}
public static readonly BindableProperty BarIndicatorColorProperty = BindableProperty.Create(
nameof(BarIndicatorColor),
typeof(Color),
typeof(TopTabbedPage),
Color.White,
BindingMode.OneWay);
public Color BarIndicatorColor
{
get { return (Color)GetValue(BarIndicatorColorProperty); }
set { SetValue(BarIndicatorColorProperty, value); }
}
public static readonly BindableProperty SwipeEnabledColorProperty = BindableProperty.Create(
nameof(SwipeEnabled),
typeof(bool),
typeof(TopTabbedPage),
true,
BindingMode.OneWay);
public bool SwipeEnabled
{
get { return (bool)GetValue(SwipeEnabledColorProperty); }
set { SetValue(SwipeEnabledColorProperty, value); }
}
}
And then the renderer would look something like this:
[assembly: ExportRenderer(typeof(TopTabbedPage), typeof(TopTabbedRenderer))]
namespace Naxam.Controls.Platform.iOS
{
using Platform = Xamarin.Forms.Platform.iOS.Platform;
using Forms = Xamarin.Forms.Forms;
public partial class TopTabbedRenderer :
UIViewController
{
public static void Init()
{
}
UIColor _defaultBarColor;
bool _defaultBarColorSet;
bool _loaded;
Size _queuedSize;
int lastSelectedIndex;
Page Page => Element as Page;
UIPageViewController pageViewController;
protected UIViewController SelectedViewController;
protected IList<UIViewController> ViewControllers;
protected IPageController PageController
{
get { return Page; }
}
protected TopTabbedPage Tabbed
{
get { return (TopTabbedPage)Element; }
}
protected TabsView TabBar;
private NSLayoutConstraint tabBarHeight;
public TopTabbedRenderer()
{
ViewControllers = new UIViewController[0];
pageViewController = new UIPageViewController(
UIPageViewControllerTransitionStyle.Scroll,
UIPageViewControllerNavigationOrientation.Horizontal,
UIPageViewControllerSpineLocation.None
);
TabBar = new TabsView
{
TranslatesAutoresizingMaskIntoConstraints = false
};
TabBar.TabsSelectionChanged += HandleTabsSelectionChanged;
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
View.SetNeedsLayout();
}
public override void ViewDidAppear(bool animated)
{
PageController.SendAppearing();
base.ViewDidAppear(animated);
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
PageController.SendDisappearing();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
View.AddSubview(TabBar);
AddChildViewController(pageViewController);
View.AddSubview(pageViewController.View);
pageViewController.View.TranslatesAutoresizingMaskIntoConstraints = false;
pageViewController.DidMoveToParentViewController(this);
var views = NSDictionary.FromObjectsAndKeys(
new NSObject[] {
TabBar,
pageViewController.View
},
new NSObject[] {
(NSString) "tabbar",
(NSString) "content"
}
);
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|-0-[tabbar]-0-[content]-0-|",
0,
null,
views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|-0-[tabbar]-0-|",
0,
null,
views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|-0-[content]-0-|",
0,
null,
views));
tabBarHeight = NSLayoutConstraint.Create(
TabBar,
NSLayoutAttribute.Height,
NSLayoutRelation.Equal,
1, 68
);
TabBar.AddConstraint(tabBarHeight);
if (pageViewController.ViewControllers.Length == 0
&& lastSelectedIndex >= 0 || lastSelectedIndex < ViewControllers.Count)
{
pageViewController.SetViewControllers(
new[] { ViewControllers[lastSelectedIndex] },
UIPageViewControllerNavigationDirection.Forward,
true, null
);
}
UpdateSwipe(Tabbed.SwipeEnabled);
pageViewController.DidFinishAnimating += HandlePageViewControllerDidFinishAnimating;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
PageController?.SendDisappearing();
if (Tabbed != null)
{
Tabbed.PropertyChanged -= OnPropertyChanged;
Tabbed.PagesChanged -= OnPagesChanged;
TabBar.TabsSelectionChanged -= HandleTabsSelectionChanged;
}
if (pageViewController != null)
{
pageViewController.WeakDataSource = null;
pageViewController.DidFinishAnimating -= HandlePageViewControllerDidFinishAnimating;
pageViewController?.Dispose();
}
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
ElementChanged?.Invoke(this, e);
}
UIViewController GetViewController(Page page)
{
var renderer = Platform.GetRenderer(page);
return renderer?.ViewController;
}
void OnPagePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != Page.TitleProperty.PropertyName)
return;
if (!(sender is Page page) || page.Title is null)
return;
TabBar.ReplaceItem(page.Title, Tabbed.Children.IndexOf(page));
}
void OnPagesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
e.Apply((o, i, c) => SetupPage((Page)o, i), (o, i) => TeardownPage((Page)o, i), Reset);
SetControllers();
UIViewController controller = null;
if (Tabbed.CurrentPage != null)
{
controller = GetViewController(Tabbed.CurrentPage);
}
if (controller != null && controller != SelectedViewController)
{
SelectedViewController = controller;
var index = ViewControllers.IndexOf(SelectedViewController);
MoveToByIndex(index);
TabBar.SelectedIndex = index;
}
}
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(TabbedPage.CurrentPage))
{
var current = Tabbed.CurrentPage;
if (current == null)
return;
var controller = GetViewController(current);
if (controller == null)
return;
SelectedViewController = controller;
var index = ViewControllers.IndexOf(SelectedViewController);
MoveToByIndex(index);
TabBar.SelectedIndex = index;
}
else if (e.PropertyName == TabbedPage.BarBackgroundColorProperty.PropertyName)
{
UpdateBarBackgroundColor();
}
else if (e.PropertyName == TabbedPage.BarTextColorProperty.PropertyName)
{
UpdateBarTextColor();
}
else if (e.PropertyName == TopTabbedPage.BarIndicatorColorProperty.PropertyName)
{
UpdateBarIndicatorColor();
}
else if (e.PropertyName == TopTabbedPage.SwipeEnabledColorProperty.PropertyName)
{
UpdateSwipe(Tabbed.SwipeEnabled);
}
}
public override UIViewController ChildViewControllerForStatusBarHidden()
{
var current = Tabbed.CurrentPage;
if (current == null)
return null;
return GetViewController(current);
}
void UpdateSwipe(bool swipeEnabled)
{
pageViewController.WeakDataSource = swipeEnabled ? this : null;
}
void Reset()
{
var i = 0;
foreach (var page in Tabbed.Children)
{
SetupPage(page, i++);
}
}
void SetControllers()
{
var list = new List<UIViewController>();
var titles = new List<string>();
for (var i = 0; i < Tabbed.Children.Count; i++)
{
var child = Tabbed.Children[i];
var v = child as VisualElement;
if (v == null)
continue;
var renderer = Platform.GetRenderer(v);
if (renderer == null) continue;
list.Add(renderer.ViewController);
titles.Add(Tabbed.Children[i].Title);
}
ViewControllers = list.ToArray();
TabBar.SetItems(titles);
}
void SetupPage(Page page, int index)
{
IVisualElementRenderer renderer = Platform.GetRenderer(page);
if (renderer == null)
{
renderer = Platform.CreateRenderer(page);
Platform.SetRenderer(page, renderer);
}
page.PropertyChanged -= OnPagePropertyChanged;
page.PropertyChanged += OnPagePropertyChanged;
}
void TeardownPage(Page page, int index)
{
page.PropertyChanged -= OnPagePropertyChanged;
Platform.SetRenderer(page, null);
}
void UpdateBarBackgroundColor()
{
if (Tabbed == null || TabBar == null)
return;
var barBackgroundColor = Tabbed.BarBackgroundColor;
if (!_defaultBarColorSet)
{
_defaultBarColor = TabBar.BackgroundColor;
_defaultBarColorSet = true;
}
TabBar.BackgroundColor = barBackgroundColor.ToUIColor();
}
void UpdateBarTextColor()
{
TabBar.TextColor = Tabbed.BarTextColor.ToUIColor();
}
void UpdateBarIndicatorColor()
{
TabBar.IndicatorColor = Tabbed.BarIndicatorColor.ToUIColor();
}
}
}

xamarin.ios mp3 streaming from url stops before its end

I'm developing an ios app with xamarin, that contains some mp3 files to stream in the app.
i used thissample, and it seems to work fine...
but the mp3 stops before its end, always at around 2' 30"
this is the code i used:
public partial class PlayerViewController : UIViewController
{
NSTimer updatingTimer;
StreamingPlayback player;
public event EventHandler<ErrorArg> ErrorOccurred;
public string SourceUrl { get; private set; }
public string Title { get; private set; }
public PlayerOption PlayerOption { get; private set; }
public bool IsPlaying { get; private set; }
public PlayerViewController (PlayerOption playerOption, string sourceUrl, string title) : base ("PlayerViewController", null)
{
PlayerOption = playerOption;
SourceUrl = sourceUrl;
Title = title;
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
this.View = View;
volumeSlider.TouchUpInside += SetVolume;
playPauseButton.TouchUpInside += PlayPauseButtonClickHandler;
headerMusic.Text = this.Title;
}
void SetVolume (object sender, EventArgs e)
{
if (player == null)
return;
player.Volume = volumeSlider.Value;
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
Title = PlayerOption == PlayerOption.Stream ? "Stream " : "Stream & Save";
playPauseButton.TitleLabel.Text = "Pause";
timeLabel.Text = string.Empty;
// Create a shared intance session & check
var session = AVAudioSession.SharedInstance ();
if (session == null) {
var alert = new UIAlertView ("Playback error", "Unable to playback stream", null, "Cancel");
alert.Show ();
alert.Clicked += (object sender, UIButtonEventArgs e) => alert.DismissWithClickedButtonIndex (0, true);
} else {
StartPlayback ();
IsPlaying = true;
// Set up the session for playback category
NSError error;
session.SetCategory (AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.DefaultToSpeaker);
session.OverrideOutputAudioPort (AVAudioSessionPortOverride.Speaker, out error);
}
}
public override void ViewDidDisappear (bool animated)
{
base.ViewDidDisappear (animated);
if (updatingTimer != null)
updatingTimer.Invalidate ();
if (player != null) {
player.FlushAndClose ();
player = null;
}
}
void PlayPauseButtonClickHandler (object sender, EventArgs e)
{
if (player == null)
return;
if (IsPlaying)
player.Pause ();
else
player.Play ();
var title = IsPlaying ? "Play" : "Pause";
playPauseButton.SetTitle (title, UIControlState.Normal);
playPauseButton.SetTitle (title, UIControlState.Selected);
IsPlaying = !IsPlaying;
}
void StartPlayback ()
{
try {
var request = (HttpWebRequest)WebRequest.Create (SourceUrl);
request.BeginGetResponse (StreamDownloadedHandler, request);
} catch (Exception e) {
string.Format ("Error: {0}", e.ToString ());
}
}
void RaiseErrorOccurredEvent (string message)
{
var handler = ErrorOccurred;
if (handler != null)
handler (this, new ErrorArg { Description = message });
}
void StreamDownloadedHandler (IAsyncResult result)
{
var buffer = new byte [8192];
int l = 0;
int inputStreamLength;
double sampleRate = 0;
Stream inputStream;
AudioQueueTimeline timeline = null;
var request = result.AsyncState as HttpWebRequest;
try {
var response = request.EndGetResponse (result);
var responseStream = response.GetResponseStream ();
if (PlayerOption == PlayerOption.StreamAndSave)
inputStream = GetQueueStream (responseStream);
else
inputStream = responseStream;
using (player = new StreamingPlayback ()) {
player.OutputReady += delegate {
timeline = player.OutputQueue.CreateTimeline ();
sampleRate = player.OutputQueue.SampleRate;
};
InvokeOnMainThread (delegate {
if (updatingTimer != null)
updatingTimer.Invalidate ();
updatingTimer = NSTimer.CreateRepeatingScheduledTimer (0.5, (timer) => RepeatingAction (timeline, sampleRate));
});
while ((inputStreamLength = inputStream.Read (buffer, 0, buffer.Length)) != 0 && player != null) {
l += inputStreamLength;
player.ParseBytes (buffer, inputStreamLength, false, l == (int)response.ContentLength);
InvokeOnMainThread (delegate {
progressBar.Progress = l / (float)response.ContentLength;
});
}
}
} catch (Exception e) {
RaiseErrorOccurredEvent ("Error fetching response stream\n" + e);
Debug.WriteLine (e);
InvokeOnMainThread (delegate {
if (NavigationController != null)
NavigationController.PopToRootViewController (true);
});
}
}
void RepeatingAction (AudioQueueTimeline timeline, double sampleRate)
{
var queue = player.OutputQueue;
if (queue == null || timeline == null)
return;
bool disc = false;
var time = new AudioTimeStamp ();
queue.GetCurrentTime (timeline, ref time, ref disc);
playbackTime.Text = FormatTime (time.SampleTime / sampleRate);
}
string FormatTime (double time)
{
double minutes = time / 60;
double seconds = time % 60;
return String.Format ("{0}:{1:D2}", (int)minutes, (int)seconds);
}
Stream GetQueueStream (Stream responseStream)
{
var queueStream = new QueueStream (Environment.GetFolderPath (Environment.SpecialFolder.Personal) + "/copy.mp3");
var t = new Thread ((x) => {
var tbuf = new byte [8192];
int count;
while ((count = responseStream.Read (tbuf, 0, tbuf.Length)) != 0)
queueStream.Push (tbuf, 0, count);
});
t.Start ();
return queueStream;
}
}
how can i solve this problem?
thanks in advance
Had the same issue.
Open the StreamingPlayback.cs file
Change the variable
int bufferSize = 128 * 1024
Into
int bufferSize = 128 * 128
Or try other sizes..
It worked for me

How to get latitude and longitude in Mono for android?

First i worked with this tutorial tutorial
to get latitude and longitude, but i get nothing, so this is my code :
[Activity(Label = "GetLocation", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity1 : Activity, ILocationListener
{
private Location _currentLocation;
private LocationManager _locationManager;
private TextView _locationText;
private TextView _addressText;
private string _locationProvider;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_addressText = FindViewById<TextView>(Resource.Id.address_text);
_locationText = FindViewById<TextView>(Resource.Id.location_text);
FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;
InitializeLocationManager();
}
private void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
var criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
var acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = String.Empty;
}
}
protected override void OnResume()
{
base.OnResume();
_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
}
protected override void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdates(this);
}
private void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
_addressText.Text = "Can't determine the current location.";
return;
}
new Thread(() =>
{
var addressText = "Unable to find a location.";
var geocoder = new Geocoder(this);
var addressList = geocoder.GetFromLocation(_currentLocation.Latitude, _currentLocation.Longitude, 50);
var address = addressList.FirstOrDefault();
if (address != null)
{
var deviceLocation = new StringBuilder();
for (var i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceLocation.Append(address.GetAddressLine(i))
.AppendLine(",");
}
_addressText.Text = deviceLocation.ToString();
}
RunOnUiThread(() => { _addressText.Text = addressText; });
}).Start();
}
public void OnLocationChanged(Location location)
{
_currentLocation = location;
if (_currentLocation == null)
{
_locationText.Text = "Unable to determine your location.";
}
else
{
_locationText.Text = String.Format("{0},{1}", _currentLocation.Latitude, _currentLocation.Longitude);
}
}
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
}
So please if someone has any idea about what wrong with my code i will be very appreciative.
There is one spot in your code where you're updating the the UI _addressText.Text from a background thread. That could also account for why, when you click the button, you're not seeing any address updates. See below for a snippet of the one line of code:
if (address != null)
{
var deviceLocation = new StringBuilder();
for (var i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceLocation.Append(address.GetAddressLine(i))
.AppendLine(",");
}
// Here you were updating the UI thread from the background:
RunOnUiThread(() => _addressText.Text = deviceLocation.ToString());
}

Categories

Resources