Android programming requires the use of the Findidbyview function, which is also required for Xamarin Android development. The work is boring and annoying. In the conventional Android development, people have invented some methods to eliminate this work, such as Android data binding, as well as butterknife, can solve this problem. I'm not going to elaborate on them. But these two programs are not available in Xamarin Android development. This article introduces a function that frees the programmer from this work, as in the original text, see http://redth.codes/auto-wire-up-views-xamarin-activity/.
Let's go directly to the code below.
This paragraph is an activity.
1 usingAndroid.app;2 usingAndroid.widget;3 usingAndroid.os;4 5 namespaceAndApp26 {7[Activity (Label ="AndApp2", Mainlauncher =true, Icon ="@drawable/icon")]8 Public classmainactivity:activity9 {Ten intCount =1; One Button MyButton; A TextView txtname; - - protected Override voidOnCreate (Bundle bundle) the { - Base. OnCreate (bundle); - This. BindView (Resource.Layout.Main); - +Mybutton.click + = (s,e) = { -Mybutton.text =string. Format ("{0} clicks!", count++); +txtName.Text ="Bruce"; A }; at } - } -}
Where BindView is an extension method, including setcontent and the variable that binds the view to this activity.
Layout has a button mybutton and a TextView txtname.
Here is the BindView extension method:
1 Public Static classactivityextensions2 {3 Public Static voidBindView ( ThisActivity activity,intlayoutresid)4 {5 activity. Setcontentview (LAYOUTRESID);6 //Get All the View fields from the activity7 varMembers = fromMinchActivity. GetType (). GetFields (BindingFlags.NonPublic |bindingflags.instance)8 whereM.fieldtype.issubclassof (typeof(View))9 Selectm;Ten One if(!Members . Any ()) A return; - -Members. ToList (). ForEach (M = the { - Try - { - //Find The android identifier with the same name + varid = activity. Resources.getidentifier (M.name,"ID", activity. PackageName); - //Set the Activity field ' s value to the view with that identifier + M.setvalue (activity, activity. Findviewbyid (ID)); A } at Catch(Exception ex) - { - Throw NewMissingFieldException ("Failed to wire up the field" -+ M.name +"To a View in your layout with a corresponding identifier", ex); - } - }); in } -}
The method uses reflection, and some people worry about its performance. However, it is negligible for a few view in an activity.
Of course, it's not a problem at all. It has been pointed out that an exception will be thrown if you want to use a view that does not have a corresponding in layout. This problem is actually very well solved. For example, to modify the BindView function, let's agree that all automatically bound view variables start with M and the other variables don't start with M. When we can also take the variable annotated on the scheme, this will solve the problem, as to how to do, it is not here to say, so far, I think now is good enough.
Xamarinandroid automatically bind view variables