1. 程式人生 > >通過bundle物件實現Fragment之間的傳值

通過bundle物件實現Fragment之間的傳值

這裡我們介紹一下使用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;
	@Override
	protected 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{

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View 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() {
			
			@Override
			public void onClick(View v) {
				//獲取從MainActivity傳來的值
				String content = getArguments().getString("key");
				Toast.makeText(getActivity(),
						"activity說的:"+content, 0).show();
			}
		});
		return view;
	}
	
}