如何解决语境'是一种类型,在给定的上下文中无效?

时间:2016-10-16 13:24:48

标签: c# android xamarin

我是Android和xamarin的新手 我想在使用片段构建的选项卡中添加listview。

我的代码在这里,它是xamarin构建三个选项卡的示例代码,我想在SpeakerFragment中构建一个列表视图:

using System;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using System.Collections.Generic;
using Android.Content;
using Android.Runtime;

namespace com.xamarin.example.actionbar.tabs
{
    public class SpeakersFragment :Fragment
    {

        private List<string> mItems;
        private ListView mListView;

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {

            View view = inflater.Inflate(Resource.Layout.listviewlayout,container,false);
            mListView = view.FindViewById<ListView>(Resource.Id.myList);

            mItems = new List<string>();
            mItems.Add("One");
            mItems.Add("Two");
            mItems.Add("Three");
            mItems.Add("Four");
            mItems.Add("Five");

            ArrayAdapter<string> adapter = new ArrayAdapter<string>(Context,Android.Resource.Layout.SimpleListItem1, objects: mItems.ToArray());

            mListView.Adapter = adapter;
            return view;
        }

    }

    public class SessionsFragment : Fragment
    {
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {

            View view = inflater.Inflate(Resource.Layout.simple_fragment, null);
            view.FindViewById<TextView>(Resource.Id.textView1).SetText(Resource.String.sessions_tab_label);
            view.FindViewById<ImageView>(Resource.Id.imageView1).SetImageResource(Resource.Drawable.ic_action_sessions);
            return view;
        }
    }

    public class WhatsOnFragment : Fragment
    {
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.simple_fragment, null);
            view.FindViewById<TextView>(Resource.Id.textView1).SetText(Resource.String.whatson_tab_label);
            view.FindViewById<ImageView>(Resource.Id.imageView1).SetImageResource(Resource.Drawable.ic_action_whats_on);
            return view;
        }
    }
}    

为什么会出现此错误?

  

&#39;上下文&#39;是一种类型,在给定的上下文中无效?

1 个答案:

答案 0 :(得分:2)

属性Fragment.Context仅在API级别为23时可用。https://developer.android.com/reference/android/app/Fragment.html#getContext()

您可以改用ActivityApplication.Context。或者将编译版本设置为API级别23,但如果您没有将最小支持版本设置为23,那么最终可能会在较旧的Android版本上发生一些崩溃。

ArrayAdapter<string>(Activity, Android.Resource.Layout.SimpleListItem1, objects: mItems.ToArray())