通过bundle对象实现Fragment之间的传值

来源:互联网 发布:淘宝免单可信吗 编辑:程序博客网 时间:2024/06/06 14:24

这里我们介绍一下使用bundle对象进行Fragment传值,比较简单我们直接看代码吧,都有注释的。

MainActivity:

package org.mobiletrain.fragment_demo07;import android.os.Bundle;import android.app.Activity;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.view.Menu;import android.view.View;import android.widget.Toast;public class MainActivity extends Activity {RightFragment fragment;FragmentManager manager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);fragment = new RightFragment();manager = getFragmentManager();FragmentTransaction transaction = manager.beginTransaction();//通过bundle对象向Fragment传值Bundle bundle = new Bundle();bundle.putString("key", "我是主人,activity");fragment.setArguments(bundle);transaction.add(R.id.rightLayout, fragment);transaction.commit();}public void getRight(View v){//获取从Fragment中传来的值String values = fragment.getArguments().getString("data");Toast.makeText(MainActivity.this, "fragment传来的:"+values, 0).show();}}
右边的Fragment:

package org.mobiletrain.fragment_demo07;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast;public class RightFragment extends Fragment{@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView view = inflater.inflate(R.layout.right, null);//向MainActivity传值getArguments().putString("data", "您好,我是fragment");Button rightButton = (Button)view.findViewById(R.id.rightBn);rightButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//获取从MainActivity传来的值String content = getArguments().getString("key");Toast.makeText(getActivity(),"activity说的:"+content, 0).show();}});return view;}}

0 0
原创粉丝点击