FragmentActivity和Fragment..在这种情况下我该如何工作
本文关键字:何工作 工作 Fragment 这种情况下 FragmentActivity | 更新日期: 2023-09-27 18:19:48
我真的想不出一个好的问题标题。很抱歉。
这是我的问题:我有我的主要活动:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Support.V4.App;
namespace AndroidApplication2
{
[Activity(Label = "AndroidApplication2", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : FragmentActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
//Not sure if I need the code below
FragmentTransaction ft = this.SupportFragmentManager.BeginTransaction();
Activity2 fragment = new Activity2();
ft.Add(Resource.Id.fragmentContainer, fragment);
ft.Commit();
}
}
}
主活动的XML文件看起来像:
<?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">
<fragment
class="AndroidApplication2.Activity2"
android:id="@+id/fragmentContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/changeFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Fragment" />
</LinearLayout>
现在,Activity2看起来是这样的:
namespace AndroidApplication2
{
[Activity(Label = "My Activity")]
public class Activity2 : Fragment
{
public override View OnCreateView(LayoutInflater p0, ViewGroup p1, Bundle p2)
{
return p0.Inflate(Resource.Layout.fragment_layout, p1, false);
}
}
}
fragment_layout.axml看起来像这样:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView from the fragment" />
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button from the fragment" />
</LinearLayout>
这段代码在C#中使用Xamarin。
现在,我只想访问fragment_layout中的按钮,并使用它来替换Activity1(我的主要活动)中的片段。我用这个来避免为每一件简单的事情创建新的活动,比如显示某件事的细节,但我也不能使用任何弹出窗口。
我无法访问我在主FragmentActivity中加载的片段上的按钮,用它可以用另一个片段替换它。帮助谢谢任何其他改进或建议也欢迎。
尝试通过首先膨胀视图来访问按钮,然后返回。例如:
View view = p0.Inflate(Resource.Layout.fragment_layout, p1, false);
// now we can access button, textview etc... in the layout
_btnAboutUs = (Button)view.FindViewById(Resource.Id.btnAboutUs);
return view;
"但我仍然不知道如何访问我添加的新片段的按钮。"
你总是可以这样引用这个按钮:
_btnAboutUs = (Button)FindViewById (Resource.Id.btnAboutUs);
但是,也许在片段中使用按钮来替换按钮本身所在的片段并不是最好的方法。为什么不把按钮放在Activity1中,这样你就可以使用它的fragmentManager来替换片段了。片段没有fragmentManager,但活动有。