activity与activity之间怎么传值,与fragment是怎么创的?

来源:互联网 发布:德国4g网络制式是什么 编辑:程序博客网 时间:2024/05/05 07:32

MainActivity:

//创建Fragment对象的时候,使用Bundle对象传值给Fragment

@Override

protected void onCreate(Bundle savedInstanceState)

{

   super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

 

    //创建Fragment对象,并通过Bundle对象传递值

    MyFragmentfragment = new MyFragment();

    Bundle bundle =new Bundle();

   bundle.putString("key", "value");

   fragment.setArguments(bundle);

 

    //利用FragmentManager对象和事物对象添加到布局中

    FragmentManagerfragmentManager = getFragmentManager();

   FragmentTransaction transaction  =fragmentManager.beginTransaction();

   transaction.add(R.id.relativeLayout_show, fragment;

   transaction.commit();

 

}

                                 

MyFragment:

//拿到Bundle对象,如果有参数传递,就拿到值并赋值给str
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
{
    Bundle bundle = this.getArguments();
    if (bundle != null)
    {
        String str = bundle.getString("key");
    }
    TextView textView = new TextView(getActivity());
    textView.setText("上上下下的享受");//是电梯,别误会
    return textView;
}

写法2

因为考虑是面向对象的话,传递值这样的事情应该由Fragment来做,也就是你(Fragment)要什么值,我(Activity)就给你什么值

public class MainActivity extends Activity

{

    @SuppressLint("NewApi")

    @Override

    protected voidonCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

 

       FragmentManager fragmentManager = getFragmentManager();

       FragmentTransaction transaction = fragmentManager.beginTransaction();

        MyFragmentfragment = MyFragment.newMyFragment("给老子过去");//如果不想传值,给过去一个null就行

       transaction.add(R.id.relativeLayout_show, fragment);

       transaction.commit();

    }

}

 

 

 

/*========================Fragment↓==========================*/

 

class MyFragment extends Fragment

{

    StringmValue;// 用于接收Activity传过来的数值

    private staticfinal String MARK = "mark";// 设置标记

 

    @Override

    public ViewonCreateView(LayoutInflater inflater, ViewGroup container,BundlesavedInstanceState)

    {

        // 那到Bundle对象,如果有参数传递,就拿到值并赋值给mValue

        Bundlebundle = this.getArguments();

        if (bundle!= null)

        {

            mValue= bundle.getString(MARK);

        }

        TextViewtextView = new TextView(getActivity());

       textView.setText(mValue);

        returntextView;

    }

 

 

    /**

     * 别通过new对象拿到Fragment了,直接调用我就行了

     * @param value想要拿到我,好啊!给我值(value)

     * @returnfragment

     */

    public staticMyFragment newMyFragment(String value)

    {

        //将fragment绑定参数

        Bundlebundle = new Bundle();

       bundle.putString(MARK, value);

        MyFragmentfragment = new MyFragment();

       fragment.setArguments(bundle);

        returnfragment;

    }

}

0 0
原创粉丝点击