【安卓学习笔记】Activity与Fragment通信——Fragment发送到Activity

要点:

  • Fragment中定义内部接口和方法;
  • Activity继承该接口,并实现该接口的方法(方法中处理Fragment传过来的数据);
  • Fragment中获得Activity对象,并调用接口中方法。
  • 核心思想:接口的回调

效果图:

效果图

源码:

1、自定义的fragment布局文件fragment.xml




    

    

2、fragment源码

public class myFragment extends Fragment {

    private EditText et01;
    private Button btn01;
    public sendDataToActivity mySendDataToActivity;

    // 定义一个内部接口,接口中方法用于处理发送给activity的数据
    public interface sendDataToActivity {
        public void send(String str);
    }

    /*
     * fragment生命周期中,onAttach在与activity关联后,首先执行, 并且,在这里会返回一个activity对象,
     * 获得activity后,即可用于后面调用activity中方法
     */
    @Override
    public void onAttach(Activity activity) {
        mySendDataToActivity = (sendDataToActivity) activity;
        super.onAttach(activity);
    }

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

        View view = inflater.inflate(R.layout.fragment, container, false);

        et01 = (EditText) view.findViewById(R.id.et1);
        btn01 = (Button) view.findViewById(R.id.btn);

        btn01.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // 调用activity中实现的接口方法
                mySendDataToActivity.send(et01.getText().toString());
            }
        });

        return view;
    }

}

3、MainActivity的布局文件activity_main.xml


    
          
        

4、MainActivity

//继承接口
public class MainActivity extends Activity implements sendDataToActivity {

    private TextView tv01;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tv01 = (TextView) findViewById(R.id.tv1);

        // 实例化自定义的fragment
        myFragment fragment = new myFragment();

        // 后面和动态加载fragment一样
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction beginTransaction = fragmentManager
                .beginTransaction();
        // 将fragment添加到activity的布局中
        beginTransaction.add(R.id.layout, fragment);
        beginTransaction.addToBackStack(null);
        beginTransaction.commit();

    }
    
    //实现接口中方法,并处理fragment传过来的数据
    @Override
    public void send(String str) {
        tv01.setText(tv01.getText().toString()+str);
    }
}

你可能感兴趣的:(【安卓学习笔记】Activity与Fragment通信——Fragment发送到Activity)