您的位置:首页 > 移动开发 > Android开发

android中接口回调机制

2015-11-22 09:45 344 查看
今天做一个关于接口回调机制,意思是注册之后并不会立马执行,而是在某个时机触发执行。举个例子,一个人有很多才能,琴棋书画,当我要求她画一幅画的时候,她才会用自己的技能画一幅画,并返还给我。一般情况下,接口回调可以放在异步中,防止在异步中操作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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: