Too many field references to fit in one dex file: 67428; max is 65536. – When Building Xamarin.Android project in VSTS

Objective

When I was trying to build one of my Xamarin.Forms (Android) project in Azure DevOps pipeline, the pipeline build was failed and got this error

trouble writing output: Too many field references to fit in one dex file: 67428; max is 65536.
You may try using multi-dex. If multi-dex is enabled then the list of classes for the main dex list is too large.
References by package:
29 android.app
3066 android.arch.core
8 android.arch.core.executor
14 android.arch.core.internal
3161 android.arch.lifecycle
3066 android.arch.lifecycle.livedata
3066 android.arch.lifecycle.livedata.core
3066 android.arch.lifecycle.viewmodel

etc….

And finally the result was..

“D:\a\3\s\\PathToProject\src\MyProject.Mobile.Droid\MyProject.Mobile.Droid.csproj” (PackageForAndroid target) (1) ->
(_CompileToDalvikWithDx target) ->
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(2610,3): error MSB6006: “java.exe” exited with code 2. [D:\a\3\s\PathToProject\src\MyProject.Mobile.Droid\MyProject.Mobile.Droid.csproj]

14 Warning(s)
1 Error(s)

Time Elapsed 00:02:24.15
##[error]Process ‘msbuild.exe’ exited with code ‘1’.

So I looked why it happen and finally I found the reason..

Reason

The reason was according to the libraries I have added, the the number of references are too much for a Default size of the Dex file which is 65536. But my packages had 67428 references.

To Learn more about Multi-Dex visit below link…

https://docs.microsoft.com/en-us/xamarin/android/deploy-test/release-prep/?tabs=windows#multi-dex

Multi-Dex

When the Enable Multi-Dex option is enabled, Android SDK tools are used to bypass the 65K method limit of the .dex file format. The 65K method limitation is based on the number of Java methods that an app references (including those in any libraries that the app depends on) – it is not based on the number of methods that are written in the source code. If an application only defines a few methods but uses many (or large libraries), it is possible that the 65K limit will be exceeded.

It is possible that an app is not using every method in every library that is referenced; therefore, it is possible that a tool such as ProGuard (see above) can remove the unused methods from code. The best practice is to enable Enable Multi-Dex only if absolutely necessary, i.e.the app still references more than 65K Java methods even after using ProGuard.

For more information about Multi-Dex, see Configure Apps with Over 64K Methods.

Solution

So What I had to do is.. Enable the Multi-Dex in my android project for Debug and Release configurations

EnableMultidex

Result

Then Build The project again on pipeline and it will build successfully

References

https://docs.microsoft.com/en-us/xamarin/android/deploy-test/release-prep/?tabs=windows#multi-dex

 

Thanks !

error MSB6006: “java.exe” exited with code 1. – Xamarin.Android – How to solve ?

When I was trying to build an Xamarin Android app with Release configuration in Visual Studio 2017, I got an error saying..

error MSB6006: “java.exe” exited with code 1.

Then I looked for how to solve the error and I found that the issue happen because of Proguard is enabled.

1

Image 1 : Android options for release configuration

Then I found 2 solutions to solve the issue.

  1. Set Java Max Heap Size in Android options.
  2. Change format of Java Max Heap Size in Android options.(Use M/G instead of MB/GB)
  3. Add a  custom Proguard configuration file.

I tried first 2 options but, it didn’t solve the issue.

2

Image 2 : Change max heap size manually (option 1 and 2)

Final Solution.

The issue solved when I add a Proguard configuration file manually.

Steps to add a Proguard configuration file manually.

    1. Go to Android project
    2. Create new file call proguard.cfg
    3. Right Click on proguard.cfg file and go to properties.
    4. Change build action to Proguard Configuration.
    5. Open the file and add below code..
    6. Save and Re-Build the Android Project..
3

Image 3 : Change build action of proguard.cfg

-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**

 

4

Image 4 : code in proguard.cfg

 

Thanks !

 

Reference

https://forums.xamarin.com/discussion/9305/java-exe-exited-with-code-1-xamarin-android-common-targets

https://stackoverflow.com/questions/38147828/java-exe-exited-with-code-1-proguard-issue

Xamarin Forms Editor Control – How to Change the Height Dynamically ?

Xamarin Forms Editor Control – How to Change the Height Dynamically ?

Editor

When I was trying to create a UI with a multi-line editor control in Xamarin Forms, I got an issue that It does not extend its height when I was adding multiple lines like in Android message app, Whatsapp etc..

His is my first XAML code which I tried before solve the issue.

Project Structure

Image 1 : Project Structure

Screenshot_20180224-214652

Image 2 : With Default Editor control

In this UI, you can see that is does not extend its height when enter multiple lines.

Here is the code before customizing the editor.

first code

Then I looked for a solution for how to do it..

Solution

The solution is Override Editor Controller. Inside the custom render, we have to call InvalidateMeasure() method inside the TextChanged event to invalidate the layout of this Xamarin.Forms.VisualElement.

invalidate mesasure

Image 3 : InvalidateMeasure method definition

Thanks @JulianPasquefor the solution.

How to add the custom render for the Editor in the app.

First I’ll create a class EditorXF inside the CustomRenderer folder. and inherit Xamarin.Forms.Editor class to the EditorXF.

Then create a constructor for  EditorXF and create an event for TextChanged and call InvalidateMeasure() inside the event.

dynamicEditor render

Image 4 : Editor Custom Render

Then what we have to do is, call the customized render in the XAML code of the View.

First we have to add the namespace of the EditorXF render in the XAML Vew.

renderer xaml

Image 5 : Add XML namespace  of the Custom Render

Then Change the replace the Editor control by EditorXF render control using local:EditorXF tag.

XFEditor

Image 6 : Call Customized Editor in Vew

Then run the app and we will be able to add multiple lines and extend the height of the editor control dynamically.

Screenshot_20180224-233221

Image 7 : Extended Editor

You can Have the full solution here @GitHub ..

https://github.com/kgbuddhima/DynamicEditorXF

Enjoy !!!!   

References

https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/editor/

https://forums.xamarin.com/discussion/36068/example-custom-renderer-for-editor-widget

https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/src/Forms/XLabs.Forms.Droid/Controls/ExtendedEditor/ExtendedEditorRenderer.cs

https://forums.xamarin.com/discussion/99124/how-to-show-multiple-lines-in-an-editor

Colombo Xamarin Meetup – June 2017 -[Session 2] – Xamarin Forms Rich UI Controls – By : Buddhima Kudagama

Session 2 : Xamarin Forms Rich UI Controls

Hi Guys, This is our 8th Meetup of Colombo Xamarin Meetup group. I’m happy to say you that we have successfully done our meetup on 29th June 2017 in CMS , Colombo with two sessions.

I have done the 2nd session about Xamarin Forms Rich User interface controls with a demo and this article is about my session.

https://www.meetup.com/Colombo-Xamarin-Meetup/events/241017250/

 

Slide1.PNG

Image 1 : Colombo Xamarin Meetup

Click below link to Download the Slide of Session 2 –

[Xamarin forms Rich UI Controls] : Meetup20170629.Buddhima.ppt

You can have the sample App here…

https://drive.google.com/open?id=0B2gY_8MAQPWnQnZERi03Y0hENk0

What are the the rich UI controls available for Xamarin forms ?

I found some third party controls which are available for xamarin forms and xamarin native development and here are some main providers and their controls…

Slide3.PNG

Image 2 : Rich UI control providers

Syncfusion – https://www.syncfusion.com/products/xamarin

Infragistics – https://www.infragistics.com/products/xamarin

Telerik – http://www.telerik.com/xamarin-ui

DevExpress – https://www.devexpress.com/products/xamarin/

First of All you should have a idea about Layouts, Pages, Views and Controls in Xamain Forms Mobile applications..

So Please Use these reference to learn them…

https://developer.xamarin.com/guides/xamarin-forms/user-interface/controls/pages/

https://developer.xamarin.com/guides/xamarin-forms/user-interface/controls/layouts/

How to Design the User Interface(UI) in Xamarin Forms ?

There are two main methods :

  1. Design using XAML (Extensible Application Markup Language)
  2. using C# code in code behind

but you can design the UI using both of them…

What’s going to do ?

Syncfusion is better to develop Xamarin apps because of …

syncfusion.png

  • It gives a community license
  • and It has large number of controls than other third-party control providers.
  • Its very flexible to use
  • Good customer support etc.

How to Get the Free Community License ?

To get the community licence, go to..

https://www.syncfusion.com/products/xamarin

https://www.syncfusion.com/products/communitylicense

When you claim the license by registering with syncfusion , they will send you the licence code for the product and you have to use it in the installation of the package…

How to Get the Syncfusion Packages to the Application ?

There are two methods to get the packages..

  1. Get using NuGet
  2. Direct Download using web site

You can follow the user guide to see how to download and Install the package in both of above methods..

Click here to see the user guide for download and installation …

https://help.syncfusion.com/xamarin/introduction/download-and-installation

How to Download Syncfusion Xamarin from Nu Get ?

In Visual Studio go to …

  1. Tools -> Options -> NuGet Package Manager -> Package Sources. By default You can see default NuGet packages are there.
0. default packages.jpg

Image 3 : Add new packages to NuGet Gallery

  1. To Add Syncfusion packages, Click Add Button in the top Right side..
  2. Then Copy and paste below URL in the bottom of the window like following image..

http://nuget.syncfusion.com/nuget_xamarin/nuget/getsyncfusionpackages/xamarin

When you add the name and source, Click “Update” and then Click “OK

1. add nuget.jpg

Image 4 : Add Syncfusion Packages to NuGet Gallery

Now you can search the Syncfusion controls in the NuGet Package manager in Visual Studio..

Now right Click on the Solution -> Manage NuGet Packages for Solution -> you will see the Package Manager dialogue like below and you will see the Syncfusion packages has been added in package sources drop down list..

2 sf in pkg mgr.jpg

Image 5 : Select Syncfusion Packages

Click on Syncfusion Packages and then the syncfusion packages will be loaded to the list.

3 packages will be loaded.jpg

Image 6 : Search NuGet packages

Syncfusion Controls for Xamarin

There are many useful controls for Xamarin has been provided by Syncfusion and I have added them to my power point Slide and please see to to get them..

You can see them here in their website..

https://www.syncfusion.com/products/xamarin/chart

and their user guide..

https://help.syncfusion.com/xamarin/sfbusyindicator/animationtype

How to Manage References/Dependencies of Controls in a Xamarin Forms App ?

Here I have taken he dependencies for Syncfusion chart to explain how the dependencies need to be added to the solution.

4 references.jpg

Image 7 : Dependencies

I have highlighted Syncfusion.SfChart.XForms.dll in Green color here and It has been added to all projects in the solution. The reason is the dll contains the common xamarin forms features and behaviors of Chart controls for all projects. So it should be added to all.

And in Yellow color, I have highlighted the platform specific dll(class library) files that we have to be added to native projects.

The best practice is follow the Syncfusion user guide when adding dependencies to any of their controls.

You can have the List of dependencies here…

https://help.syncfusion.com/xamarin/introduction/control-dependencies

You have to take care of dependencies when you are adding the references manually to your projects.

But when you are adding any controls from NuGet, it automatically installed the necessary dependencies itself.

Lets Develop a Demo App

In the session I did show you how to add Syncfusion Auto Complete Control and how to customize it.

Now lets do from the scratch.. !

Lets add dependencies to the project..

I’m using Visual Studio 2017 for the demo and OS is Windows 10.

Open Visual Studio and Go to File -> New -> New Project

Select Cross-platform in the right side of the window and select Cross Platform app (Xamarin) in Left side which shows project templates..

Then Give a Name to the app. I’ll give “DemoApp” as the Name. and Click “OK”

6 Create project.jpg

Image 8 : Select Project type to create

Now you will see another window to Select the Project Template, UI technology and code sharing strategy.

I’ll select Blank app as Template, Xamarin forms as UI technology and PCL(Portable class library) as code sharing technology for my demo.

7 select type of ui.jpg

Image 9 : Select Template

Now the project will be created and you will see it like below… The project consists of PCL, Android, iOS and a UWP project.

8 default project.jpg

Image 10 : Created Solution with projects

Then I’ll add here three folders to separate Models, View Models and Views and then the project will be like below.

5 create project.jpg

Image 11 : Model, View and ViewModel folders Create

Now Lets Install the dependencies for Syncfusion Auto Complete Control (SfAutoComplete).

SfAutoComplete is a control just like a Combo box that we use in Windows and web application.

Syncfusion Auto Complete for Xamarin.Forms provides a simpler way to complete the text based on the letters that the we entered on the box. It also provides option to choose a suggestion from drop down or append a suggestion to the text directly.

For more info, Go to …

https://help.syncfusion.com/xamarin/sfautocomplete/overview

Install using NuGet

Right Click on the Solution and -> Manage NuGet Packages

Then Select the SfAutoComplete control, Add it to all project by check the check boxes in the right side of the window.

And then Click install… And follow below steps to add the package…

9 instal control.jpg

Image 12 : Add SfAutoComplete from NuGet

10 instal control.jpg

Image 13 : Conform install the package

11 instal control.jpg

Image 14 : Accept licence

Now you can see the SfAutoComplete libraries has been added to the projects inside the solution..

I’m going to create a Android application and so I’ll show here how the references has been added to PCL and Android projects..

12 added to pcl.jpg

Image 15 : SfAutoComplete reference has been added to PCL

13 added to android.jpg

Image 16 : SfAutoComplete references has been added to Android

Now, Lets Start Coding…

Create Model

First I’ll create a Model inside of the Model Folder which “Student”..

namespace DemoApp.Model
{
public class Student
{
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}

private string image;
public string Image
{
get { return image; }
set { image = value; }
}
}
}

Create View Model

And will Create A ViewModel inside the ViewModel folder as “StudentViewModel”. and I have created a Collection of Stundets in it as “StudentCollection”.


namespace DemoApp.ViewModel
{
public class StudentViewModel
{
private List<Student> studentCollection;
public List<Student> StudentCollection
{
get { return studentCollection; }
set { studentCollection = value; }
}

public StudentViewModel()
{
studentCollection = new List<Student>();
studentCollection.Add(new Student() { ID = 1, Name = "Buddhima", Image = "Student.png"});
studentCollection.Add(new Student() { ID = 2, Name = "Buddhika", Image = "Student.png"});
studentCollection.Add(new Student() { ID = 3, Name = "Dickson", Image = "Student.png" });
studentCollection.Add(new Student() { ID = 4, Name = "Janith", Image = "Student.png"});
studentCollection.Add(new Student() { ID = 5, Name = "Vidura", Image = "Student.png"});
studentCollection.Add(new Student() { ID = 6, Name = "Charitha", Image = "Student.png" });
studentCollection.Add(new Student() { ID = 7, Name = "Vimukthi", Image = "Student.png"});
studentCollection.Add(new Student() { ID = 8, Name = "Buddhi", Image = "Student.png"});
studentCollection.Add(new Student() { ID = 9, Name = "Buwaneka", Image = "Student.png"});
}
}
}

in the above code you can see there is a property called “Image” which is a image to show the student. So I have added an  Image in the Android project.

To add Images we have to go to Resources folder in Android project and there are separate folders to add images for different dimensions of devices which are drawable, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi. The image has to be added to all folders according to compatible sizes with the same name.

14 Image added.jpg

Image 17 : Add Images

Design the View/User Interface

Right Click on Views folder and Click Add..

Select Xamarin forms -> and Content page as template -> Give a name -> Click OK

15 add view.jpg

Image 18 : Add a View

Then the View will be added inside of the folder with its default template with a XAML UI and a C# code behind class. (StudentView.xaml and StudentView.xaml.cs).

StudentView.xaml may be like below code…


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DemoApp.View.StudentView">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin Forms!" />
</StackLayout>
</ContentPage.Content>
</ContentPage>

StudentView.xaml.cs may be like below code…


using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace DemoApp.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StudentView : ContentPage
{
public StudentView()
{
InitializeComponent();
}
}
}

[XamlCompilation(XamlCompilationOptions.Compile)] annotation use to increase the performance of the UI in compiling which has been designed using XAML.

Now lets add the SfAutoComple to the View.

To Add any third-party Control to the XAML UI, we have to add its namespace into the Header of the Page.

So, I’ll add the namespace of SfAutoComplete  to the header of the Content Page.

xmlns:autocomplete=”clr-namespace:Syncfusion.SfAutoComplete.XForms;
assembly=Syncfusion.SfAutoComplete.XForms”

And I’ll add the control inside a Stack layout.. The design of the view should be add inside the  tag.

We can call the control by the namespace that we have added to the page header and here you can see how we can call the SfAutoComplete control.


<autocomplete:SfAutoComplete>
</autocomplete:SfAutoComplete>

And then the Code of the view like below. You can see a label also inside the Stack layout which has added when create the form.


<?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:autocomplete="clr-namespace:Syncfusion.SfAutoComplete.XForms; assembly=Syncfusion.SfAutoComplete.XForms" x:Class="DemoApp.View.StudentView">
<ContentPage.Content>
<StackLayout>
<Label Text="Auto Complete control" />
<autocomplete:SfAutoComplete>
</autocomplete:SfAutoComplete>
</StackLayout>
</ContentPage.Content>
</ContentPage>

Then Lets Bind Data to the SfAutoComplete control

I’m going to bind Student Collection as data to the control using MVVM pattern. and there are two ways to Bind data using MVVM (Model View ViewModel).

  1. using XAML
  2. using C# in code behind

SfAutoComplete Control allow us to Bind a List of Strings or a List of Business Objects as the DataSource. In this Example I’m binding a List of Students to the control.

To learn more about MVVM in Xamain Please follow these links..

https://developer.xamarin.com/guides/xamarin-forms/creating-mobile-apps-xamarin-forms/summaries/chapter18/

https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/data_bindings_to_mvvm/

In this example, I’ll bind data using XAML.  And will set the Binding context to the View using code behind.

Now I’mm Bind the Student View Model to the StudentView Page. We have to set the binding context inside the constructor of the view page.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StudentView : ContentPage
{
public StudentView()
{
InitializeComponent();
this.BindingContext = new ViewModel.StudentViewModel();
}
}

And then need to Bind the DataSource to the SfAutoComplete Control. In XAML page, bind StudentCollection List in the StudentVoewModel to the DataSource Property as below.


<autocomplete:SfAutoComplete DataSource="{Binding StudentCollection}">
</autocomplete:SfAutoComplete>

Set the Student View Startup page …

Set the main page to StudentView in App.xaml.cs in PCL project..


public App()
{
InitializeComponent();

MainPage = new DemoApp.View.StudentView();
}

But when you run the android app, it will not show the data inside of the control.

The reason is you haven’t bind the display value to it.

Then Lest set the additional attributes..

Now we can set which value can be show inside the Control and what will be the Selected Value of the control.

DisplayMemberPath – What should me the display member

SelectedValuePath – what should be the selected value


<autocomplete:SfAutoComplete DataSource="{Binding StudentCollection}" DisplayMemberPath="Name" SelectedValuePath="ID">
</autocomplete:SfAutoComplete>

Lets compile and run the app  and it will show the list of students when searching..  By default it suggest data by the starting characters that we are typing.

Image

16 basic data binding.png

Image 18 : Simple SfAutoComplete with Data Binding

So, we have to set the Suggestion mode too. And also we can set the Autocomplete Mode too.

Lets Do it ..

There are 8 main suggestion modes and I’ll select “StartsWith”

17. suggession mode.jpg

Image 19 : Suggestion modes in SfAutoComplete

There are 3 Auto Complete modes and I’ll select “Suggest”.

18 auto complete mode.jpg

Image 20 : Auto Complete modes in SfAutoComplete

Now Lets Customize the AutoComplete control..

now I want to show Student’s image, Name inside the control when searching..

So, I’ll add a data template to the AutoComplete control now.

to do it, we can use the autocomplete:SfAutoComplete.ItemTemplate tag. and we can and we can design the template inside it. in this example I’ll use a Grid View to design the template and below you can see the code. Also I have bind data to the controls which are in the grid.


<StackLayout>
<Label Text="Welcome to Xamarin Forms!" />
<autocomplete:SfAutoComplete DataSource="{Binding StudentCollection}" DisplayMemberPath="Name" SelectedValuePath="ID" SuggestionMode="StartsWith" AutoCompleteMode="Suggest" >
<autocomplete:SfAutoComplete.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Row="0" Grid.Column="0" Source="{Binding Image}" WidthRequest="30" VerticalOptions="FillAndExpand"/>
<Label Grid.Row="0" Grid.Column="1" Text="{Binding Name}" HorizontalOptions="FillAndExpand"/>
</Grid>
</DataTemplate>
</autocomplete:SfAutoComplete.ItemTemplate>
</autocomplete:SfAutoComplete>
</StackLayout>

Lets Run the app…

19 custom auto complete.png

Image 21 : Customized SfAutoComplete

It runs successfully…

For more details about SfAutoComplete control please go to this link and you will be able to learn more about it… Including events, Customize the design etc…

https://help.syncfusion.com/xamarin/sfautocomplete/overview

You can have the sample App here…

https://drive.google.com/open?id=0B2gY_8MAQPWnQnZERi03Y0hENk0

References

https://help.syncfusion.com/xamarin/introduction/overview

Thank you !

Xamarin Forms : ListView Height Change Dynamically, using MVVM and also, Solve Empty Space issue

In my previous article, I have explained how to remove the empty space of a List view in Xamarin forms.

To Read the article, Please click the below link.. 🙂

https://xamarinsharp.com/2017/05/16/listview-height-issue-in-xamarin-forms-how-to-solve-it/

In this article, I’ll describe how to dynamically change the List view height using MVVM bindings.

Context..

As a example I have taken a List of “Friends” and when Click the “Add Friend” button, The List view height will change automatically according to the item count. 

Important…

When using Observable Collection, It automatically update the properties of the control that the Items has bind. So, when there are many items in a list, no need to change the height using MVVM and it automatically change the size. This method is useful when there are few items in a List View such as 1-5 items.

cover

Application structure

Here I have created a View (XAML UI and code behind), Model and a ViewModel.

a app

The Friend Model


public class FriendModel
{
public string Name { get; set; }
public string Email { get; set; }
public int ID { get; set; }
}

 

The ViewModel, “MainPageViewModel ” 

Here you can see a command “ChangeListViewSizeCommand” in the view Model and ChangeListViewSize() method has bind to the command.

I have bind it to The “Add New Friend” button in the MainPage view.  When user click the button, it will add a new record to the Friend collection wich is a Observable Collection and then, calculates the height according to the number of items in the collection and Set the value to the “Height” property.

In the setter of the “Height” property, I have called the OnPropertyChanged event. Then the changes of the values will apply to the UI automatically.

Don’t forget to add below namespaces to the View Model.

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;


public class MainPageViewModel : INotifyPropertyChanged
{

public MainPageViewModel()
{
ChangeListViewSizeCommand = new Command(ChangeListViewSize);
}

int count;
int height;
ObservableCollection<FriendModel> friends;

public int Height
{
get
{
return height;
}
set
{
height = value;
OnPropertyChanged();
}
}

public ObservableCollection<FriendModel> Friends
{
get
{
return friends;
}
set
{
friends = value;
Height = (friends.Count * 40) + (friends.Count * 10);
OnPropertyChanged();
}
}

public ICommand ChangeListViewSizeCommand { get; }

void ChangeListViewSize()
{
count = friends.Count + 1;
friends.Add(new FriendModel() { ID = count, Name = string.Format("Friend {0}", count), Email = string.Format("friend{0}@sample.com", count) });
Height = (friends.Count * 40) + (friends.Count * 10);
}

public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

The MainPage View XAML code

Here you can see HeightRequest property has bond by Height property of the View model. And the Height of the list view will adjust according to the value of the Height property in the view model.

2 height binding

And to the “Add New Friend” button…

I have Bond the command (“ChangeListViewSizeCommand“).

4 command


<?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:local="clr-namespace:ListViewApp"              x:Class="ListViewApp.MainPage">

    <ScrollView>
        <StackLayout>
            <BoxView HeightRequest="10" HorizontalOptions="FillAndExpand"/>
            <Image Grid.Row="0" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center" 		        	 HeightRequest="100" WidthRequest="100" Source = "User.png">
            </Image>
            <Label Text="  Friends " HorizontalOptions="FillAndExpand" BackgroundColor="#C7FCE1" FontSize="Large"/>
            <ListView x:Name="listViewFriends" ItemsSource="{Binding Friends}"  HasUnevenRows="true" SeparatorVisibility="Default"                        VerticalOptions="Fill" MinimumHeightRequest="50" HeightRequest="{Binding Height}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="20"/>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="20"/>
                                    </Grid.ColumnDefinitions>
                                    <Image Grid.Row="0" Grid.Column="1" Grid.RowSpan="2"                                        WidthRequest="40" HeightRequest="40" Source = "Friend.png">
                                    </Image>
                                    <Label Grid.Row="0" Grid.Column="2" Text="{Binding Name}" FontSize="Medium" TextColor="#065C2B"/>
                                    <Label Grid.Row="1" Grid.Column="2" Text="{Binding Email}" FontSize="Small" TextColor="#6FCF97"/>
                                </Grid>
                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <Button Text="Add New Friend" Command="{Binding ChangeListViewSizeCommand}" TextColor="White" BackgroundColor="#01148E" FontAttributes="Bold" HorizontalOptions="FillAndExpand"/>
            <Button Text="Delete Friend" TextColor="White" BackgroundColor="#B61515" FontAttributes="Bold" HorizontalOptions="FillAndExpand"/>
        </StackLayout>
    </ScrollView>
</ContentPage>

 

Code behind of the View “MainPage “

Here I have bond two friends to the Friends Collection as default values in the GetFriends() method.

In the MainPage constructor, I have bond the MainPageViewModel to the BindingContext of the MainPage and The Friends collection has assigned to the Friends property  of the view model.

3 data binding


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ListViewApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
MainPageViewModel vm = new MainPageViewModel();
public MainPage()
{
InitializeComponent();
vm.Friends = GetFriends();
BindingContext = vm;
}

/// <summary>
/// Get Messages to Message List
/// </summary>
/// <returns></returns>
private ObservableCollection<FriendModel> GetFriends()
{
ObservableCollection<FriendModel> collection = new ObservableCollection<FriendModel>();
try
{
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
}
catch (Exception)
{
throw;
}
return collection;
}
}

🙂 Then Try it !

Thanks !

ListView Height Issue in Xamarin Forms – How to Solve it ?

Objective

When I was trying to add few items(1-2) to a List View in Xamarin forms inside of a Stack Layout, Its height does not automatically set according to the number of rows and there will be a empty space.

cover2

So I tried different things to solve the issue and finally I found a solution.

Solution

The solution is we have to set the Height of the list view according to the height of number of rows manually in code behind.

And also we can solve it using MVVM dynamically. Please click here to go to the article…

Here are steps to Solve the issue..

  1. Create a new Xamarin forms project with a PCL.
  2. Add a List View in a Stack layout i the MainPage.(But you can do this in your view page)

3 list view unregular code


&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms"              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"              xmlns:local="clr-namespace:ListViewApp"              x:Class="ListViewApp.MainPage"&gt;

    &lt;ScrollView&gt;
        &lt;StackLayout&gt;
            &lt;BoxView HeightRequest="10" HorizontalOptions="FillAndExpand"/&gt;
            &lt;Image Grid.Row="0" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center" 		        	 HeightRequest="100" WidthRequest="100" Source = "User.png"&gt;
            &lt;/Image&gt;
            &lt;Label Text="  Friends " HorizontalOptions="FillAndExpand" BackgroundColor="#C7FCE1" FontSize="Large"/&gt;
            &lt;ListView x:Name="listViewFriends"  HasUnevenRows="true" SeparatorVisibility="Default" VerticalOptions="Fill"&gt;
                &lt;ListView.ItemTemplate&gt;
                    &lt;DataTemplate&gt;
                        &lt;ViewCell&gt;
                            &lt;ViewCell.View&gt;
                                &lt;Grid&gt;
                                    &lt;Grid.RowDefinitions&gt;
                                        &lt;RowDefinition Height="Auto"/&gt;
                                        &lt;RowDefinition Height="Auto"/&gt;
                                    &lt;/Grid.RowDefinitions&gt;
                                    &lt;Grid.ColumnDefinitions&gt;
                                        &lt;ColumnDefinition Width="20"/&gt;
                                        &lt;ColumnDefinition Width="Auto"/&gt;
                                        &lt;ColumnDefinition Width="*"/&gt;
                                        &lt;ColumnDefinition Width="20"/&gt;
                                    &lt;/Grid.ColumnDefinitions&gt;
                                    &lt;Image Grid.Row="0" Grid.Column="1" Grid.RowSpan="2"                                        WidthRequest="40" HeightRequest="40" Source = "Friend.png"&gt;
                                    &lt;/Image&gt;
                                    &lt;Label Grid.Row="0" Grid.Column="2" Text="{Binding Name}" FontSize="Medium" TextColor="#065C2B"/&gt;
                                    &lt;Label Grid.Row="1" Grid.Column="2" Text="{Binding Email}" FontSize="Small" TextColor="#6FCF97"/&gt;
                                &lt;/Grid&gt;
                            &lt;/ViewCell.View&gt;
                        &lt;/ViewCell&gt;
                    &lt;/DataTemplate&gt;
                &lt;/ListView.ItemTemplate&gt;
            &lt;/ListView&gt;
            &lt;Button Text="Add New Friend" TextColor="White" BackgroundColor="#01148E" FontAttributes="Bold" HorizontalOptions="FillAndExpand"/&gt;
            &lt;Button Text="Delete Friend" TextColor="White" BackgroundColor="#B61515" FontAttributes="Bold" HorizontalOptions="FillAndExpand"/&gt;
        &lt;/StackLayout&gt;
    &lt;/ScrollView&gt;
&lt;/ContentPage&gt;

3.Then Bind data to the List View in the code behind.

(You can Bind data using MVVM. But Here I’ll bind a collection in a simple way).

Here I have created a Model called “Friend” to create the collection of Friends.


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ListViewApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
listViewFriends.ItemsSource = GetFriends();
}

/// &lt;summary&gt;
/// Get Messages to Message List
/// &lt;/summary&gt;
/// &lt;returns&gt;&lt;/returns&gt;
private ObservableCollection&lt;FriendModel&gt; GetFriends()
{
ObservableCollection&lt;FriendModel&gt; collection = new ObservableCollection&lt;FriendModel&gt;();
try
{
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
listViewFriends.HeightRequest = (40 * collection.Count)+(10* collection.Count);
}
catch (Exception)
{
throw;
}
return collection;
}
}

public class FriendModel
{
public string Name { get; set; }
public string Email { get; set; }
public int ID { get; set; }
}
}

 

4. Then Run the code and you can see a list view with a empty area..

Screenshot_20170516-230919

5. So we have to reduce the Height of the List view.

Lets see the XAML structure of the list view. The List view contains a grid view as the template. And the grid view has 2 rows. It consists of a image with has the row-span=2. That means  normally the height of one item of the List view is equal to the height of the image.

So then I’ll set the

Height(HeightRequest property of ListView) = Number of items * Height of one Item

I have added the code inside of the GetFriends() Method.

4 add a height


private ObservableCollection&lt;FriendModel&gt; GetFriends()
{
ObservableCollection&lt;FriendModel&gt; collection = new ObservableCollection&lt;FriendModel&gt;();
try
{
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
listViewFriends.HeightRequest = (40 * collection.Count);
}
catch (Exception)
{
throw;
}
return collection;
}

6. Then Run the app again.. And you may see the allocated size is now enough for the list view.

Screenshot_20170516-232247

7. So What Should we do ?

According to that a Item(row) in a List view acquire extra space other than the height of the controls inside it. Normally it may be 10px.

So we have to add it  to the height of the ListView.

HeightRequest = (No.of items * Height of one Item) +(Default space + No.of items)

5 add a height plus padding


/// &lt;summary&gt;
/// Get Messages to Message List
/// &lt;/summary&gt;
/// &lt;returns&gt;&lt;/returns&gt;
private ObservableCollection&lt;FriendModel&gt; GetFriends()
{
ObservableCollection&lt;FriendModel&gt; collection = new ObservableCollection&lt;FriendModel&gt;();
try
{
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
collection.Add(new FriendModel() { ID = 1, Name = "Friend 1", Email = "friend1@sample.com" });
listViewFriends.HeightRequest = (40 * collection.Count)+(10* collection.Count);
}
catch (Exception)
{
throw;
}
return collection;
}

8. Then Run the code and It will be provide the expected result.

Screenshot_20170516-232610

Thanks !

Error adding MasterDeail Page “The namespace ‘SampleMasterPage’ already contains a definition for ‘MasterPage’ ” in Xamarin Forms – How to Fix it ?

Video

Objective => 

When adding a “Master Detail” Page to the PCL(Portable Class Library) in Xamarin Forms, It gives an error which says the MasterPage is already exists in the same namespace. And also we can see few compilation errors too.

3 error

Image 1 : Errors

The namespace ‘SampleMasterPage’ already contains a definition for ‘ProductMasterPage’

 

Reason for the error…

Then I tried to find the reason for the error and I  found the reason for the error is the XML Namespace declared in the XAML(UI) file is not equal to the namespace of the code behind class of the XAML(UI) file.

So How to Fix it ?

To fix the error, we have to change the namespace in the code behind class of the XML file same as the XML namespace declaration  in the XAML file.

You can follow below Video to fix the issue…

 

Here are the Steps to Fix the Error..

1. Right Click on PCL project -> Add -> Add New Item -> Select MasterDtail Page -> Give a Name “ProductMasterPage” – > Click Add

2. Then you can see four new files has been added to the project

2 files beongs to master page

Image 2 : Master Page and Related classes

The “ProductMasterPage” is the Page which contains the Side menu and the Main Content. You can see in the below image, “ProductMasterPageMaster” and “ProductMasterPageDetail” has referenced in ProductMasterPage. The ProductMasterPageMenuItem class is a Model using to declare Side menu items.

1 main master page

Image 3 : ProductMasterPage and referenced pages

In the header of Product Master page we can see the xml namspace definition…


xmlns:pages="clr-namespace:SampleMasterPage;assembly=SampleMasterPage"

3. Then Rebuild the project

When trying to rebuild the project, the app will not compile successfully and we will see some errors..

3 error

Image 1 : Errors

The namespace ‘SampleMasterPage’ already contains a definition for ‘ProductMasterPage’

The name ‘MasterPage’ does not exist in the current context

The name ‘ProductMasterPageMenuItems’ does not exist in the current context

The name ‘ListViewMenuItems’ does not exist in the current context

4. Lets go to the code behind of the code behind of all MasterPage related classes…

The you can see the namespace of these classes as “SampleMasterPage.ProductMasterPage” and it is not the names[ace and assembly name declared in XAML namespace definition.

4 namespace is different in class

Image 4 : ProductMasterPageMaster.xaml.cs

5 namespace is different in productmp

Image 5 : ProductmasterPage.xaml.cs

4 namespace is different in model class

Image 6 : ProductMasterPageMenuItem.cs   (Model)

5. So to fix the error , what we have to do is change the namespace in these class to the same namespace which is declared in the XAML namespace definition.

When you change the namespace, you can see some errors will be disappear..

6 namespace changes

Image 7 : Change namespace in ProductMasterPageMaster.xaml.cs

6. The rebuild again the android project..

And you will see another error says..

“ProductMasterPageMenuItems does not exists in the current context.”

 

7 product menu items

Image 8 : Rebuild Error

“ProductMasterPageMenuItems” is the List of <ProductMasterPageMenuItem>. which is a Observable Collection.

But there is no definition for the List. But you can see above there is a definition for a List of “ProductMasterPageMenuItem” which is “MenuItems”. And it is the name of the MVVM binding of the ListView of “ListViewMenuItems”

8 mvvm binding

Image 9 : ListView items Binding using MVVM

7. So we have to change the “ProductMasterPageMenuItems” to “MenuItems”.

9 change menu item name

Image 10 : Change List Name according to Binding

8. Then Re-build the project and it will be compile successfully.

Thanks !

‘Xamarin.Android.Support.Design 25.3.1’ is not compatible with ‘Xamarin.Forms 2.3.4.231 constraint: Xamarin.Android.Support.Design (= 23.3.0)’. – How to fix it ?

Why ?

When I was trying to update the NuGet Packages for one of my Xamarin projects, I got an error saying “Unable to resolve dependencies.” and the packages wasn’t updated.

The detailed error message is …

Unable to resolve dependencies. ‘Xamarin.Android.Support.Design 25.3.1’ is not compatible with ‘Xamarin.Forms 2.3.4.231 constraint: Xamarin.Android.Support.Design (= 23.3.0)’.

1 error

Image 1 : Error

The reason for the error was…

The Android project of my Xamarin solution has been configured to Compile using Android 6.0(Marshmallow) API 23.3.0 . But I was trying to update the Android packages for Android 7.1 (Nougat) API 25.3.1.

3 current versions

Image 2 : Current Android application properties(Compile using Android 6.0)

So the target compilation version is not compatible with the updating version of Android packages.

How To Fix the Error ?

To fix the error we have to change the target framework for compile to “Android 7.1(Nougat)”.

Here are Steps to change the target compile framework..

2. go to properties

Image 3 : Right Click on Android Project -> Properties

3 current versions

Image 4 : Current Android application properties(Compile using Android 6.0)

4 select api nouget

Image 5 : Change Compile Android Version to Android 7.1 (Nougat)

When Change the target compilation version of Android , Visual Studio will ask you to restart the project to configure itself…

5 restart project

Image 6 : “Yes” to close and reopen

6 lading

Image 7 : App is loading

7 go to nuget

Image 8 : Again go to NuGet package manager to update Android packages

8 download

Image 9 : Select Android Packages v.25.3.1(or the package showing here)

9 accept

Image 10 : Accept to Agree licence and tearms

9 conform update

Image 11 : You can see changes will be happening (the old packages and new packages). Click OK.

10. installing packages

Image 12 : Then the packages will be downloaded and Install Successfully.

Then Re-Build the project and the app will run successfully…

Thanks !

Xamarin Lesson 2 : Create a Cross-Platform Mobile Project in Visual Studio 2017

Video

This video demonstrates, How to create cross-platform mobile app Including Android/iOS/Windows Phone Native apps and a Portable Class Library(PCL) in Visual Studio 2017

Thanks !