Android如何将数据从Activity发送到Fragment?

时间:2016-12-12 17:51:45

标签: android android-fragments android-activity

我想将数据从Activity传递到Fragment。我不知道该怎么做。我见过很多解决方案,但没有一个能真正起作用。

我只想将一个简单的String传递给Fragment

我试过这种方式:

public class PhotoActivty extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        if (null == savedInstanceState) {
            Bundle bundle = new Bundle();
            String myMessage = "Stackoverflow is cool!";
            bundle.putString("message", myMessage );
            BasicFragment fragInfo = new BasicFragment();
            fragInfo.setArguments(bundle);
            android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.photo_frame, fragInfo);
            transaction.commit();
        }
    }
}

那里有什么错误?我这样称呼它:

String myValue = this.getArguments().getString("message"); 

onCreateView

中的Fragment

5 个答案:

答案 0 :(得分:1)

Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
Fragment fragInfo = new BasicFragment();
fragInfo.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.photo_frame, fragInfo);
transaction.commit();

在你的if

中试试

答案 1 :(得分:1)

我通常使用静态工厂模式:

public class MyFragment extends Fragment {
    public static MyFragment newInstance(int index) {
        MyFragment f = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);
        return f;
    }
}

在您的活动中创建片段时:

Fragment MyFragment = MyFragment.newInstance(5);

Alex Lockwood对于为何这是首选设计模式有一个很好的概述: http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html

答案 2 :(得分:1)

来自活动:

Bundle bundleObject = new Bundle();
bundleObject.putString("data", " Send From Activity");
/*set Fragmentclass Arguments*/
Fragment fragmentobject = new Fragment();
fragmentobject .setArguments(bundleObject );

来自片段你会收到这样的:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
String stringText = getArguments().getString("data");    
return inflater.inflate(R.layout.fragment, container, false);

答案 3 :(得分:0)

不确定这是否是问题的真正原因,但您必须在getSupportFragmentManager()内使用getFragmentManager()而不是AppCompatActivity。此外,FragmentFragmentTransaction等类应来自support.v4包。

答案 4 :(得分:0)

删除活动中的savedInstanceStatenull == null。如果BasicFragment,那么FrameLayout将不会取代R.id.photo_frame {{1}}。{/ p>