Xamarin Cheatsheet¶
Xamarin - Cross-Platform Mobile Apps mit .NET
Xamarin ist eine Open-Source-Plattform für den Aufbau moderner und performanter Anwendungen für iOS, Android und Windows mit .NET. Xamarin ist eine Abstraktionsschicht, die die Kommunikation des gemeinsamen Codes mit dem zugrunde liegenden Plattformcode verwaltet. < p>
Inhaltsverzeichnis¶
- [Installation](#installation
- (#getting-started)
- [Projektstruktur](#project-structure_
- Xamarin.Formulare
- Xamarin.Native
- (XAML) (#xaml)
- [Datenbindung](LINK_6__
- [Navigation](LINK_7__
- (#dependencyservice_)
- [Kustom Renderers](LINK_9_
- Effekte
- [MessagingCenter](LINK_11__
- [Daten Persistence](LINK_12_
- [Netzwerk](#networking_
- Test
- Bestellung
- Beste Praktiken
- (#troubleshooting_)
Installation¶
Voraussetzungen¶
# Install Visual Studio (Windows) or Visual Studio for Mac (macOS)
# Make sure to include the "Mobile development with .NET" workload
# For iOS development on Windows, you need a Mac with Xcode and Visual Studio for Mac installed
```_
### Installation überprüfen
```bash
# Open Visual Studio Installer
# Check if "Mobile development with .NET" is installed
# Check for Android SDK and NDK
# Visual Studio > Tools > Options > Xamarin > Android Settings
# Check for Xcode and Apple SDKs (macOS)
# Visual Studio for Mac > Preferences > Projects > SDK Locations > Apple
```_
## Erste Schritte
### Neues Projekt erstellen
```bash
# In Visual Studio
# File > New > Project
# Select "Mobile App (Xamarin.Forms)"
# Choose a template (Blank, Tabbed, Shell)
# In Visual Studio for Mac
# File > New Solution
# Select "Multiplatform > App > Xamarin.Forms"
# Choose a template (Blank, Tabbed, Shell)
```_
### Die App starten
```bash
# Select a startup project (Android or iOS)
# Choose a device or emulator
# Click the "Run" button or press F5
```_
## Projektstruktur
Xamarin. Formulare¶
Seiten¶
```csharp // ContentPage public class MyContentPage : ContentPage { public MyContentPage() { Content = new StackLayout { Children = { new Label { Text = "Welcome to Xamarin.Forms!" } } }; } }
// TabbedPage public class MyTabbedPage : TabbedPage { public MyTabbedPage() { Children.Add(new MyContentPage { Title = "Tab 1" }); Children.Add(new MyContentPage { Title = "Tab 2" }); } }
// FlyoutPage (Master-Detail) public class MyFlyoutPage : FlyoutPage { public MyFlyoutPage() { Flyout = new ContentPage { Title = "Menu" }; Detail = new NavigationPage(new MyContentPage()); } } ```_
Layouts¶
```csharp // StackLayout new StackLayout { Orientation = StackOrientation.Vertical, Spacing = 10, Children = { new Label(), new Button() } };
// Grid new Grid { RowDefinitions = { new RowDefinition { Height = GridLength.Auto } }, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) } }, Children = { { new Label(), 0, 0 } } };
// FlexLayout new FlexLayout { Direction = FlexDirection.Row, JustifyContent = FlexJustify.SpaceBetween, Children = { new Label(), new Button() } };
// AbsoluteLayout new AbsoluteLayout { Children = { { new BoxView { Color = Colors.Blue }, new Rectangle(0, 0, 100, 100) } } };
// RelativeLayout new RelativeLayout { Children = { { new BoxView(), Constraint.Constant(0) } } }; ```_
Kontrolle¶
```csharp // Label new Label { Text = "Hello, Xamarin!", FontSize = 24 };
// Button new Button { Text = "Click Me", Command = new Command(() => DisplayAlert("Title", "Message", "OK")) };
// Entry new Entry { Placeholder = "Enter text" };
// Editor new Editor { Placeholder = "Enter multi-line text" };
// SearchBar new SearchBar { Placeholder = "Search..." };
// Slider new Slider { Minimum = 0, Maximum = 100 };
// Stepper new Stepper { Minimum = 0, Maximum = 10 };
// Switch new Switch { IsToggled = true };
// DatePicker new DatePicker();
// TimePicker new TimePicker();
// ListView new ListView { ItemsSource = new[] { "Item 1", "Item 2" }, ItemTemplate = new DataTemplate(() => { var cell = new TextCell(); cell.SetBinding(TextCell.TextProperty, "."); return cell; }) };
// CollectionView new CollectionView { ItemsSource = new[] { "Item 1", "Item 2" } }; ```_
Xamarin. Native¶
Xamarin. Android¶
```csharp // MainActivity.cs [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)] public class MainActivity : AppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main);
var button = FindViewById<Button>(Resource.Id.myButton);
button.Click += (sender, e) =>
{
Toast.MakeText(this, "Button Clicked!", ToastLength.Short).Show();
};
}
} ```_
Xamarin.iOS¶
```csharp // ViewController.cs public partial class ViewController : UIViewController { public ViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
base.ViewDidLoad();
var button = new UIButton(UIButtonType.System);
button.Frame = new CGRect(20, 200, 280, 44);
button.SetTitle("Click Me", UIControlState.Normal);
button.TouchUpInside += (sender, e) =>
{
var alert = UIAlertController.Create("Title", "Message", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
};
View.AddSubview(button);
}
} ```_
XAML¶
```xml
```csharp // MainPage.xaml.cs public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); }
private void OnButtonClicked(object sender, EventArgs e)
{
DisplayAlert("Title", "Message", "OK");
}
} ```_
Datenbindung¶
```xml
public class MyViewModel : INotifyPropertyChanged { private string _name; public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Navigation¶
```csharp // Push a new page await Navigation.PushAsync(new DetailsPage());
// Pop a page await Navigation.PopAsync();
// Pop to root await Navigation.PopToRootAsync();
// Pass data await Navigation.PushAsync(new DetailsPage(item));
// Modal navigation await Navigation.PushModalAsync(new ModalPage()); await Navigation.PopModalAsync(); ```_
DependanceService¶
```csharp // Define an interface in shared code public interface ITextToSpeech { void Speak(string text); }
// Implement the interface in platform-specific projects // Android [assembly: Dependency(typeof(TextToSpeech_Android))] namespace MyApp.Droid { public class TextToSpeech_Android : ITextToSpeech { ... } }
// iOS [assembly: Dependency(typeof(TextToSpeech_iOS))] namespace MyApp.iOS { public class TextToSpeech_iOS : ITextToSpeech { ... } }
// Use the service in shared code
DependencyService.Get
Kundenspezifische Render¶
```csharp // Create a custom control in shared code public class MyEntry : Entry { }
// Create a custom renderer in platform-specific projects
// Android
[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))]
namespace MyApp.Droid
{
public class MyEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs
// iOS
[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))]
namespace MyApp.iOS
{
public class MyEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs
Auswirkungen¶
```csharp // Create an effect in shared code public class FocusEffect : RoutingEffect { public FocusEffect() : base("MyApp.FocusEffect") { } }
// Implement the effect in platform-specific projects // Android [assembly: ResolutionGroupName("MyApp")] [assembly: ExportEffect(typeof(FocusEffect_Android), "FocusEffect")] namespace MyApp.Droid { public class FocusEffect_Android : PlatformEffect { ... } }
// Use the effect in XAML
Messen und Messen¶
```csharp
// Subscribe to a message
MessagingCenter.Subscribe
// Send a message MessagingCenter.Send(this, "Hi", "John");
// Unsubscribe
MessagingCenter.Unsubscribe
Daten Persistenz¶
Vorlieben¶
```csharp // Set a value Preferences.Set("my_key", "my_value");
// Get a value var value = Preferences.Get("my_key", "default_value"); ```_
Dateisystem¶
```csharp // Get the local app data folder var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var filename = Path.Combine(path, "myfile.txt");
// Write to a file File.WriteAllText(filename, "Hello, Xamarin!");
// Read from a file var content = File.ReadAllText(filename); ```_
SQLite¶
```csharp // Install sqlite-net-pcl NuGet package
// Create a model public class MyItem { [PrimaryKey, AutoIncrement] public int ID { get; set; } public string Text { get; set; } }
// Create a database connection
var db = new SQLiteAsyncConnection(dbPath);
await db.CreateTableAsync
// Save an item await db.InsertAsync(item);
// Get all items
var items = await db.Table
Vernetzung¶
HttpClient¶
csharp
var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/items");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var items = JsonConvert.DeserializeObject<List<MyItem>>(content);
}_
Refit¶
```csharp // Install Refit NuGet package
// Define an interface
public interface IMyApi
{
[Get("/items")]
Task> GetItems();
}
// Use the interface
var api = RestService.For
Prüfung¶
Einheitsprüfung¶
```csharp // Use a testing framework like NUnit or xUnit [Test] public void MyViewModel_MyCommand_ShouldDoSomething() { // Arrange var viewModel = new MyViewModel();
// Act
viewModel.MyCommand.Execute(null);
// Assert
Assert.IsTrue(viewModel.MyProperty);
} ```_
UI Testing¶
```csharp // Use Xamarin.UITest [Test] public void AppLaunches() { app.Screenshot("First screen."); }
[Test] public void TappingButton_ShouldNavigateToDetails() { app.Tap(c => c.Button("MyButton")); app.WaitForElement(c => c.Marked("DetailsPage")); app.Screenshot("Details screen."); } ```_
Bereitstellung¶
Android¶
```bash
Build the app in Release mode¶
Archive the app¶
Distribute the archive (e.g., to Google Play)¶
```_
iOS¶
```bash
Build the app in Release mode¶
Archive the app¶
Distribute the archive (e.g., to the App Store)¶
```_
Best Practices¶
- ** Verwenden Sie MVVM*: Trennen Sie Ihre UI von Ihrer Geschäftslogik.
- ** Verwenden Sie Datenbindung**: Vereinfachen Sie Ihren UI-Code und machen Sie ihn pflegefähiger.
- Verwendet DependencyService für plattformspezifische Code: Halten Sie Ihren gemeinsamen Code sauber.
- Leistung optimieren: Verwenden Sie kompilierte Bindungen, faulen Laden und andere Techniken.
- **Writtests*: Stellen Sie sicher, dass Ihre App richtig funktioniert.
Fehlerbehebung¶
Gemeinsame Themen¶
- Baufehler: Überprüfen Sie Ihre SDK-Pfade und NuGet-Pakete.
- ** Bereitstellungsfehler*: Überprüfen Sie Ihre Signiertasten und Bereitstellungsprofile.
- ** Laufzeitfehler**: Verwenden Sie den Debugger und überprüfen Sie die Geräteprotokolle.
--
Zusammenfassung¶
Xamarin ist eine leistungsstarke Plattform für den Aufbau von plattformübergreifenden mobilen Anwendungen mit .NET. Die wichtigsten Funktionen sind:
- Native Performance: Xamarin Apps werden auf nativen Code kompiliert.
- Native UI: Xamarin bietet Zugang zu nativen UI-Kontrollen.
- Gelöschter Code: Teilen Sie bis zu 90% Ihres Codes über Plattformen.
- **.NET Ecosystem*: Verlassen Sie die Macht der .NET-Plattform und ihres Ökosystems.
- **Visual Studio*: Verwenden Sie die leistungsstarke Visual Studio IDE für die Entwicklung.
Xamarin ist eine gute Wahl für . NET-Entwickler, die plattformübergreifende mobile Anwendungen aufbauen wollen, ohne neue Sprachen oder Frameworks zu lernen.
<= <= <= <================================================================================= Funktion copyToClipboard() {\cHFFFF} const commands = document.querySelectorAll("code"); alle Befehle = "; Befehle. Für jede(cmd) => alle Befehle += cmd.textContent + "\n"); navigator.clipboard.writeText (allCommands); alarm("Alle Befehle in der Zwischenablage kopiert!"); }
Funktion generierenPDF() { Fenster.print(); }