[英]fragment access widget from another fragment in the same activity
我想通过单击fragment2中的按钮来更改fragment1中文本视图中的文本,我设法通过将文本视图声明为static
来做到这一点,因此可以通过Fragment1.textv.setText("hi");
来更改文本Fragment1.textv.setText("hi");
,可以吗,这样做的最佳方法是什么?
static textv ;
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_frag_beam_rec, container, false);
textv= (TextView)v.findViewById(R.id.textview);
return v;
}
最常见的方法是使用接口从片段A到片段B“说话”(您需要通过活动进行通信):
http://developer.android.com/training/basics/fragments/communicating.html
您还可以使用像Otto这样的事件总线库,注册要更新的片段,并从另一个片段发布更新:
如user3806331所述,您需要使用接口,单击链接即可找到所需的内容。但是请注意,静态引用窗口小部件是一种不好的做法,因为在某些情况下可能会导致内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.