Search code examples
c#androidxamarinandroid-videoview

Why can I not initialise a VideoView object by the FindViewById method?


I want to play a mp4 video which I have put in the folder Resources/raw. The following is my code and the error "A field initialiser can not be applied to the non static fiel or non static method or property" (translated from German) is displayed, 'FindViewById(Resource.Id.vv)' being the underlined part. In my layout file I have included a VideoView with the id 'vd'. I would be very thankful for every help to play my video!

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;

namespace App_1_design
{
    [Activity(Theme = "@style/AppTheme", MainLauncher = true]
    public class MainActivity : AppCompatActivity
    {
        VideoView vid = (VideoView) FindViewById(Resource.Id.vv);

Solution

  • We need to initialize controls in the OnCreate event after setting the layout file like:

    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        VideoView vid;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
    
            vid = FindViewById<VideoView>(Resource.Id.vv);
    
            var uri = Android.Net.Uri.Parse("android.resource://" + PackageName + "/" + Resource.Raw.sample_video);
            vid.SetVideoURI(uri);
            vid.Start();
        }
    }
    

    Update

    why now the error message says 'resource does not contain a definition for raw'?

    enter image description here

    Make sure the build action of your video is AndroidResource. And then we could access this resource through Resource.Raw.[yourVideoID].