Fragment向父Activity傳值

 

Fragment中ide

public class VideoOneFragment extends Fragment implements View.OnClickListener {

    private View view;
    private Button mBut1;
    private Button mBut2;
    private Button mBut3;
    //接口
    CallBackValue callBackValue;
    /**
     * fragment與activity產生關聯是  回調這個方法
     */
    @Override
    public void onAttach(Context context) {
        // TODO Auto-generated method stub
        super.onAttach(context );
        //當前fragment從activity重寫了回調接口  獲得接口的實例化對象
        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;
        }
    }

    //定義一個回調接口
    public interface CallBackValue{
        public void SendMessageValue(String strValue);
    }
}

Activity中this

@Override
public void SendMessageValue(String strValue) {
    tv.setText(strValue);
}
相關文章
相關標籤/搜索