/*
* Copyright 2017 GcsSloop
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Last modified 2017-03-11 22:24:54
*
* GitHub: https://github.com/GcsSloop
* Website: http://www.gcssloop.com
* Weibo: http://weibo.com/GcsSloop
*/
package com.gcssloop.diycode.base.app;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gcssloop.diycode_sdk.log.Logger;
public class ViewHolder {
private SparseArray<View> mViews;
private View mRootView;
public ViewHolder(LayoutInflater inflater, ViewGroup parent, int layoutId) {
this.mViews = new SparseArray<View>();
mRootView = inflater.inflate(layoutId, parent, false);
}
/**
* 通过View的id来获取子View
*
* @param resId view的id
* @param <T> 泛型
* @return 子View
*/
public <T extends View> T get(int resId) {
View view = mViews.get(resId);
//如果该View没有缓存过,则查找View并缓存
if (view == null) {
view = mRootView.findViewById(resId);
mViews.put(resId, view);
}
if (view == null){
Logger.e("View == null");
}
return (T) view;
}
/**
* 获取布局View
*
* @return 布局View
*/
public View getRootView() {
return mRootView;
}
/**
* 设置文本
*
* @param res_id view 的 id
* @param text 文本内容
* @return 是否成功
*/
public boolean setText(CharSequence text, @NonNull int res_id) {
try {
TextView textView = get(res_id);
textView.setText(text);
return true;
} catch (Exception e) {
return false;
}
}
public boolean setText(@NonNull int res_id, CharSequence text) {
return setText(text, res_id);
}
public void loadImage(Context context, String url, int res_id) {
ImageView imageView = get(res_id);
String url2 = url;
if (url.contains("diycode"))
url2 = url.replace("large_avatar", "avatar");
Glide.with(context).load(url2).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
}
/**
* 设置监听器
*
* @param l 监听器
* @param ids view 的 id
*/
public void setOnClickListener(View.OnClickListener l, int... ids) {
if (ids == null) {
return;
}
for (int id : ids) {
get(id).setOnClickListener(l);
}
}
}