安卓:片段无法获得活动 [英] Android: Fragment cannot get activity

查看:141
本文介绍了安卓:片段无法获得活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有做一个片段交易活动

I have an activity which does a fragment transaction

DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();

这工作正常。现在我知道在我的活动动态字符串我需要更换的布局我在newFragment。我想,我能器transaction.commit后调用()只是像

that works fine. Now I know within my activity a dynamic string I need to replace in the layout I have in newFragment. I thought that I can call after transaction.commit() just something like

newFragment.setMyString("my dynamic value");

而在newFragment.java我有

And in the newFragment.java I have

public void setMyString(String s)
{
 TextView tv = (TextView) getActivity().findViewById(R.id.myobject);
 tv.setText(s);
}

的一点是,getActivity()返回null。我怎样才能获得方面,我需要找到我的布局元素?

The point is that getActivity() returns null. How can I get the context I need to find my layout elements?

编辑:

我尝试使用包,因为这似乎是最干净的方式来遵循的路线。所以我改变了我的code:

I try to follow the route using a bundle as this seems to be the cleanest way. So I have changed my code:

Bundle b = new Bundle();
b.putString("text", "my dynamic Text");
DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();

我的片段onCreateView看起来是这样的:

My fragment onCreateView looks like this:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
   View v = inflater.inflate(R.layout.mylayout, container, false);
   TextView t = (TextView) v.findViewById(R.id.texttobereplaced);
   t.setText(savedInstanceState.getString("text");
}

看来savedInstranceState是空的。我应该在哪里找到我的包?

It seems that savedInstranceState is empty. Where should I find my bundle?

EDIT2:

无缘getArguments()的答复。是现在的工作。

missed the getArguments() in the reply. is working now.

推荐答案

片段还没有连接到活动然而,这也意味着你的布局并没有被夸大,但(见片段生命周期 )。最好的解决方法在这里是添加你的字符串值通过<一个参数传递给片段 href="http://developer.android.com/reference/android/app/Fragment.html#setArguments%28android.os.Bundle%29"><$c$c>Fragment.setArguments(Bundle)方法。这可以被检索片段通过<一个接收href="http://developer.android.com/reference/android/app/Fragment.html#getArguments%28%29"><$c$c>Fragment.getArguments()方法。

Your Fragment hasn't attached to the Activity yet, which also means your layout hasn't been inflated yet (See the Fragment lifecycle). The best solution here would be to add your String value as an argument to the Fragment via the Fragment.setArguments(Bundle) method. This can be retrieved in the receiving Fragment via the Fragment.getArguments() method.

这篇关于安卓:片段无法获得活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆