android中接口回调机制

来源:互联网 发布:java培训课 编辑:程序博客网 时间:2024/05/27 19:25

今天做一个关于接口回调机制,意思是注册之后并不会立马执行,而是在某个时机触发执行。举个例子,一个人有很多才能,琴棋书画,当我要求她画一幅画的时候,她才会用自己的技能画一幅画,并返还给我。一般情况下,接口回调可以放在异步中,防止在异步中操作ui界面。写个例子如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private Button callback;    private Button textView;    private String  url;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        setListener();    }    private void setListener() {        callback.setOnClickListener(this);    }    private void initView() {        callback = ((Button) findViewById(R.id.callback));        textView = ((Button) findViewById(R.id.text));    }    @Override    public void onClick(View view) {        new MyAsyncTask(new MyAsyncTask.Callback() {            @Override            public void call(String s) {                Log.d("通过接口回调过来的数据",s);                textView.setText(s);            }        }).execute(url);    }}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" tools:context=".MainActivity"    android:orientation="vertical"    >    <Button        android:id="@+id/callback"        android:text="" android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/text"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>

public class MyAsyncTask extends AsyncTask{    Callback callback;//接口对象    public MyAsyncTask(Callback callback) {//将接口对象作为异步的构造方法中的参数传入        this.callback=callback;    }    @Override    protected Object doInBackground(Object[] objects) {        callback.call(objects.toString());//将异步请求的数据放到接口中的方法中        return null;    }    interface Callback{//定义接口        void call(String s);    }}

0 0
原创粉丝点击