Android Fragment接口传值

来源:互联网 发布:学生怒骂日本记者知乎 编辑:程序博客网 时间:2024/06/13 14:11

Fragment_A.class

package cn.bgs.fragment_interface;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;


public class Fragment_A extends Fragment {
private Button mBtn;
private Fragment_Call call;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=View.inflate(getActivity(), R.layout.fragment_a, null);
mBtn=(Button) v.findViewById(R.id.mBtn);
mBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
call.call();
}
});
return v;
}
public void getInter(Fragment_Call call){
this.call=call;
}
}


Fragment_B.class

package cn.bgs.fragment_interface;


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


public class Fragment_B extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=View.inflate(getActivity(), R.layout.fragment_b, null);
return v;
}
}


Fragment_Call.class

package cn.bgs.fragment_interface;


public interface Fragment_Call {
public void call();
}


XML

activity_main.XML

<LinearLayout 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"
    tools:context=".MainActivity" 
    android:orientation="vertical">
<LinearLayout 
   android:id="@+id/group"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   />
</LinearLayout>

fragment_a.XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button 
        android:id="@+id/mBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击"
        />
    <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        />

</LinearLayout>


fragment_b.XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这里是Bfragment"
        android:textSize="30sp"
        />


</LinearLayout>