Android:将数据发送到 fragment

标签 android android-fragments textview

我试图简单地将数据从我的 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/

相关文章:

Android:在选择另一个微调器中的选项后使微调器出现

android - 我应该如何在 android 上保存包含 ListView 的 fragment 状态?

java - android.widget.TextView.setTextAlignment() : java. lang.NoSuchMethodError

android - 在 android 中使用其他 View 在屏幕上绘图

java - 从字符串列表中删除字符串项

android - 刷新 Activity/"performing stop of activity that is not resumed"错误

android - 如何在右侧创建状态栏图标? (安卓)

java - 为什么我的 CardView 不会出现在我的 fragment 中?

java - 在 SlidingTabslayout 中的两个选项卡 fragment 之间传递数据

java - 如何将从联系人中选择的电话号码存储到字符串中?