从活动中访问片段视图

时间:2014-05-07 19:47:34

标签: java android android-fragments android-view

我是Android开发的新手,我想制作简单的应用程序。我有一个 MainActivity 的活动,我在该活动中有一个片段 MainFragment 。我想从Activity onCreate和/或onResume更改此片段的TextView。但是,我无法处理。我的onCreate活动方法是:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new MainFragment()).commit();
    }

    TextView tv = (TextView) getSupportFragmentManager().findFragmentById(R.layout.fragment_main).getView().findViewById(R.id.textView1);

}

我在这里获取TextView时有NullPointerException。我认为它无法通过findFragmentById(R.layout.fragment_main)找到片段。因为我有fragment_main.xml,它是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.deneme.MainFragment" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />
</RelativeLayout>

My MainFragment Class&#39; onCreateView方法是:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_main, container, false);

    return rootView;
}

不希望在onCreate方法中更改片段的textview文本。我希望从活动中更改。我的问题是什么?

由于

2 个答案:

答案 0 :(得分:1)

这里有一些你需要解决的问题。 正如资深的安卓人员会告诉你的那样,从活动中改变片段的观点并不是一件好事。将活动视为它创造的碎片的“母亲”。如果母亲开始做孩子的家庭作业那么孩子们会做什么呢?片段的视图应该从片段内部处理,而不是在片段外部处理。更进一步,因为片段可能在屏幕上不可见,因此android内核将决定销毁它并将其GC。如果你继续保持对其观点的引用,那么它将浪费内存和资源。

但如果你仍然想那样:

  • 确保使用片段管理器中的片段事务创建片段并将其绑定到父片段。保存对活动对象中片段对象的引用。确保事务已提交。这个动作会让android调用片段的oCreateView,你可以在那里给片段的主视图充气。立即将对主片段视图的引用保存在类属性变量中。
  • 稍后如果您想要访问活动中片段的视图,请调用活动中片段对象的视图的getter,然后就完成了。

但我仍然敦促你让片段进行自己的视图处理,而不是在活动和片段之间混合视图处理,也不要在两个或多个片段之间混合。这是一个很大的设计,没有。

答案 1 :(得分:1)

好吧,

这不是你想要的。

您应该将片段中的UI更新作为公共方法实现,并在需要时从Activity中调用它。

这更优雅,你应该能够用这种模式取得任何成果。如果没有,那么这就是组件设计不良的标志,你应该考虑重构。

<强>更新

很容易:)

YourFragment frag = (YourFragment)getSupportFragmentManager().findFragmentById(R.layout.fragment_main);

if(frag != null){
    frag.updateTextView();
}
相关问题