Creating a custom alert view in Android using C#
July 1, 2015
No comments
Article
As mentioned in my earlier post, we can use the default AlertDialog class to display the alerts of screen by setting different properties and methods of it. But still there sounds like, we may need dialogs on screen which would be needed to be customized. They can be accept user inputs, can display an arranged info of an user etc.
How to do it ?
We will follow few simple steps
- Create a custom view
- Render the custom view in AlertDialog
Create a custom view
Let’s add a new layout to the project under Resources > layout.
Adding the below code to the newly added layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <RelativeLayout android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/relativeLayout1" android:layout_marginBottom="191.7dp" /> <EditText android:inputType="textMultiLine" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/alertText" /> <Button android:text="Button" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnOK" /> </LinearLayout> |
Render the custom view in AlertDialog
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var custAlert = (new AlertDialog.Builder(this)).Create(); custAlert.SetTitle("Custom Alert"); var customView = this.LayoutInflater.Inflate(Resource.Layout.layout1, null); customView.FindViewById<Button>(Resource.Id.btnOK).Click += ((sender, args) => { var aletTextbox = customView.FindViewById<EditText>(Resource.Id.alertText); Toast.MakeText(this, aletTextbox.Text, ToastLength.Long).Show(); }); custAlert.SetView(customView); custAlert.Show(); |
Hope this will help đŸ™‚
Categories: Android, CSharp, MonoDroid, Visual Studio, Xamarin