Pass values from activity to Fragment by bundle

时间:2017-07-30 11:48:49

标签: android android-fragments android-bundle

in my fragment the bundle is always null

main activity

public class MainActivity extends AppCompatActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle args=new Bundle();
        args.putString("itemname", "hello");
        beaconListFragment=new BeaconListFragment();
        beaconListFragment.setArguments(args);

        //i don't know if this is needed or not, i tried with and without it
        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, beaconListFragment,"tag").commit();
    }

    ...
    ..
    .

BeaconListFragment

public class BeaconListFragment extends android.support.v4.app.Fragment {
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();


        //bundle is always null
        if (bundle != null) {
            String link = bundle.getString("itemname");

        }
    }
    ...
    ..
    .

most examples seem like this but i can't understand where is the problem

3 个答案:

答案 0 :(得分:0)

您应该读取on​​Create而不是onActivityCreated

中的数据
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    if (getArguments() != null)
    {
        String link = bundle.getString("itemname");
    }

}

答案 1 :(得分:0)

对于片段,在该方法中有一个类似 setArguments()的方法,你可以传递bundle对象。

在片段类中,您可以通过 getArguments()访问该分发包。

以上述方式你可以传递参数

答案 2 :(得分:0)

检查片段中的import语句。看起来你混合了两种类型:一种来自SDK,另一种来自支持库。一定要使用任何一个。

你的片段继承自android.support.v4.app.Fragment。您的import语句在此处的代码中不可见。如果您的import语句有android.app.Fragment,请删除该行并尝试。