fragment实现点击按钮值回传给activity

TrainingFragment.java

public class TrainingFragment extends Fragment implements View.OnClickListener{
    @BindView(R.id.begin)
     Button btnBegin;
        //定义用来与外部activity交互,获取到宿主activity
    private FragmentInteraction listterner;

    // 定义了所有activity必须实现的接口方法
    public interface FragmentInteraction {
        void process(int str,int str2);
    }

    // 当FRagmen被加载到activity的时候会被回调
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if(activity instanceof FragmentInteraction) {
            listterner = (FragmentInteraction)activity; // 获取到宿主activity并赋值
        } else{
            throw new IllegalArgumentException("activity must implements FragmentInteraction");
        }
    }


    //把传递进来的activity对象释放掉
    @Override
    public void onDetach() {
        super.onDetach();
        listterner = null;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        ...//这里写你的fragment布局实现内容
        return view;
    }
    @Override
    public void onClick(View v) {
        int id  = v.getId();
        switch (id) {
            case R.id.begin:
                listterner.process(4,0); // 执行回调
                break;
        }
    }
}

 

主activity

首先你的activity需要写上implements TrainingFragment.FragmentInteraction
// 实现接口,实现回调
@Override
public void process(int str,int str2) {//str,str2值为fragment回传值,fragment按钮点击则会触发这个回调方法
    if (str != 0) {
        ConstantConfig.DEVICE_STATUS_DO =str;
        ConstantConfig.DEVICE_TEAM_COURSE_TYPE = str2;
    }else {
        configDo=str;
        courType=str2;
        
    }
}

你可能感兴趣的:(Android开发)