我有一个执行片段事务的活动
DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();
工作正常。现在我在我的活动中知道了一个动态字符串,我需要在newFragment中的布局中替换它。我认为我可以在transaction.commit()之后调用类似
的东西newFragment.setMyString("my dynamic value");
在newFragment.java中我有
public void setMyString(String s)
{
TextView tv = (TextView) getActivity().findViewById(R.id.myobject);
tv.setText(s);
}
重点是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();
我的片段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");
}
似乎savedInstranceState为空。我应该在哪里找到我的捆绑包?
EDIT2:
错过了回复中的getArguments()。现在正在努力。
答案 0 :(得分:20)
请务必在getActivity()
之内或之后致电onAttach()
,与之前一样,它将返回null
。
答案 1 :(得分:18)
您的Fragment
尚未附加到Activity
,这也意味着您的布局尚未充气(请参阅Fragment lifecycle)。这里最好的解决方案是通过Fragment.setArguments(Bundle)
方法将String
值作为参数添加到Fragment
。这可以通过Fragment.getArguments()
方法在接收Fragment
中检索。
答案 2 :(得分:2)
所以我也使用相同的片段事务管理器,我可以看到你的代码唯一的问题是你在newFragment类的onCreateView方法中定义TextView tv,然后像这样实例化它:
public class AboutFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.newFragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.textview);
return v;
}
public void setMyString(String s) {
tv.setText(s);
}
}
我知道它确实没有多大意义,但这就是我运行代码的方式,它运行良好:)
答案 3 :(得分:0)
如果你需要在OnCreateView中调用getActivity,请将所有你的代码从onCreateView移到onActivityCreate并且只剩下左行
View v = inflater.inflate(R.layout.xxxx, container, false);
return v;
onCreateView 中的
但我有一个有趣的情况。
在我的onActivityCreated
中Spinner s1 = (Spinner) getActivity().findViewById(R.id.bitlength);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity(), R.array.bitlengths,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
有时onActivityCreated不会运行(正确!?),因此微调器s1变空。