从片段内的setText [英] setText from inside a fragment

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

问题描述

我运行一个片段活动,试图设置父活动一个TextView的文本内的setText命令,但它不工作。任何想法?

I run a setText command inside of a fragment activity to try and set the text of a textView in the parent activity, but it's not working. Any ideas?

TextView text = (TextView) getView().findViewById(R.id.status);
        text.setText("Text from a fragment");

我不明白在Eclipse中的错误,但我在运行时得到一个空指针异常。当然,它发生在哪里我的setText行。如何做到这一点任何想法?

I don't get an error in eclipse, but I get a null pointer exception during runtime. Of course it happens at the line where I setText. Any ideas on how to do this?

推荐答案

是您的NPE可能是因为 R.id.status 很可能无法在片段的视图定义

Yes your NPE will probably be because R.id.status is probably not defined in the fragment's view.

getView()将返回在你的碎片的 onCreateView()方法生成的视图。

getView() will return the view that is generated in your Fragment's onCreateView() method.

您想从(次)FragmentActivity在活动设置一个TextView或试图从一个片段设置在FragmentActivity一个TextView?

Are you trying to set a TextView in your Activity from a (secondary) FragmentActivity or trying to set a TextView in your FragmentActivity from a Fragment?

如果它是第一种选择,你会想要做这样的事情用一个消息处理程序,并通过第二次活动的消息。我不认为这是你在问什么,但。

If it's the 1st option, you'll want to do something like use a message handler and pass the 2nd Activity a message. I don't think this is what you're asking though.

如果你想从一个片段设置一个TextView,要做到这一点,一般的方法是定义你的FragmentActivity接口与方法( UPDATETEXT()例如),并获得片段调用的方法。那么活动处理TextView的更新,这很好地工作,因为它可以调用 getView()将返回你要找的看法。我的答案公布它类似于<一个href=\"http://stackoverflow.com/questions/11573712/why-direct-communication-between-fragments-is-not-recommended/11573912#11573912\">here

If you're wanting to set a TextView from a Fragment, the general way to do that is to define an interface on your FragmentActivity with a method (updateText() for example) and get the Fragment to call the method. The Activity then handles the TextView update, which works nicely because it can call getView() which will return the view you're looking for. It's similar to my answer posted here

这篇关于从片段内的setText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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