个人喜欢复杂东西简单化,这里就不做理论性描述,实现这方法当然很多,比如可以使用广播,实现Activity回调再调用Fragment等,这里是直接Activity回调到Fragment
- 效果流程图
2.实现流程
2.1 接口类,如CallBackInterface.java
package com.cyy.test; public interface CallBackInterface<T> { void onCallBack(T var); }
2.2 Activity接口方法设置
package com.cyy.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Activity2 extends Activity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity2); Button button=(Button)findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button: //执行回调 instance.callBacker.onCallBack("来之Activity2回调"); if (instance!=null){ instance.finish(); instance=null; } finish(); break; } } //////////////////////////// //第二步 //设置单例 public static Activity2 instance; public static Activity2 getInstance(){ if (instance==null){ instance=new Activity2(); } return instance; } //设置回调方法 CallBackInterface <String> callBacker; public void onCallBack(CallBackInterface<String> callBacker) { this.callBacker=callBacker; } //////////////////////////////// }
2.3 Activity1中Fragment接口方法定义,打开Actvity2界面并设置回调方法
package com.cyy.test; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; public class MyFragment extends Fragment implements View.OnClickListener{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment_my, container, false); Button button=(Button)view.findViewById(R.id.button); button.setOnClickListener(this); return view; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button: //点击跳转到到Activity2 startActivity(new Intent(getActivity(), Activity2.class)); //接口回调方法定义 callBack(); break; } } //////////////////////////////////////////// //第三步 //接口定义 public void callBack() { Activity2.getInstance().onCallBack(new CallBackInterface<String>() { @Override public void onCallBack(String var) { Toast.makeText(getActivity(), "成功回调" + var, Toast.LENGTH_LONG).show(); } }); } ///////////////////////////////////////////// }
3.Demo代码,开发工具和版本号Android Sutdio 1.2.0.0
时间: 2024-11-05 17:27:26