Android使用回调接口

Android使用回调接口

  • Android使用回调接口
    • adapter与context之间建立回调
      • adapter里面需要执行的操作
      • context里面需要执行的操作
      • 源码如下

adapter与context之间建立回调

adapter里面可触发一下按键事件,然后这个按键事件必须在context进行响应,这里有一种处理方法就是使用接口回调,顾名思义,接口回调就是暴露自己的接口,让其他对象来实现自己的接口。这里就是adapter需要定义并暴露自己的接口,然后让context来实现自己的接口。

adapter里面需要执行的操作

  • 首先adapter里面自定义一个接口,接口里面的方法自己定义,不需要方法的主体,只要有方法名字,方法形参,方法返回类型就可以了。例如下面:

    public interface ClickEvent{
        void add();
        void del(int position);
    }
  • 然后adapter里面需要定义一个接口(这里定义的接口不需要初始化,初始化工作交给context,这种说法也不正确),并在自己的点击事件里面调用接口里面的方法,例如下面:

    ClickEvent mClickEvent;
    //这里是为item里面的按钮设置点击事件,但是点击之后的事件具体怎么操作这里不需要知道,否者接口回调就没意义了。
    viewholder.addordel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(((int)v.getTag())==2)//这里是为了区分此次点击事件到底执行添加还是删除操作
                {
                    mClickEvent.add();
                    Log.i(TAG, "onClick: login");
                }
                else
                {
                    mClickEvent.del(position);
                }
            }
        });
  • adapter自己定义了在哪儿调用接口,但是并没有暴露这个接口,所以外面的context并找不到这个接口,所以这里写一个方法暴露接口,顺便初始化我们建立的 mClickEvent,例如下面:
    public void setClickEvent(ClickEvent event){
        mClickEvent=event;
    }

context里面需要执行的操作

  • adapter里面需要暴露的接口已经有了,我们只需要在context调用并实现接口就行了,因为这里是使用的adapter,所以在context里面找到我们建立的adapter并调用里面的暴露接口方法这里就是上面的setClickEvent方法),例如下面:
    mReAdapter.setClickEvent(new AccountReAdapter.ClickEvent() {
            @Override
            public void add() {
                mSsoHandler.authorize(new AuthListener());
                Log.i(TAG, "add: callback");
            }

            @Override
            public void del(int position) {
                mBeanList.remove(position);
                mReAdapter.notifyDataSetChanged();
                mAccessToken = new Oauth2AccessToken();
            }
        });

源码如下:


这里的源码是在项目中提取出来的,所以有些复杂。如果心情烦躁,可以不看。
adapter代码

package com.hskj.damnicomniplusvic.weiqian.adapter;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.hskj.damnicomniplusvic.weiqian.Bean.AccountBean;
import com.hskj.damnicomniplusvic.weiqian.R;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

/**
 * Created by DAMNICOMNIPLUSVIC on 2017/1/4.
 */

public class AccountReAdapter extends RecyclerView.Adapter  {
    List mList;
    ClickEvent mClickEvent;
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.account_recycle_item, parent, false);
        return new AccountViewholder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        AccountViewholder viewholder= (AccountViewholder) holder;
        AccountBean bean=mList.get(position);
        Glide.with(holder.itemView.getContext()).load(bean.getAvatar_large()).into(viewholder.headimg);
        viewholder.nickname.setText(bean.getScreen_name());
        if(bean.getScreen_name()!=null&&bean.getScreen_name()!="") {
            viewholder.addordel.setBackgroundResource(R.drawable.fensi);
            viewholder.addordel.setTag(1);
        }else
        {
            viewholder.addordel.setBackgroundResource(R.drawable.tianjia);
            viewholder.addordel.setTag(2);
        }
        viewholder.addordel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(((int)v.getTag())==2)
                {
                    mClickEvent.add();
                    Log.i(TAG, "onClick: login");
                }
                else
                {
                    mClickEvent.del(position);
                }
            }
        });
    }

    public void setList(List list){
        mList=list;
        notifyDataSetChanged();
    }
    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    static class AccountViewholder extends RecyclerView.ViewHolder{
        @Bind(R.id.account_item_nickname)TextView nickname;
        @Bind(R.id.account_item_headimg)ImageView headimg;
        @Bind(R.id.account_item_add_del)Button addordel;
        public AccountViewholder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

    public interface ClickEvent{
        void add();
        void del(int position);
    }
    public void setClickEvent(ClickEvent event){
        mClickEvent=event;
    }
}

context代码:

package com.hskj.damnicomniplusvic.weiqian.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hskj.damnicomniplusvic.weiqian.Bean.AccountBean;
import com.hskj.damnicomniplusvic.weiqian.R;
import com.hskj.damnicomniplusvic.weiqian.adapter.AccountReAdapter;
import com.hskj.damnicomniplusvic.weiqian.customview.RoundImageView;
import com.hskj.damnicomniplusvic.weiqian.utils.Constant;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.sina.weibo.sdk.openapi.models.User;
import com.sina.weibo.sdk.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


public class AccountFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match

    String TAG="AccountFragment";
    @Bind(R.id.account_description) TextView description;
    @Bind(R.id.account_fans) TextView fans;
    @Bind(R.id.account_favourite) TextView favourite;
    @Bind(R.id.account_follow) TextView follow;
    @Bind(R.id.account_gender) TextView gender;
    @Bind(R.id.account_headimage) RoundImageView headimage;
    @Bind(R.id.account_location) TextView location;
    @Bind(R.id.account_nickname) TextView nickname;
    @Bind(R.id.account_states) TextView states;
    @Bind(R.id.account_recycleview) RecyclerView mRecyclerView;
    private List mBeanList;
    private AccountReAdapter mReAdapter;
    /** 封装了 "access_token","expires_in","refresh_token",并提供了他们的管理功能  */
    private Oauth2AccessToken mAccessToken;
    private AuthInfo mAuthInfo;
    /** 注意:SsoHandler 仅当 SDK 支持 SSO 时有效 */
    private SsoHandler mSsoHandler;
    private UsersAPI mUsersapi;


    public AccountFragment() {
        // Required empty public constructor
    }


    // TODO: Rename and change types and number of parameters
    public static AccountFragment newInstance() {
        AccountFragment fragment = new AccountFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_account, container, false);
        ButterKnife.bind(this,view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        AccountBean footer=new AccountBean();
        footer.setScreen_name("");
        footer.setAvatar_large("");
        mBeanList=new ArrayList<>();
        mBeanList.add(footer);
        mReAdapter=new AccountReAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mReAdapter);
        mReAdapter.setList(mBeanList);
        mReAdapter.setClickEvent(new AccountReAdapter.ClickEvent() {
            @Override
            public void add() {
                mSsoHandler.authorize(new AuthListener());
                Log.i(TAG, "add: callback");
            }
            @Override
            public void del(int position) {
                mBeanList.remove(position);
                mReAdapter.notifyDataSetChanged();
                mAccessToken = new Oauth2AccessToken();
            }
        });
        // 创建微博实例
        //mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);
        // 快速授权时,请不要传入 SCOPE,否则可能会授权不成功
        mAuthInfo=new AuthInfo(this.getActivity(), Constant.APP_KEY,Constant.REDIRECT_URL,Constant.SCOPE);
        mSsoHandler = new SsoHandler(this.getActivity(), mAuthInfo);
    }


    /**
     * 当 SSO 授权 Activity 退出时,该函数被调用。
     *
     * @see {@link Activity#onActivityResult}
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: "+requestCode+"\tresultCode"+resultCode);
        // SSO 授权回调
        // 重要:发起 SSO 登陆的 Activity 必须重写 onActivityResults
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    /**
     * 微博认证授权回调类。
     * 1. SSO 授权时,需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后,
     *    该回调才会被执行。
     * 2. 非 SSO 授权时,当授权结束后,该回调就会被执行。
     * 当授权成功后,请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {
        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            //从这里获取用户输入的 电话号码信息
            Log.i(TAG, "onComplete: "+mAccessToken);
            String  phoneNum =  mAccessToken.getPhoneNum();
            if (mAccessToken.isSessionValid()) {
                // 显示 Token
                mUsersapi=new UsersAPI(getContext(),Constant.APP_KEY,mAccessToken);
                mUsersapi.show(mAccessToken.getUid(),mListener);
                // 保存 Token 到 SharedPreferences
                Toast.makeText(getContext(),
                        R.string.weibosdk_demo_toast_auth_success, Toast.LENGTH_SHORT).show();
            } else {
                // 以下几种情况,您会收到 Code:
                // 1. 当您未在平台上注册的应用程序的包名与签名时;
                // 2. 当您注册的应用程序包名与签名不正确时;
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = getString(R.string.weibosdk_demo_toast_auth_failed);
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
                Log.i(TAG, "onComplete: "+message);
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(getContext(),
                    R.string.weibosdk_demo_toast_auth_canceled, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(getContext(),
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 微博 OpenAPI 回调接口。
     */
    private RequestListener mListener = new RequestListener() {
        @Override
        public void onComplete(String response) {
            Log.i(TAG, "onComplete: "+response);
            if (!TextUtils.isEmpty(response)) {
                // 调用 User#parse 将JSON串解析成User对象
                User user = User.parse(response);
                if (user != null) {
                    Toast.makeText(getContext(),
                            "获取User信息成功,用户昵称:" + user.screen_name,
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getContext(), response, Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            LogUtil.e(TAG, e.getMessage());
            ErrorInfo info = ErrorInfo.parse(e.getMessage());
            Toast.makeText(getContext(), info.toString(), Toast.LENGTH_LONG).show();
        }
    };
}

你可能感兴趣的:(Android,java,code)