相关疑难解决方法(0)

Android:Fragment无法获得活动

我有一个执行片段事务的活动

DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Run Code Online (Sandbox Code Playgroud)

工作正常.现在我在我的活动中知道了一个动态字符串,我需要在newFragment中的布局中替换它.我以为我可以在transaction.commit()之后调用类似的东西

newFragment.setMyString("my dynamic value");
Run Code Online (Sandbox Code Playgroud)

而在newFragment.java中我有

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

关键是getActivity()返回null.如何获得我需要的上下文来查找布局元素?

编辑:

我尝试使用捆绑包来跟踪路线,因为这似乎是最干净的方式.所以我改变了我的代码:

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();
Run Code Online (Sandbox Code Playgroud)

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

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");
}
Run Code Online (Sandbox Code Playgroud)

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

EDIT2:

在回复中错过了getArguments().现在正在工作.

android android-fragments

18
推荐指数
2
解决办法
7万
查看次数

将服务绑定到FragmentActivity或Fragment?

绑定服务是否更好FragmentActivity:

bindService(Intent, ServiceConnection, int);
Run Code Online (Sandbox Code Playgroud)

或者Fragment:

getActivity().bindService(Intent, ServiceConnection, int);
Run Code Online (Sandbox Code Playgroud)

什么是更好的做法?

service android android-fragments android-fragmentactivity

10
推荐指数
1
解决办法
2万
查看次数