0

这是我的容器活动Table_info,我想将数据从容器活动传递给它的子片段Table_no。但我收到片段中的字符串为null.

Table_info 的代码:

package com.example.androiddbconnection;

import android.content.Intent;
import android.os.Bundle;
android.support.v4.app.FragmentActivity;
import android.util.Log;

public class Table_info extends FragmentActivity {
String restaurant;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tableinfo_frag);

Intent in=getIntent();
    Bundle bundle = getIntent().getExtras();
    restaurant = bundle.getString("outletname");
    Log.d("in mainactivity",restaurant);

  Bundle bundle1 = new Bundle();

  bundle1.putString("restaurant",restaurant);

    Table_no fragment=new Table_no();
    fragment.setArguments(bundle1);



    }


  }

这是我的片段Table_no

public class Table_no extends Fragment {

String restaurant12;
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle=getArguments(); 
        if (bundle == null) {
        Toast.makeText(getActivity(),"argum is null", Toast.LENGTH_LONG).show();
        }
            else{
            Toast.makeText(getActivity(),"argume", Toast.LENGTH_LONG).show();
        restaurant12=bundle.toString();
        Log.d("arguments", restaurant12);
        }

 }

但我得到的回应是'argum is null'

4

3 回答 3

1

为了从 Activity 调用 Fragment 的方法,您需要将您的 Activity 添加到FragmentTransaction然后您可以这样做:

在活动的网站上:

Table_no mTable_no = (Table_no) getFragmentManager().findFragmentByTag("Table_no_tag");
mTable_no.setMyData(String);

在片段的网站上:

 public void setMyData(String string) {
    this.string = string;
 }
于 2013-10-16T09:02:56.217 回答
0

对片段使用构造函数。您可以使用它的构造函数直接将值传递给片段。

public class Table_no extends Fragment {

String restaurant12="";

public Table_no(String restaurant)
{
restaurant12=restaurant;
}

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 Toast.makeText(getActivity(),restaurant12, Toast.LENGTH_LONG).show();

 }
于 2013-10-16T09:22:35.917 回答
0

即使我面临同样的问题,但添加以下行解决了我的问题。

Bundle bundle = getIntent().getExtras();
       String getFeatureDescription= bundle.getString("desc");

        Bundle b = new Bundle();
        fragmentManager = getSupportFragmentManager();
        b.putString("bb",getFeatureDescription);

        FragmentFeatureOverview ff = new FragmentFeatureOverview();
        ff.setArguments(b );
fragmentManager.beginTransaction().replace(R.id.fragmentContainer,ff).commit();

但是在添加这一行之后,我的标签停止交换。

fragmentManager.beginTransaction().replace (R.id.fragmentContainer,ff).commit();
于 2017-08-03T10:22:29.650 回答