我试图简单地将数据从我的 Activity 类发送到我的 fragment ,但是当我试图在我的 fragment 中调用“setText(String text)”时,程序崩溃了。
Activity 类:
Fragment_green green = new Fragment_green();
transaction.replace(R.id.infoFragment, green);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
green.setText("bar"); //Works okay this far
我的 Fragment_green:
public class Fragment_green extends Fragment {
String textShow;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_green, container, false);
}
public void setText(String text){
TextView textView = (TextView) getView().findViewById(R.id.textGreen);
textView.setText(text); //Crash :(
}}
其他一切正常。我可以将 fragment 更改为另一个 fragment 等等。 我看过一些类似的帖子,但是当我尝试实现这些帖子时,会出现其他问题。
感谢所有有用的答案!
最佳答案
如果您确定 TextView 在您的 fragment 布局中,那么它可能是一个生命周期错误。当您尝试访问 TextView 时, fragment 的 View 尚未膨胀。
不建议以这种方式将信息传递给 fragment 。尝试通过包传递字符串,并在调用 onCreateView 时在 TextView 中设置文本。
关于Android:将数据发送到 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20080438/