Xamarin Day 2 – Android Concepts

Using Xamarin you can code Android apps and deploy it on Android. This post discusses Android basics for the un-initiated and how to approach android platform using Visual Studio

Introduces

  • MVC
  • Activity lifecycle

The View

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:orientation=”vertical”

android:layoutwidth=”fillparent”

android:layoutheight=”fillparent”>

<EditText

android:id=”@+id/txtview”

android:layoutwidth=”fillparent”

android:layoutheight=”wrapcontent” />

<Button

android:id=”@+id/MyButton”

android:layoutwidth=”fillparent”

android:layoutheight=”wrapcontent”

android:text=”@string/Hello” />

</LinearLayout>

The Activity

[Activity(Label = “Demo1”, MainLauncher = true, Icon = “@drawable/icon”)]

public class MainActivity : Activity

{

int count = 1;

protected override void OnCreate(Bundle bundle)

{

base.OnCreate(bundle);

// Set our view from the “main” layout resource

SetContentView(Resource.Layout.Main);

// Get our button from the layout resource,

// and attach an event to it

Button button = FindViewById<Button>(Resource.Id.MyButton);

var editText = FindViewById<EditText>(Resource.Id.txtview);

editText.Text = “Hello”;

button.Click += delegate { button.Text = string.Format(“{0} clicks!”, count++); };

}

}

Model

public class MyViewModel

{

public MyViewModel() { }

public int Id { get; set; }

public string Name { get; set; }

public string Designation { get; set; }

public string Index

{

get

{

return Text.Length == 0 ? “A” : Text[0].ToString().ToUpper();

}

}

}

Need to hide Titlebar?? Set the below properties in the attribute [Activity(Label = “Demo1”, MainLauncher = true, Icon = “@drawable/icon”)]

Theme = “@android:style/Theme.NoTitleBar”

Need to set Orienation

ScreenOrientation = ScreenOrientation.Portrait

Need Navigation?

void navigateToNextScreen(string txt)

{

Intent intent = new Intent();

intent.SetClass(this, typeof(Activity2));

intent.PutExtra(“txt”,txt);

StartActivity(intent);

}

Need to send parameters?

var txt = Intent.GetStringExtra(“txt”);

Need to show Dialog?

new AlertDialog.Builder(this).SetMessage(txtview.Text).Show();

Toast.MakeText(this, “The demo service has started”, ToastLength.Long).Show();

Resources are handled uniquely in Android as respect to other platforms (iOS, Windows);

Declare a ImageView 

<ImageVie

android:layoutwidth=”fillparent”

android:layoutheight=”fillparent”

android:id=”@+id/demoImageView”

android:src=”@drawable/fbicon”

android:scaleType=”fitCenter”/>

Setting image source in code

imageView.SetImageResource (Resource.Drawable.sample2);

Working listView

public class MyListAdapter : BaseAdapter<MyViewModel>, ISectionIndexer

{

protected Activity context = null;

protected IList<MyViewModel> list = new List<MyViewModel>();

public MyListAdapter(Activity context, IList<MyViewModel> list)
base()

{

this.context = context;

if (list == null)

list = new List<MyViewModel>();

this.list = list;

}

public override MyViewModel this[int position]

{

get { return list[position]; }

}

public override long GetItemId(int position)

{

return position;

}

public override int Count

{

get

{

return list.Count;

}

}

public override View GetView(int position, View convertView, ViewGroup parent)

{

// Get our object for this position

var item = list[position];

var view = (convertView ??

context.LayoutInflater.Inflate(

Resource.Layout.listviewitem,

parent,

false)) as LinearLayout;

// Find references to each subview in the list item’s view

var bigTextView = view.FindViewById<TextView>(Resource.Id.textView1);

var smallTextView = view.FindViewById<TextView>(Resource.Id.textView2);

bigTextView.SetText(list[position].Name, TextView.BufferType.Normal);

smallTextView.SetText(list[position].Designation, TextView.BufferType.Normal);

//((Activity)context).RunOnUiThread(() =>

//            {

//                imageview.SetImageBitmap(image);

//            });

return view;

}

public int GetPositionForSection(int section)

{

return 1;// alphaIndexer[sections[section]];

}

public int GetSectionForPosition(int position)

{

return 1;

}

public Java.Lang.Object[] GetSections()

{

return null;// sectionsO;

}

}

ListView in View

<ListView

android:minWidth=”25px”

android:minHeight=”25px”

android:layoutwidth=”matchparent”

android:layoutheight=”wrapcontent”

android:id=”@+id/listView1″ />

listItemView

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:orientation=”vertical”

android:layoutwidth=”fillparent”

android:layoutheight=”fillparent”

android:minWidth=”25px”

android:minHeight=”25px”>

<TextView

android:text=”Large Text”

android:textAppearance=”?android:attr/textAppearanceLarge”

android:layoutwidth=”matchparent”

android:layoutheight=”wrapcontent”

android:id=”@+id/textView1″ />

<TextView

android:text=”Small Text”

android:textAppearance=”?android:attr/textAppearanceSmall”

android:layoutwidth=”matchparent”

android:layoutheight=”wrapcontent”

android:id=”@+id/textView2″ />

</LinearLayout>

Code in Activity

SetContentView(Resource.Layout.mylistview);

listView = FindViewById<ListView>(Resource.Id.listView1);

if (listView != null)

{

listView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>

{

var intent = new Intent(this, typeof(Activity2));

intent.PutExtra(“txt”, getDummyData()[e.Position].Name);

StartActivity(intent);

};

}

loadList();

void loadList()

{

RunOnUiThread(() =>

{

MyListAdapter adapter = new MyListAdapter(this, getDummyData());

adapter.NotifyDataSetChanged();

listView.Adapter = adapter;

});

}

List<MyViewModel> getDummyData()

{

List<MyViewModel> list = new List<MyViewModel>();

list.Add(new MyViewModel() { Id = 1, Name = “ABC”, Designation = “ccc” });

list.Add(new MyViewModel() { Id = 1, Name = “DEF”, Designation = “cded” });

list.Add(new MyViewModel() { Id = 1, Name = “ABC”, Designation = “ccc” });

return list;

}

Activity Lifecyle events

protected override void OnCreate(Bundle bundle)

{

base.OnCreate(bundle);

Log.Info(tag, “OnCreate()”);

}

protected override void OnStart()

{

base.OnStart();

Log.Info(tag, “OnStart()”);

}

protected override void OnResume()

{

base.OnResume();

Log.Info(tag, “OnResume()”);

}

protected override void OnPause()

{

base.OnPause();

Log.Info(tag, “OnPause()”);

}

protected override void OnStop()

{

base.OnStop();

Log.Info(tag, “OnStop()”);

}

protected override void OnDestroy()

{

base.OnDestroy();

Log.Info(tag, “OnDestroy()”);

}

protected override void OnRestart()

{

base.OnRestart();

Log.Info(tag, “OnRestart()”);

}

protected override void OnSaveInstanceState(Bundle outState)

{

base.OnSaveInstanceState(outState);

Log.Info(tag, “OnSaveInstanceState()”);

}

protected override void OnRestoreInstanceState(Bundle savedInstanceState)

{

base.OnRestoreInstanceState(savedInstanceState);

Log.Info(tag, “OnRestoreInstanceState()”);

}

logging

string tag = “myapp”;

Log.Info (tag, “this is an info message”);

Log.Warn (tag, “this is a warning message”);

Log.Error (tag, “this is an error message”);

Log.Info(tag, this.LocalClassName);

button.Click += delegate

{

Intent i = new Intent();

if (this.LocalClassName == “demotry.MainActivity”)

{

i.SetClass(this, typeof(Activity1));

}

else

{

i.SetClass(this, typeof(MainActivity));

}

StartActivity(i);

};

Working for WebView

<WebView xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:layoutwidth=”fillparent”

android:layoutheight=”fillparent”

android:id=”@+id/LocalWebView”>

</WebView>

var webView = view.FindViewById<WebView>(Resource.Id.LocalWebView);

webView.LoadUrl(“http://xamarin.com&#8221;);

File read write

Utilities.CreateFile(“myfile.txt”, “this is content”);

string filecontent = Utilities.ReadFile(“myfile.txt”);

public class Utilities

{

public static void CreateFile(string fileName, string content)

{

string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

string filePath = System.IO.Path.Combine(path, fileName);

using (var file = File.Open(filePath, FileMode.Create, FileAccess.Write))

using (var strm = new StreamWriter(file))

{

strm.Write(content);

}

}

public static string ReadFile(string fileName)

{

string content = string.Empty;

string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

string filePath = System.IO.Path.Combine(path, fileName);

using (var file = File.Open(filePath, FileMode.Open, FileAccess.Read))

using (var strm = new StreamReader(file))

{

content = strm.ReadToEnd();

}

return content;

}

}

public static void SetPreference(Context context, string key , String value)

{

ISharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(context);

sp.Edit().PutString(key, value).Commit();

}

public static String GetPreference(Context context, string key)

{

ISharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(context);

return sp.GetString(key, null);

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s