我在Android Xamarin中创建片段。
这是我到目前为止所做的:
PortfolioFragment.cs
class PortfolioFragment: Fragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);
var view = inflater.Inflate(Resource.Layout.portfolio_fragment, container, false);
return view;
}
}
fragment.axml
<?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"
android:minWidth="25px"
android:minHeight="25px">
<TextView
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView1" />
</LinearLayout>
Main.cs
PortfolioFragment pFragment = new PortfolioFragment();
FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction().Replace(Resource.Id.fragment_container, pFragment);
但我收到错误:
Error 1 'MyProject.Resource.Id' does not contain a definition for 'fragment_container'
有什么不对?
修改
我尝试改为:
homeactivity.axml
<?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"
android:minWidth="25px"
android:minHeight="25px">
<FrameLayout
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frame_container" />
</LinearLayout>
Main.cs
SetContentView(Resource.Layout.homeactivity);
HomeFragment hFragment = new HomeFragment(this);
FragmentTransaction fTx = this.FragmentManager.BeginTransaction().Add(Resource.Id.frame_container, hFragment);
现在我收到一个错误:
Error 3 The best overloaded method match for 'Android.App.FragmentTransaction.Add(int, Android.App.Fragment)' has some invalid arguments
Error 4 Argument 2: cannot convert from 'MyProject.Views.HomeFragment' to 'Android.App.Fragment'
答案 0 :(得分:2)
Resource.Id.fragment_container名称错误
似乎您的Activity中没有片段容器。 创建一个布局(FrameLayout)来保存活动中的片段,并将该布局ID赋予replace方法的第一个参数。
EG。 R.id.fragment_container
请遵循本教程
http://wptrafficanalyzer.in/blog/dynamically-add-fragments-to-an-activity-in-android/