更改屏幕片段后崩溃

时间:2015-01-21 09:05:20

标签: java android android-fragments fragment android-orientation

我想用捆绑包发送数据并在另一个片段中检索它们。

我的问题是当我在片段接收中更改屏幕方向时应用程序崩溃。

这是我的一段代码:

片段接收:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_actuality, container, false);

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    ImageView networkImageView = (ImageView)view.findViewById(R.id.thumbnail);

    Bundle bundle = getArguments();

    textcontent = (TextView)view.findViewById(R.id.content);
    texttitle = (TextView)view.findViewById(R.id.title);
    textdate = (TextView)view.findViewById(R.id.date);
    textweb = (TextView)view.findViewById(R.id.web);



    textcontent.setText(Html.fromHtml(bundle.getString("article")));
    textdate.setText("le " + bundle.getString("date"));
    texttitle.setText(bundle.getString("title"));
    textweb.setText("Pour plus d'information : " + bundle.getString("urlweb")); }

3 个答案:

答案 0 :(得分:1)

使用捆绑包时应始终检查为空

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_actuality, container, false);
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    ImageView networkImageView = (ImageView)view.findViewById(R.id.thumbnail);

        textcontent = (TextView)view.findViewById(R.id.content);
        texttitle = (TextView)view.findViewById(R.id.title);
        textdate = (TextView)view.findViewById(R.id.date);
        textweb = (TextView)view.findViewById(R.id.web);


        if(savedInstanceState!=null){  
        textcontent.setText(Html.fromHtml(bundle.getString("article")));
        textdate.setText("le " + bundle.getString("date"));
        texttitle.setText(savedInstanceState.getString("title"));
        textweb.setText("Pour plus d'information : "savedInstanceState.getString("urlweb"));
}

答案 1 :(得分:0)

在轮换时,将重新创建片段,将再次调用onCreateView()并且getArguments将为null。因此,您需要将数据保存在onSaveInstanceState()onCreateView()中,如果savedInstanceState为空则添加,您可以从getArgument()获取数据,否则您将从{{1}获取数据}}

答案 2 :(得分:0)

将此行添加到清单中的活动:

android:configChanges="keyboardHidden|orientation|screenSize"