【发布时间】:2013-06-24 22:21:11
【问题描述】:
我真的想不出一个好的问题标题。对此感到抱歉。
这是我的问题: 我有我的主要活动:
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 中加载的片段上的按钮,我可以用该按钮将其替换为另一个片段。帮助!谢谢!也欢迎任何其他改进或建议。
【问题讨论】:
-
好的,我的一个问题解决了。如果片段是静态添加的,我无法替换它。但我仍然不知道如何访问我添加的新片段的按钮。请帮帮我。谢谢!
标签: c# android-fragments xamarin.android xamarin android-fragmentactivity