创建片段编程Android Xamarin

本文关键字:Xamarin Android 编程 片段 创建 | 更新日期: 2023-09-27 18:15:40

我正在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>

c

 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>

c

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'    

创建片段编程Android Xamarin

Resource.Id.fragment_container名称错误

似乎你没有fragment容器在你的活动。创建一个布局(FrameLayout)来保存你的fragment在你的activity中,并把这个布局id给replace方法的第一个参数。

。R.id.fragment_container

请遵循本教程

http://wptrafficanalyzer.in/blog/dynamically-add-fragments-to-an-activity-in-android/