Fragment pass value to parent Activity

 

Fragment

public class VideoOneFragment extends Fragment implements View.OnClickListener {

    private View view;
    private Button mBut1;
    private Button mBut2;
    private Button mBut3;
    //interface
    CallBackValue callBackValue;
    /**
     * The association between fragment and activity is to call back this method
     */
    @Override
    public void onAttach(Context context) {
        // TODO Auto-generated method stub
        super.onAttach(context );
        //The current fragment rewrites the callback interface from the activity to get the instantiated object of the interface
        callBackValue =(CallBackValue) getActivity();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_video_one, container, false);
        initView(inflate);
        return inflate;
    }

    private void initView(View inflate) {
        mBut1 = (Button) inflate.findViewById(R.id.but1);
        mBut1.setOnClickListener(this);
        mBut2 = (Button) inflate.findViewById(R.id.but2);
        mBut2.setOnClickListener(this);
        mBut3 = (Button) inflate.findViewById(R.id.but3);
        mBut3.setOnClickListener(this);
        callBackValue.SendMessageValue("0");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.but1:
                callBackValue.SendMessageValue("1");
                break;
            case R.id.but2:
                callBackValue.SendMessageValue("2");
                break;
            case R.id.but3:
                callBackValue.SendMessageValue("3");
                break;
        }
    }

    //Define a callback interface
    public interface CallBackValue{
        public void SendMessageValue(String strValue);
    }
}

in Activity

@Override
public void SendMessageValue(String strValue) {
    tv.setText(strValue);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325680767&siteId=291194637