Fragment和Activity通信以及Fragment之间通信的两种方式

Fragment之间通信很简单……这里只是提供思路,无论是Fragment和Activity还是Fragment之间,通信的原理都是如此,一通百通,后面会附上DEMO

Fragment是依附于Activity的,所以Fragment之间通信不能直接通信,必须依靠所依附的Activity。

方式1

可以通过getSupportFragmentManager()拿到FragmentManager,然后通过FragmentManager的findFragmentByTag或者findFragmentById拿到我们需要通信的Fragment(比如说在下面的DEMO中我们用的是FragmentTabHost,所以就使用findFragmentByTag拿到Fragment,如果Fragment是直接在XML中定义的,那么就使用findFragmentById拿到Fragment),然后就可以对拿到的Fragment进行各种操作了。

方式2

如果直接在Fragment里面操作其他的Fragment总归是不太好,为了降低代码之间的耦合,我们可以通过回调实现Fragment之间通信。

因为太简单了,所以直接帖代码了


Demo1

1 重写fragment_home.xml和fragment_message.xml(只在fragment_home和fragment_message之间通信

fragment_home.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <TextView
          android:id="@+id/tv"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="Fragment Home" />

    
     <Button 
         android:id="@+id/btn_home"
         android:layout_below="@id/tv"
        android:layout_centerHorizontal="true"
         android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取来自Fragment Message的数据"/>
</RelativeLayout>

fragment_message.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Fragment Message"
        android:textSize="25sp" />

    <Button
        android:id="@+id/btn_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:layout_centerHorizontal="true"
        android:text="获取来自Fragment Home的数据" />

</RelativeLayout>

再来看看FragmentHome的代码,很简单……

扫描二维码关注公众号,回复: 3268770 查看本文章

public class FragmentHome extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_home, null);
		setupView(view);

		return view;

	}

	private void setupView(View view) {

		Button Btn1 = (Button) view.findViewById(R.id.btn_home);// 获取按钮资源
		Btn1.setOnClickListener(new Button.OnClickListener() {// 创建监听
			public void onClick(View v) {
				MainTab activity = ((MainTab) getActivity());
				FragmentManager manager = activity.getSupportFragmentManager();
				FragmentMessage fragment = (FragmentMessage) manager
						.findFragmentByTag("tab2");
				if (null != fragment) {
					View vw = fragment.getView();
					if (null != vw) {
						TextView txt = (TextView) vw.findViewById(R.id.tv);
						T.showShort(getActivity(), txt.getText().toString());
					}
				} else {
					T.showShort(getActivity(), "FragmentMessage还未创建");
				}

			}

		});

	}
}

这里做一下简单说明:

MainTab activity = ((MainTab) getActivity());得到当前绑定的Activity实例对象

FragmentManager manager = activity.getSupportFragmentManager(); 拿到FragmentManager

FragmentMessage fragment = (FragmentMessage) manager.findFragmentByTag("tab2"); 拿到需要操作的fragment ,接下来就可以对它进行各种操作了

FragmentMessage代码类似

public class FragmentMessage extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_message, null);

		

		setupView(view);
		
		return view;
	}

	private void setupView(View view) {
        Button Btn1 = (Button)view.findViewById(R.id.btn_message);//获取按钮资源    
        Btn1.setOnClickListener(new Button.OnClickListener(){//创建监听    
            public void onClick(View v) {    
            	MainTab activity = ((MainTab) getActivity());
            	FragmentManager manager = activity.getSupportFragmentManager();
            	FragmentHome fragmentHome = (FragmentHome) manager.findFragmentByTag("tab1");
            	if (null != fragmentHome) {
     				View vw = fragmentHome.getView();
        				if (null != vw) {
        					TextView txt = (TextView) vw
        							.findViewById(R.id.tv);
        					T.showShort(getActivity(), txt.getText().toString());  
        				}
        			} else {
        				T.showShort(getActivity(), "FragmentHome还未创建");  
        			}		
            	
            }    
  
        });    

	}
}

效果图1(首次打开时点击,FragmentMessage还未创建)

                效果图2(切换到消息Tab,获取到了FragmentHome中TextView的值

                效果图3(再次切换到首页Tab,获取到了FragmentMessage中TextView的值



Demo2

fragment_home.xml和fragment_message.xml(只在fragment_home和fragment_message之间通信

fragment_home.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <TextView
          android:id="@+id/tv"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="Fragment Home" />

    
     <Button 
         android:id="@+id/btn_home"
         android:layout_below="@id/tv"
        android:layout_centerHorizontal="true"
         android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击把值传给Fragment Message"/>
</RelativeLayout>

fragment_message.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Fragment Message"
        android:textSize="25sp" />

</RelativeLayout>


FragmentHome

<pre name="code" class="java">public class FragmentHome extends Fragment {

	OnButtonclickListener mCallback;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		 View  view = inflater.inflate(R.layout.fragment_home, null );
		
		 setupView(view);
		return view;	
		
	}

	private void setupView(View view) {
        Button Btn1 = (Button)view.findViewById(R.id.btn_home);//获取按钮资源    
        final TextView tv = (TextView) view.findViewById(R.id.tv);
        Btn1.setOnClickListener(new Button.OnClickListener(){//创建监听    
            public void onClick(View v) {    
            	
            	mCallback.OnButtonclicked(tv.getText().toString());
            	
            }    
  
        });    

	}
	
	
	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

      
        try {
            mCallback = (OnButtonclickListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnButtonclickListener");
        }
    }
	
	
	

     public interface OnButtonclickListener {
    	 
        public void OnButtonclicked(Object object);
    }
	
}


 说明:首先定义接口,然后在Button的点击事件中回调 
 

再来看看MainTab,实现 OnButtonclickListener接口,然后重写OnButtonclicked方法就可以了

@Override
	public void OnButtonclicked(Object object) {
		FragmentMessage fMessage = (FragmentMessage) getSupportFragmentManager()
				.findFragmentByTag("tab2");
		if (fMessage != null) {
			
			View vw = fMessage.getView();
			if (null != vw) {
				TextView txt = (TextView) vw.findViewById(R.id.tv);
				txt.setText(object.toString());
			} 

		}else {

			T.showShort(MainTab.this, "FragmentMessage还未创建");
		}
	}

最后看看效果

               效果图1(首次打开时点击,FragmentMessage还未创建,所以不能把FragmentHome中TextView的值传给FragmentMessage

                效果图2(切换到消息Tab,FragmentMessage中TextView的值显示为Fragment Message

                效果图3(再次切换到首页Tab,点击,再切换到消息Tab,可以看到FragmentHome中TextView的值已经成功传递到FragmentMessage



Demo1下载地址:http://download.csdn.net/detail/yalinfendou/8539469

Demo2下载地址:http://download.csdn.net/detail/yalinfendou/8539655

猜你喜欢

转载自blog.csdn.net/yalinfendou/article/details/44677183