从片段中检索数据

时间:2016-03-07 15:15:12

标签: java android

我想从我从活动发送的片段中检索String数据,并且我正在使用此代码发送:

Bundle bundle = new Bundle();
bundle.putString("name",texts.get(position));
CatSelected catSelected = new CatSelected();
catSelected.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, catSelected, "CatSelected").commit();

此代码接收:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.search_frag, container, false);
    txt = (TextView) view.findViewById(R.id.textView);
    txt.setText(getArguments().getString("name"));
    return view;
}

但是textview显示默认文字并且不会更改。有什么问题?

2 个答案:

答案 0 :(得分:0)

在第二个片段或片段中,您想要首先检索传递的值,必须创建一个bundle。试试这个。

  Bundle bundle = getArguments();
  txt.setText = bundle.getString("name");

答案 1 :(得分:0)

使用片段时常见的做法是,不要直接实例化片段。相反,您可以通过执行以下操作来获取片段对象。

    MyFragment = MyFragment.newInstance(int arg1, String args2); // pass your args here
    getSupportFragmentManager().beginTransaction().replace(R.id.flContent, fragment).commit();

现在,MyFragment

组成
public static MyFragment newInstance(int arg1, String arg2) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("arg1Key", arg1);
        args.putInt("arg1Key", arg2);
        fragment.setArguments(args);
        return fragment;
    }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        myArg1 = getArguments().getInt("arg1Key");
        myArg2 = getArguments().getInt("arg2Key");
    }
}