Activity向Fragment传值

package com.qy.af;

import com.qy.af.fragment.Frag_one;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.widget.Button;
//v4包 需要继承FragmentActivity
public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button=    (Button) findViewById(R.id.button1);

 FragmentManager manager=  getSupportFragmentManager();
 FragmentTransaction transaction=   manager.beginTransaction();
 Frag_one one=new Frag_one();
 //1.获取button的值
 String name= button.getText().toString();
 //2传值
 Bundle bundle=new Bundle();
 bundle.putString("name", name);
 //3开始传值
 one.setArguments(bundle);
 transaction.add(R.id.frag, one);
 transaction.commit();
}

}

package com.qy.af.fragment;

import com.qy.af.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class Frag_one extends Fragment{

private TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
     View view=inflater.inflate(R.layout.frag_one, container, false);
textView = (TextView) view.findViewById(R.id.text);
//接收传值
Bundle bundle=   getArguments();
textView.setText(bundle.getString("name"));
    return view ;
}

}

猜你喜欢

转载自blog.csdn.net/weixin_42791904/article/details/82624585