GoldGold

阳哥的移动开发之旅

Activity向Fragment中传值

activity向fragment中传值   
1。要传的值  放到Bundle对象里

2。通过创建传递封Fragment 将bundle对象 通过 setArguments()传递到fragment

3.Fragment中 通过getArguments() 得到 bundle对象  就能得到里面的值



代码:

MainActivity:


package com.qianfeng.activitytofragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

@SuppressLint("NewApi") 
public class MainActivity extends Activity {

	private EditText et1;
	private FragmentManager manager;
	private FragmentTransaction transaction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et1 = (EditText) findViewById(R.id.et1);
        
        manager = getFragmentManager();
        transaction = manager.beginTransaction();
        
        transaction.add(R.id.contents, new Fragment1());
        transaction.commit();
        
    }
    
    //点击按钮时  进行传值
    public void onclickBtn(View v){
    	switch (v.getId()) {
		case R.id.button1:
			Fragment1 fragment1 = new Fragment1();
			Bundle bundle = new Bundle();
			String strValue = et1.getText().toString().trim();
			bundle.putString("str", strValue);
			fragment1.setArguments(bundle);
			//如果transaction  commit()过  那么我们要重新得到transaction
			transaction = manager.beginTransaction();
			transaction.replace(R.id.contents, fragment1);
			transaction.commit();
			break;

		default:
			break;
		}
    }
    
    
    
}












Fragment :


package com.qianfeng.activitytofragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("NewApi") 
public class Fragment1 extends  Fragment{
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_layout1, container, false);
		TextView textView1 = (TextView) view.findViewById(R.id.textView1);
		Bundle bundle = getArguments();//从activity传过来的Bundle
		if(bundle!=null){
			textView1.setText(bundle.getString("str"));
		}
		
		return view;
	}
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shanxuyang/article/details/47113709
文章标签: android
个人分类: Android基础知识
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭