【发布时间】:2016-07-22 15:43:20
【问题描述】:
我有一个包含 2 个布局的滑动选项卡界面。在第二个布局上,我有一个按钮,它必须启动一个将内容视图设置为新布局的活动。尝试启动活动时出现以下错误:
非静态字段、方法或属性“Fragment.StartActivity(Intent)”需要对象引用
ViewPager 类如下所示:
public class SamplePagerAdapter : PagerAdapter
{
List<string> items = new List<string>(); //This list called items contains the items that we add below
public SamplePagerAdapter() : base() //This method creates the tabs on top
{
items.Add("Productivity Optimization");
items.Add("Remote Health Monitoring");
}
public override int Count
{
get { return items.Count; } //This method returns the count of the tabs
}
public override bool IsViewFromObject(View view, Java.Lang.Object obj)
{
return view == obj;
}
public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)
{
View view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.PO, container, false);
//***Original code***
//View view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.pager_item, container, false);
//container.AddView(view);
//TextView txtTitle = view.FindViewById<TextView>(Resource.Id.item_title);
//int pos = position + 1;
//txtTitle.Text = pos.ToString();
//return view;
//***end of original code***
//This is where you set which layout to display in which order
if (position == 0)
{
view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.PO, container, false);
container.AddView(view);
}
if (position == 1)
{
view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.RHM, container, false);
container.AddView(view);
//New test button that should start the web browser activity
var btnRep = (Button)view.FindViewById(Resource.Id.btnReport);
btnRep.Click += BtnRep_Click;
}
return view;
}
}
而发生错误的按钮点击方法如下所示:
(错误在于StartActivity)
private void BtnRep_Click(object sender, EventArgs e)
{
var BrowserIntent = new Intent(Application.Context,typeof(ReportBrowserActivity));
**StartActivity(BrowserIntent);**
}
我知道对于这个问题有很多类似的问题和答案,但我是 Xamarin 的新手,我似乎无法做到这一点。
我们将不胜感激任何对正确方向的帮助或推动。
【问题讨论】:
-
点击方法中的行 (
BrowserIntent) 可以尝试将Application.Context替换为Context吗? -
@Pilatus,感谢您回复我。是的,我也尝试过,但随后出现以下错误:'Context' 是一种类型,在给定的上下文中无效。 这是在我将行更改为@987654328 之后@
-
这可能是因为你从你的活动中调用
Context在这种情况下this等于你的Activity的Context尝试用this替换Context。 -
@Pilatus,我最初是这样写的,但它一直给我以下错误:CS1503 Argument 1: cannot convert from 'JoySmart_Solutions.SlidingTabsFragment.SamplePagerAdapter' to 'Android.内容.上下文'
-
您需要引用
Activity。如果您使用Fragment来显示ViewPager,则可以通过Activity属性访问此引用。