implementation 'com.google.code.gson:gson:2.2.4'
implementation 'com.android.support:design:27.1.1' (解决导入xrecycle报错的)
implementation 'com.jcodecraeer:xrecyclerview:1.5.9'
//自定义View梯形的 布局
public class UITiXing extends ViewGroup {
public UITiXing(Context context) {
this(context,null);
}
public UITiXing(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public UITiXing(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//测量子View的宽高,只有Viewgroup中有这个方法 直接继承View没有这个方法
measureChildren(widthMeasureSpec,heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//获取屏幕的高度和宽度
int measuredHeight = getMeasuredHeight();
int v_width = getMeasuredWidth()/3;
int measuredWidth = getMeasuredWidth();
//获取子空间的个数
int childCount = getChildCount();
//顶一个临时的高度
int startHeight=0;
int startWidth=0;
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);//给子控件定义位置
if (i%3==0){
v.setBackgroundColor(Color.RED);
}else if (i%3==1){
v.setBackgroundColor(Color.GREEN);
}else if (i%3==2){
v.setBackgroundColor(Color.BLUE);
}
//如果startwidth>屏幕宽度就
if (startWidth>=measuredWidth){
startWidth=0;
}
v.layout(startWidth,startHeight,startWidth+v_width,startHeight+v.getMeasuredHeight());
startHeight+=v.getMeasuredHeight();
startWidth+=v_width;
//动画
if (i==childCount-1){
AnimatorSet set = new AnimatorSet();
ObjectAnimator animatorX=ObjectAnimator.ofFloat(v,"translationX",new float[]{v_width,0});
ObjectAnimator animatorY=ObjectAnimator.ofFloat(v,"translationY",new float[]{-startHeight,0});
set.playTogether(animatorX,animatorY);
set.setDuration(2000);
set.start();
}
//给每个空间添加点击和长安监听事件
final int finalI = i;
v.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnItemTextClick.onTextClick(finalI);
}
});
//长安
v.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mOnItemTextLongClick.onTextLongClick(v);
return true;
}
});
}
}
//添加点击事件
public interface OnItemTextClick{
void onTextClick(int finalI);
}
private OnItemTextClick mOnItemTextClick;
public void setmOnItemTextClick(OnItemTextClick mOnItemTextClick) {
this.mOnItemTextClick = mOnItemTextClick;
}
//添加长按点击事件
public interface OnItemTextLongClick{
void onTextLongClick(View finalI);
}
private OnItemTextLongClick mOnItemTextLongClick;
public void setmOnItemTextLongClick(OnItemTextLongClick mOnItemTextLongClick) {
this.mOnItemTextLongClick = mOnItemTextLongClick;
}
}
//MainActivity 的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.MainActivity">
<com.example.moni01.uiview.UITiXing
android:id="@+id/tixing"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
>
</com.example.moni01.uiview.UITiXing>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="三色梯形" />
<Button
android:id="@+id/btn_add"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:text="+" />
</RelativeLayout>
//MAintivity的代码 动态添加和点击删除跳转
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private UITiXing tixing;
private Button btn_add;
int i=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
tixing = (UITiXing) findViewById(R.id.tixing);
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);
//点击跳转
tixing.setmOnItemTextClick(new UITiXing.OnItemTextClick() {
@Override
public void onTextClick(int finalI) {
TextView text = (TextView) tixing.getChildAt(finalI);
String s = text.getText().toString();
//传值http://ttpc.dftoutiao.com/jsonpc/refresh?type=5010
Integer value01 = Integer.valueOf(s);
int value02=value01+5010;
String url="http://ttpc.dftoutiao.com/jsonpc/refresh?type=";
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
intent.putExtra("url",url);
intent.putExtra("value",value02);
startActivity(intent);
}
});
//长安删除
tixing.setmOnItemTextLongClick(new UITiXing.OnItemTextLongClick() {
@Override
public void onTextLongClick(View v) {
tixing.removeView(v);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
TextView textView = new TextView(this);
textView.setGravity(Gravity.CENTER);
textView.setText(i+"");
textView.setTextSize(30);
i++;
tixing.addView(textView);
break;
}
}
}
//model层接口
public interface LoginModelInt {
void getJsonS(String url,GetStringToView getStringToView);
public interface GetStringToView{
void getViewString(String replace);
}
}
//model层实现类
public class LoginModelImp implements LoginModelInt {
OkhttpUtils okhttpUtils = OkhttpUtils.getOkhttpUtils();
private Context context;
private final Dao dao;
public LoginModelImp(Context context) {
this.context = context;
dao = new Dao(context);
}
@Override
public void getJsonS(final String url, final GetStringToView getStringToView) {
okhttpUtils.getSuccessJson(url, new OkhttpUtils.Fun1() {
@Override
public void getResultJson(String s) {
String replace = s.replace("null(", "").replace(")", "");
Log.i("Url",replace);
dao.add(url,replace);//离线加载到数据库
getStringToView.getViewString(replace);
}
});
}
}
//view层接口
public interface LoginVIewInt {
void setViewString(Bean bean);
void NotNetWork();
}
//跳转后MVP搭建数据获取刷新页面
//P层代码
public class LoginPresenter {
private LoginVIewInt mloginVIewInt;
private final LoginModelInt loginModelInt;
private final Dao dao;
public LoginPresenter(LoginVIewInt mloginVIewInt,Context context) {
loginModelInt = new LoginModelImp(context);//多态的方式连接model层
dao = new Dao(context);
this.mloginVIewInt = mloginVIewInt;//构造联系v层
}
public void getJsonString(String url,Context context) {
boolean connNetWork = NetWork.isConnNetWork(context);
if (connNetWork){//有网络的时候
loginModelInt.getJsonS(url, new LoginModelInt.GetStringToView() {
@Override
public void getViewString(String replace) {
Gson gson = new Gson();
Bean bean = gson.fromJson(replace, Bean.class);
mloginVIewInt.setViewString(bean);
}
});
}else {//没网的时候
mloginVIewInt.NotNetWork();
String s = dao.select(url);
//判断是还不是空 第一次添加时没有数据的
if (!TextUtils.isEmpty(s)){
Gson gson = new Gson();
Bean bean = gson.fromJson(s, Bean.class);
mloginVIewInt.setViewString(bean);
}
}
}
}
//跳转到Login层页面代码
public class LoginActivity extends AppCompatActivity implements LoginVIewInt {
private XRecyclerView mRecy;
private Integer int1;
boolean down = false;
private List<Bean.DataBean> data;
private List<Bean.DataBean> datas=new ArrayList<>();
private String split;
private int value;
private String path;
private String url;
private RecyViewAdapter recyViewAdapter;
private LoginPresenter loginPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//得到穿过老的url
Intent intent = getIntent();
path = intent.getStringExtra("url");
value = intent.getIntExtra("value",0);
//Log.i("TAG", "onCreate: "+url);
initView();
}
private void initView() {
mRecy = findViewById(R.id.recy);
mRecy.setLayoutManager(new LinearLayoutManager(LoginActivity.this,LinearLayoutManager.VERTICAL,false));
mRecy.addItemDecoration(new DividerItemDecoration(LoginActivity.this,DividerItemDecoration.VERTICAL));
url = path+value;
mRecy.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
//下啦
down=true;
datas.clear();
value++;
url =path+value;
loginPresenter.getJsonString(url,LoginActivity.this);
}
@Override
public void onLoadMore() {
//上滑
down=false;
value++;
url=path+value;
loginPresenter.getJsonString(url,LoginActivity.this);
}
});
//P层逻辑再查找id后面
loginPresenter = new LoginPresenter(this,LoginActivity.this);
loginPresenter.getJsonString(url,this);
}
@Override
public void setViewString(Bean bean) {
data = bean.getData();//返回的集合
datas.addAll(data);
if (down){
mRecy.refreshComplete();
}else {
mRecy.loadMoreComplete();
}
//属性适配器
if (recyViewAdapter==null) {
recyViewAdapter = new RecyViewAdapter(LoginActivity.this, datas);
mRecy.setAdapter(recyViewAdapter);
}else {
recyViewAdapter.notifyDataSetChanged();
}
//删除
recyViewAdapter.setmOnItemClickRemove(new RecyViewAdapter.OnItemClickRemove() {
@Override
public void onItemRemove(final int position) {
new AlertDialog.Builder(LoginActivity.this).setTitle("确定删除吗???")
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("ddd", "onClick: "+position);
datas.remove(position-1);
recyViewAdapter.notifyItemRemoved(position);
}
}).setPositiveButton("取消",null).show();
}
});
}
@Override
public void NotNetWork() {
Toast.makeText(this, "当前没有网络...", Toast.LENGTH_SHORT).show();
}
}
//RecyView适配器代码
public class RecyViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Bean.DataBean> data;
public static final int ONE = 100;
public static final int THREE = 300;
public RecyViewAdapter(Context context, List<Bean.DataBean> data) {
this.data = data;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == THREE) {
View view1 = LayoutInflater.from(context).inflate(R.layout.item2, parent, false);
return new ViewHolder2(view1);
} else {
View view2 = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new ViewHolder1(view2);
}
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
if (getItemViewType(position)==THREE){
//当第三个的时候
ViewHolder2 holder2 = (ViewHolder2) holder;
Glide.with(context).load(data.get(position).getMiniimg().get(0).getSrc()).into(holder2.mImage1Item2);
holder2.mText1Item2.setText(data.get(position).getDate());
holder2.mText2Item2.setText(data.get(position).getIsrecom()+"");
holder2.mTextTitleItem2.setText(data.get(position).getBrief());
holder2.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnItemClickRemove.onItemRemove(layoutPosition);
}
});
}else {
//第一个 第二个的时候
ViewHolder1 holder1 = (ViewHolder1) holder;
Glide.with(context).load(data.get(position).getMiniimg().get(0).getSrc()).into(holder1.mImage1Item);
Glide.with(context).load(data.get(position).getMiniimg().get(0).getSrc()).into(holder1.mImage2Item);
Glide.with(context).load(data.get(position).getMiniimg().get(0).getSrc()).into(holder1.mImage3Item);
holder1.mTextItem.setText(data.get(position).getBrief());
holder1.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int layoutPosition = holder.getLayoutPosition();
mOnItemClickRemove.onItemRemove(layoutPosition);
}
});
}
}
@Override
public int getItemCount() {
return data.size();
}
@Override
public int getItemViewType(int position) {
if (position % 3 == 0) {
return THREE;
}
return ONE;
}
public class ViewHolder1 extends RecyclerView.ViewHolder {
private TextView mTextItem;
private ImageView mImage1Item;
private ImageView mImage2Item;
private ImageView mImage3Item;
public ViewHolder1(View itemView) {
super(itemView);
mTextItem = itemView.findViewById(R.id.text_item);
mImage1Item = itemView.findViewById(R.id.image1_item);
mImage2Item = itemView.findViewById(R.id.image2_item);
mImage3Item = itemView.findViewById(R.id.image3_item);
}
}
public class ViewHolder2 extends RecyclerView.ViewHolder {
private ImageView mImage1Item2;
private TextView mTextTitleItem2;
private TextView mText1Item2;
private TextView mText2Item2;
public ViewHolder2(View itemView) {
super(itemView);
mImage1Item2 = itemView.findViewById(R.id.image1_item2);
mTextTitleItem2 = itemView.findViewById(R.id.text_title_item2);
mText1Item2 = itemView.findViewById(R.id.text1_item2);
mText2Item2 = itemView.findViewById(R.id.text2_item2);
}
}
//点击删除
public interface OnItemClickRemove{
void onItemRemove(int position);
}
private OnItemClickRemove mOnItemClickRemove;
public void setmOnItemClickRemove(OnItemClickRemove mOnItemClickRemove) {
this.mOnItemClickRemove = mOnItemClickRemove;
}
}
//多条目的页面xml 3个图片代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/image1_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="2dp"
app:srcCompat="@mipmap/ic_launcher" />
<ImageView
android:id="@+id/image2_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="2dp"
app:srcCompat="@mipmap/ic_launcher" />
<ImageView
android:id="@+id/image3_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="2dp"
app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>
</LinearLayout>
//1个图片代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image1_item2"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_weight="2"
app:srcCompat="@mipmap/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:orientation="vertical">
<TextView
android:id="@+id/text_title_item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="TextView" />
<LinearLayout
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_weight="2"
android:orientation="horizontal">
<TextView
android:id="@+id/text1_item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="TextView" />
<TextView
android:id="@+id/text2_item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
//工具类
OkHTTP请求封装
public class OkhttpUtils {
private final OkHttpClient okHttpClient;
private final Handler handler;
//单例模式
private OkhttpUtils() {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1000, TimeUnit.SECONDS)
.readTimeout(1000, TimeUnit.SECONDS)
.writeTimeout(1000, TimeUnit.SECONDS)
.build();
handler = new Handler();
}
private static OkhttpUtils okhttpUtils = null;
public static OkhttpUtils getOkhttpUtils() {
if (okhttpUtils == null) {
okhttpUtils = new OkhttpUtils();
}
return okhttpUtils;
}
//接口回调json串
public interface Fun1 {
void getResultJson(String String);
}
private Fun1 fun1;
public void getSuccessJson(String url, final Fun1 fun1) {
final Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String s = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
fun1.getResultJson(s);
}
});
}
});
}
}
//检验网络代码
public class NetWork {
public static boolean isConnNetWork(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info!=null&&info.isAvailable()){
return true;//有网络
}
return false;//没网络
}
}
//数据库代码
public class MySqlite extends SQLiteOpenHelper {
public MySqlite(Context context) {
super(context, "user.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person(id integer primary key autoincrement,url text,jsonData text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
//Dao
public class Dao {
private final SQLiteDatabase db;
private final MySqlite mySqlite;
public Dao(Context context) {
mySqlite = new MySqlite(context);
db = mySqlite.getWritableDatabase();
}
public void add(String url,String json){
db.delete("person","url=?",new String[]{url});
ContentValues values=new ContentValues();
values.put("url",url);
values.put("jsonData",json);
db.insert("person",null,values);
}
public String select(String url){
String jsonData="";
Cursor query = db.query("person", null, "url=?", new String[]{url}, null, null, null);
while (query.moveToNext()){
jsonData = query.getString(query.getColumnIndex("jsonData"));
}
return jsonData;
}
}
离线缓存自定义布局
最新推荐文章于 2024-12-20 16:13:23 发布