如图:
第一步:创建工程
集成友盟第三方,创建工程时,包名:com.umeng.soexample
第二步:添加回调Activity
主要是qq和微信的回调
第三步:导入jar和res
将main文件夹以及platform(选择你想使用的平台即可)文件下,对应的资源文件和jar放入你的工程!
配置Android Manifest XML
<!-- 权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 微信 -->
<activity
android:name=".wxapi.WXEntryActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<!-- QQ -->
<activity
android:name="com.tencent.tauth.AuthActivity"
android:launchMode="singleTask"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tencent100424468" />
</intent-filter>
</activity>
<activity
android:name="com.tencent.connect.common.AssistActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
Android6.0权限适配
请查看你的build.gradle
文件,如果 targetSdkVersion
小于或等于22,可以忽略这一步,如果大于或等于23,需要做权限的动态申请:
if(Build.VERSION.SDK_INT>=23){
String[] mPermissionList = new String[{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CALL_PHONE,
Manifest.permission.READ_LOGS,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.SET_DEBUG_APP,
Manifest.permission.SYSTEM_ALERT_WINDOW,
Manifest.permission.GET_ACCOUNTS,
Manifest.permission.WRITE_APN_SETTINGS};
ActivityCompat.requestPermissions(this,mPermissionList,123);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
}
初始化设置
自己创建一个类,集成AppLication
@Override
public void onCreate() {
super.onCreate();
UMConfigure.init(this,"5a12384aa40fa3551f0001d1"
,"umeng",UMConfigure.DEVICE_TYPE_PHONE,"");//58edcfeb310c93091c000be2 5965ee00734be40b580001a0
}
在onCreate方法中设置所需要的各个平台的appkey值
PlatformConfig.setWeixin("wxdc1e388c3822c80b", "3baf1193c85774b3fd9d18447d76cab0");
//豆瓣RENREN平台目前只能在服务器端配置
PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad","http://sns.whalecloud.com");
PlatformConfig.setYixin("yxc0614e80c9304c11b0391514d09f13bf");
PlatformConfig.setQQZone("100424468", "c7394704798a158208a74ab60104f0ba");
PlatformConfig.setTwitter("3aIN7fuF685MuZ7jtXkQxalyi", "MK6FEYG63eWcpDFgRYw4w9puJhzDl0tyuqWjZ3M7XJuuG7mMbO");
PlatformConfig.setAlipay("2015111700822536");
PlatformConfig.setLaiwang("laiwangd497e70d4", "d497e70d4c3e4efeab1381476bac4c5e");
PlatformConfig.setPinterest("1439206");
PlatformConfig.setKakao("e4f60e065048eb031e235c806b31c70f");
PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
PlatformConfig.setVKontakte("5764965","5My6SNliAaLxEm3Lyd9J");
PlatformConfig.setDropbox("oz8v5apet3arcdy","h7p2pjbzkkxt02a");
PlatformConfig.setYnote("9c82bf470cba7bd2f1819b0ee26f86c6ce670e9b");
开始第三方登录
在Activity中写代码;
获取用户资料
获取用户资料可以使用如下接口:
在需要的位置的点击事件中写
其中umAuthListener为授权回调,构建如下:
//QQ授权
private void initListenr() {
authListener = new UMAuthListener() {
/**
* @desc 授权开始的回调
* @param platform 平台名称
*/
@Override
public void onStart(SHARE_MEDIA platform) {
}
/**
* @desc 授权成功的回调
* @param platform 平台名称
* @param action 行为序号,开发者用不上
* @param data 用户资料返回
*/
@Override
public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
Toast.makeText(LoginActivity.this, platform + "登录成功了!!!", Toast.LENGTH_LONG).show();
}
/**
* @desc 授权失败的回调
* @param platform 平台名称
* @param action 行为序号,开发者用不上
* @param t 错误原因
*/
@Override
public void onError(SHARE_MEDIA platform, int action, Throwable t) {
Toast.makeText(LoginActivity.this, "失败:" + t.getMessage(), Toast.LENGTH_LONG).show();
}
/**
* @desc 授权取消的回调
* @param platform 平台名称
* @param action 行为序号,开发者用不上
*/
@Override
public void onCancel(SHARE_MEDIA platform, int action) {
Toast.makeText(LoginActivity.this, "取消了", Toast.LENGTH_LONG).show();
}
};
}
授权问题
第一次授权登录成功后,再次进行登录,回默认授权成功
如果需要每次登录都提示登录页面,需要在activity中添加一下代码:
UMShareConfig config = new UMShareConfig();
config.isNeedAuthOnGetUserInfo(true);
UMShareAPI.get(InfoDetailActivity.this).setShareConfig(config);
目前SDK默认设置为在Token有效期内登录不进行二次授权,如果有需要每次登录都弹出授权页面,便于切换账号的开发者可以添加上述代码
好了,不多说了,开始上代码了
LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, LoginView {
/**
* 登录
*/
private Button mBtnLogin;
/**
* 注册
*/
private Button mBtnReg;
/**
* 第三方QQ登录
*/
private Button mBtnQq;
/**
* 请输入手机号......
*/
private EditText mEdLoginMobile;
/**
* 请输入密码......
*/
private EditText mEdLoginPassword;
private LoginPresenter mLoginPresenter;
private String mMobile;
private String mPassword;
private Button mBtnWx;
UMAuthListener authListener;
/**
* 记住密码
*/
private CheckBox mCheckJz;
/**
* 自动登录
*/
private CheckBox mCheckLogin;
private SharedPreferences mSP;
private SharedPreferences.Editor mEdit;
private Intent mIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//初始化控件
initView();
mLoginPresenter = new LoginPresenter(this);
//6.0版本以上的动态权限
initPermission();
//QQ授权
initListenr();
//创建SharedPreferences储存数据
mSP = getSharedPreferences("config", MODE_PRIVATE);
boolean isCheck = mSP.getBoolean("isCheck", false);//是否记住密码
boolean isLogin = mSP.getBoolean("isLogin", false);//是否自动登录
mEdit = mSP.edit();
//判断是否记住密码
if (isCheck) {
mEdLoginMobile.setText(mSP.getString("mobile", mMobile));
mEdLoginPassword.setText(mSP.getString("password", mPassword));
mCheckJz.setChecked(true);
//判断自动登录多选状态
if (isLogin) {
mCheckLogin.setChecked(true);
//跳转
mIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(mIntent);
}
}
//复选框内容改变方法
initChecked();
}
//复选框内容改变方法
private void initChecked() {
mCheckLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//判断是否自动登录
if (mCheckLogin.isChecked()) {
mCheckJz.setChecked(true);
mEdit.putBoolean("isLogin", true).commit();
} else {
mEdit.putBoolean("isLogin", false).commit();
}
}
});
}
//QQ授权
private void initListenr() {
authListener = new UMAuthListener() {
/**
* @desc 授权开始的回调
* @param platform 平台名称
*/
@Override
public void onStart(SHARE_MEDIA platform) {
}
/**
* @desc 授权成功的回调
* @param platform 平台名称
* @param action 行为序号,开发者用不上
* @param data 用户资料返回
*/
@Override
public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
mIntent = new Intent(LoginActivity.this, MainActivity.class);
mIntent.putExtra("name", data.get("name"));
mIntent.putExtra("pri", data.get("profile_image_url"));
startActivity(mIntent);
finish();
Toast.makeText(LoginActivity.this, platform + "登录成功了!!!", Toast.LENGTH_LONG).show();
}
/**
* @desc 授权失败的回调
* @param platform 平台名称
* @param action 行为序号,开发者用不上
* @param t 错误原因
*/
@Override
public void onError(SHARE_MEDIA platform, int action, Throwable t) {
Toast.makeText(LoginActivity.this, "失败:" + t.getMessage(), Toast.LENGTH_LONG).show();
}
/**
* @desc 授权取消的回调
* @param platform 平台名称
* @param action 行为序号,开发者用不上
*/
@Override
public void onCancel(SHARE_MEDIA platform, int action) {
Toast.makeText(LoginActivity.this, "取消了", Toast.LENGTH_LONG).show();
}
};
}
//初始化控件
private void initView() {
mBtnLogin = (Button) findViewById(R.id.btn_login);
mBtnLogin.setOnClickListener(this);
mBtnReg = (Button) findViewById(R.id.btn_reg);
mBtnReg.setOnClickListener(this);
mBtnQq = (Button) findViewById(R.id.btn_qq);
mBtnQq.setOnClickListener(this);
mEdLoginMobile = (EditText) findViewById(R.id.ed_login_mobile);
mEdLoginPassword = (EditText) findViewById(R.id.ed_login_password);
mBtnWx = (Button) findViewById(R.id.btn_wx);
mBtnWx.setOnClickListener(this);
mCheckJz = (CheckBox) findViewById(R.id.check_jz);
mCheckJz.setOnClickListener(this);
mCheckLogin = (CheckBox) findViewById(R.id.check_login);
mCheckLogin.setOnClickListener(this);
}
//点击事件
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn_login://登录
mMobile = mEdLoginMobile.getText().toString().trim();
mPassword = mEdLoginPassword.getText().toString().trim();
mLoginPresenter.login(mMobile, mPassword);
break;
case R.id.btn_reg://注册
startActivity(new Intent(this, RegActivity.class));
finish();
break;
case R.id.btn_qq://QQ登录
initPermission();
UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
break;
case R.id.btn_wx://微信登录
initPermission();
UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
break;
}
}
/**
* mvp接口回调 访问数据成功
*
* @param result
*/
@Override
public void onLoginSuccess(String result) {
if (mCheckJz.isChecked()) {//记住密码
mEdit.putBoolean("isCheck", true);
mEdit.putString("mobile", mMobile);
mEdit.putString("password", mPassword);
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
mIntent = new Intent(this, MainActivity.class);
mIntent.putExtra("mobile", mMobile);
startActivity(mIntent);
finish();
mEdit.commit();
} else {//清除记住密码
mEdit.clear();
mEdit.commit();
}
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
mIntent = new Intent(this, MainActivity.class);
mIntent.putExtra("mobile", mMobile);
startActivity(mIntent);
finish();
}
/**
* mvp接口回调 访问数据失败
*
* @param error
*/
@Override
public void onLoginFailed(String error) {
if (error.equals("天呢!用户不存在")) {
Toast.makeText(this, "用户不存在,请去注册页面注册!!!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
/**
* QQ授权
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
}
/**
* 防止内存泄露
*/
@Override
protected void onDestroy() {
super.onDestroy();
mLoginPresenter.datechView();
}
//动态权限
private void initPermission() {
if (Build.VERSION.SDK_INT >= 23) {
String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
ActivityCompat.requestPermissions(this, mPermissionList, 123);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
}
}
LoginAndRegCallBack
public interface LoginAndRegCallBack {
void onSuccess(String result);
void onFailed(String error);
}
view层
public interface LoginView {
void onLoginSuccess(String result);
void onLoginFailed(String error);
}
model层
public class LoginModel {
public void login(String mobile, String password, final LoginAndRegCallBack callBack) {
String loginPath = "http://www.zhaoapi.cn/user/login?mobile="+mobile+"&password=" + password;
new HttpUtil().get(loginPath).result(new HttpUtil.HttpListener() {
@Override
public void success(String data) {
Gson gson = new Gson();
LoginAndRegBean bean = gson.fromJson(data, LoginAndRegBean.class);
if (bean.getCode().equals("0")) {
callBack.onSuccess(bean.getMsg());
}else {
callBack.onFailed(bean.getMsg());
}
}
@Override
public void fail() {
}
});
}
}
presenter层
public class LoginPresenter {
private LoginView mLoginView;
private LoginModel mLoginModel;
public LoginPresenter(LoginView loginView) {
mLoginView = loginView;
mLoginModel = new LoginModel();
}
//解绑
public void datechView(){
mLoginView = null;
}
public void login(String mobile,String password){
mLoginModel.login(mobile, password, new LoginAndRegCallBack() {
@Override
public void onSuccess(String result) {
mLoginView.onLoginSuccess(result);
}
@Override
public void onFailed(String error) {
mLoginView.onLoginFailed(error);
}
});
}
}
Utils联网工具类
public class HttpUtil {
private final int HTTP_SUCCESS=1000;//成功
private final int HTTP_FAIL=1001;//失败
public HttpUtil(){}
//get请求
public HttpUtil get(String url){
doHttp(url,"GET",null);
return this;
}
//post
public HttpUtil post(String url, String string){
doHttp(url,"POST",string);
return this;
}
//网络请求
private void doHttp(final String url,final String method,final String string){
new Thread(){
@Override
public void run() {
super.run();
try {
URL u=new URL(url);
HttpURLConnection connection= (HttpURLConnection) u.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(5000);
if("POST".equals(method)){
//post请求添加参数
PrintWriter writer=new PrintWriter(connection.getOutputStream());
writer.write(string);
writer.flush();
writer.close();
}
connection.connect();
int code=connection.getResponseCode();
Message message=Message.obtain();
if(code==HttpURLConnection.HTTP_OK){
message.what=HTTP_SUCCESS;
InputStream is = connection.getInputStream();
String data=convertStream2String(is);
message.obj=data;
}else{
message.what=HTTP_FAIL;
}
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case HTTP_SUCCESS://成功
String data= (String) msg.obj;
listener.success(data);
break;
case HTTP_FAIL://失败
listener.fail();
break;
}
}
};
private HttpListener listener;
public void result(HttpListener listener){
this.listener=listener;
}
public interface HttpListener{
void success(String data);
void fail();
}
public String convertStream2String(InputStream input){
ByteArrayOutputStream baos = new ByteArrayOutputStream();// 自带缓存的输出流
int len=-1;
byte [] buffer = new byte[512];
try {
while((len = input.read(buffer))!=-1){
baos.write(buffer, 0, len); // 将读到的字节,写入baos
}
return new String(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
注册入上登录代码一样
PullToRefresh+banner展示
Bean类
public class NewsBean {
private ResultBean result;
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public class ResultBean{
private int total;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
private List<DataList> data;
public List<DataList> getData() {
return data;
}
public void setData(List<DataList> data) {
this.data = data;
}
public class DataList{
private String title;
private String intor;
private String summary;
private String ctime;
private String media_name;
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCtime() {
return ctime;
}
public void setCtime(String ctime) {
this.ctime = ctime;
}
public String getMedia_name() {
return media_name;
}
public void setMedia_name(String media_name) {
this.media_name = media_name;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
private List<ImageBean> images;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIntor() {
return intor;
}
public void setIntor(String intor) {
this.intor = intor;
}
public List<ImageBean> getImages() {
return images;
}
public void setImages(List<ImageBean> images) {
this.images = images;
}
public class ImageBean{
private String u;
public String getU() {
return u;
}
public void setU(String u) {
this.u = u;
}
}
}
}
}
//数据展示+banner
public class ShowFragment extends Fragment {
private View mView;
private BGABanner mBgaBanner;
private PullToRefreshListView mPullList;
private String[] titleUrl = {
"http://www.zhaoapi.cn/images/quarter/ad1.png",
"http://www.zhaoapi.cn/images/quarter/ad2.png",
"http://www.zhaoapi.cn/images/quarter/ad3.png",
"http://www.zhaoapi.cn/images/quarter/ad4.png"
};
private String[] descUrl = {
"第十三界瑞丽模特大赛", "文化艺术节", "直播封面标准", "人气谁最高,金主谁最豪气"
};
private List<String> mTitle;
private List<String> mDesc;
private NewsPresenter mNewsPresenter;
private MyNewsAdapter mMyNewsAdapter;
private List<NewsBean.ResultBean.DataList> mDataBeans = new ArrayList<>();
private List<NewsBean.ResultBean.DataList> mLists = new ArrayList<>();
private int pager = 1;
private int total;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_show, container, false);
//初始化控件
initView(mView);
return mView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//初始化BGABanner数据
initBGABannerData();
initNewsData(pager);
}
private void initBGABannerData() {
mTitle = new ArrayList<>();
mDesc = new ArrayList<>();
//循环添加到集合
for (int i = 0; i < titleUrl.length; i++) {
mTitle.add(titleUrl[i]);//把数组里的值驾到集合里去
mDesc.add(descUrl[i]);
}
//设置值 里面要添加集合
mBgaBanner.setData(mTitle, mDesc);
//设置一个BGbanner的适配器 要给他加泛型 一个图片空间一个字符类型
mBgaBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
@Override
public void fillBannerItem(BGABanner banner, ImageView itemView, @Nullable String model, int position) {
//使用Picasso加载图片
Picasso.with(getActivity()).load(mTitle.get(position)).fit().into(itemView);
}
});
}
private void initView(View mView) {
mBgaBanner = (BGABanner) mView.findViewById(R.id.bga_banner);
mPullList = (PullToRefreshListView) mView.findViewById(R.id.pull_list);
mPullList.setMode(PullToRefreshBase.Mode.BOTH);
mMyNewsAdapter = new MyNewsAdapter(getActivity());
mPullList.setAdapter(mMyNewsAdapter);
mMyNewsAdapter.setList(mLists);
mPullList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mLists.clear();
initNewsData(1);
mMyNewsAdapter.notifyDataSetChanged();
mPullList.postDelayed(new Runnable() {
@Override
public void run() {
mPullList.onRefreshComplete();
}
},2000);
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
if (mLists.size() > total){
Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
}else {
pager++;
initNewsData(pager);
mMyNewsAdapter.notifyDataSetChanged();
mPullList.postDelayed(new Runnable() {
@Override
public void run() {
mPullList.onRefreshComplete();
}
},2000);
}
}
});
mPullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
NewsItemActivity.startWebActivity(getActivity(),mLists.get(i).getUrl());
}
});
}
private void initNewsData(int page) {
String newsPath = "http://feed.mix.sina.com.cn/api/roll/get?pageid=153&lid=2509&k=&num=20&page="+page;
new HttpUtil().get(newsPath).result(new HttpUtil.HttpListener() {
@Override
public void success(String data) {
Gson gson = new Gson();
NewsBean newsBean = gson.fromJson(data, NewsBean.class);
total = newsBean.getResult().getTotal();
List<NewsBean.ResultBean.DataList> lists = newsBean.getResult().getData();
mLists.addAll(lists);
mMyNewsAdapter.setList(mLists);
mMyNewsAdapter.notifyDataSetChanged();
mPullList.onRefreshComplete();//关闭
}
@Override
public void fail() {
}
});
}
}
适配器
public class MyNewsAdapter extends BaseAdapter {
private Context mContext;
private List<NewsBean.ResultBean.DataList> mDataBeans = new ArrayList<>();
public MyNewsAdapter(Context context) {
mContext = context;
}
public void setList(List<NewsBean.ResultBean.DataList> dataBeans) {
this.mDataBeans = dataBeans;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mDataBeans.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
MyViewHolder holder;
if (view == null) {
view = View.inflate(mContext, R.layout.news_item_view, null);
holder = new MyViewHolder();
holder.mCircleImageView = view.findViewById(R.id.c_imgicon);
holder.mTextViewTitle = view.findViewById(R.id.txt_news_title);
holder.mTextViewIntor = view.findViewById(R.id.txt_news_intro);
holder.mTextViewName = view.findViewById(R.id.txt_news_name);
view.setTag(holder);
} else {
holder = (MyViewHolder) view.getTag();
}
//Picasso.with(mContext).load(mDataBeans.get(i).getImages().get(i).getU()).fit().into(holder.mCircleImageView);
//图片非空判断,必须添加,不然会报 数组下标越界异常
if (mDataBeans.get(i).getImages() != null && mDataBeans.get(i).getImages().size() > 0) {
ImageLoader.getInstance().displayImage(mDataBeans.get(i).getImages().get(0).getU(), holder.mCircleImageView);
} else {
holder.mCircleImageView.setImageResource(R.drawable.p);
}
holder.mTextViewTitle.setText(mDataBeans.get(i).getTitle());
holder.mTextViewIntor.setText(mDataBeans.get(i).getIntor());
holder.mTextViewName.setText(mDataBeans.get(i).getMedia_name());
return view;
}
class MyViewHolder {
CircleImageView mCircleImageView;
TextView mTextViewTitle, mTextViewIntor, mTextViewName;
}
}
使用Zxing生成二维码
public class QRCodeFragment extends Fragment implements View.OnClickListener {
private View mView;
private View view;
private ImageView mQrImgicon;
private ImageView mQrImgicons;
/**
* 退出登录
*/
private Button mBtnQuit;
private String mName;
private String mPri;
private CircleImageView mCQrImgicon;
private TextView mTxtQrTexts;
private SharedPreferences mSP;
private SharedPreferences.Editor mEdit;
private String mMobile;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_qr, container, false);
initView(mView);
return mView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//取出QQ昵称的值
mName = getActivity().getIntent().getStringExtra("name");
mPri = getActivity().getIntent().getStringExtra("pri");
mMobile = getActivity().getIntent().getStringExtra("mobile");
ImageLoader.getInstance().displayImage(mPri, mCQrImgicon);
//判断是QQ昵称还是手机号
if (mName == null) {
mTxtQrTexts.setText(mMobile);
}else {
mTxtQrTexts.setText(mName);
}
//初始化 自动生成二维码
initZxingData();
mSP = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
mEdit = mSP.edit();
}
private void initZxingData() {
//判断是QQ昵称还是手机号,然后生成二维码
if (mName == null) {
QRTask qrTask = new QRTask(getActivity(), mQrImgicons, mMobile);
qrTask.execute(mMobile);
}else {
QRTask qrTask = new QRTask(getActivity(), mQrImgicons, mName);
qrTask.execute(mName);
}
}
//创建 QRTask 类,实现自动生成二维码
class QRTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<Context> mContextWeakReference;
private final WeakReference<ImageView> mImageViewWeakReference;
String mString;
//第一步,先创建构造方法
public QRTask(Context context, ImageView imageView, String string) {
//new 出实例
mContextWeakReference = new WeakReference<>(context);
mImageViewWeakReference = new WeakReference<>(imageView);
}
@Override
protected Bitmap doInBackground(String... strings) {
String string = strings[0];
if (TextUtils.isEmpty(string)) {
return null;
}
int size = 200;
return QRCodeEncoder.syncEncodeQRCode(string, size);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
mImageViewWeakReference.get().setImageBitmap(bitmap);
} else {
Toast.makeText(mContextWeakReference.get(), "二维码生成失败", Toast.LENGTH_SHORT).show();
}
}
}
private void initView(View mView) {
mQrImgicon = (ImageView) mView.findViewById(R.id.qr_imgicon);
mQrImgicons = (ImageView) mView.findViewById(R.id.qr_imgicons);
mBtnQuit = (Button) mView.findViewById(R.id.btn_quit);
mBtnQuit.setOnClickListener(this);
mQrImgicon.setOnClickListener(this);
mCQrImgicon = (CircleImageView) mView.findViewById(R.id.c_qr_imgicon);
mTxtQrTexts = (TextView) mView.findViewById(R.id.txt_qr_texts);
mCQrImgicon.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn_quit:
mEdit.clear();//清空所记住的内容
mEdit.commit();//关闭
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
break;
case R.id.qr_imgicon:
startActivity(new Intent(getActivity(), ScanActivity.class));
getActivity().finish();
break;
case R.id.c_qr_imgicon:
Toast.makeText(getActivity(), mPri, Toast.LENGTH_SHORT).show();
break;
}
}
}
自定义TextView实现跑马灯
@SuppressLint("AppCompatCustomView")
public class MyTextView extends TextView {
public MyTextView(Context context) {
this(context,null);
}
public MyTextView(Context context, AttributeSet attrs) {
this(context, attrs,-1);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean isFocused() {
return true;
}
}
//布局
<com.umeng.soexample.customer.MyTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#77ef1717"
android:ellipsize="marquee"
android:focusable="true"
android:layout_margin="5dp"
android:focusableInTouchMode="true"
android:gravity="center"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="内容自定义"
android:textColor="#ffffff"
android:textSize="24sp" />