自定义View+xrecyclerview多条目+数据库

自定义View实现三色梯
【自定义View+xrecyclerview多条目+数据库】


package com.example.yue.zidingyi; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.example.yue.utils.AppUtil; import com.example.yue.view.MainActivity; public class ThreeColorView extends ViewGroup {public ThreeColorView(Context context) { super(context); }public ThreeColorView(Context context, AttributeSet attrs) { super(context, attrs); }public ThreeColorView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int totalHeight=0; int totalWidth = 0; //获取到子view的数量 int child=getChildCount(); for (int i = 0; i < child; i++) { //得到所有文件中的子view View view=getChildAt(i); totalHeight+=view.getMeasuredHeight(); measureChild(view,widthMeasureSpec,heightMeasureSpec); } totalWidth = AppUtil.screenWidth(getContext()); System.out.println("width:"+totalWidth); System.out.println("height:"+totalHeight); //设置宽度和高度给当前view,通过下面这个方法 setMeasuredDimension(totalWidth, totalHeight); } @Override protected void onLayout(boolean bo, int left, int top, int right, int bottom) { { int l = 0; int t = 0; int r = 0; int b = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) {View view = getChildAt(i); //得到每一个view的对象 view.layout(l, t, l + view.getMeasuredWidth(), t + view.getMeasuredHeight()); l += view.getMeasuredWidth(); System.out.println("llll:" + l); t += view.getMeasuredHeight(); if (l + view.getMeasuredWidth() > AppUtil.screenWidth(getContext())) { l = 0; }//if (AppUtil.screenWidth(getContext()) - l < view.getMeasuredWidth()) { //l = 0; //} //点击事件 final int finalI = i; view.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) {Toast.makeText(getContext(), finalI + ":点击位置", Toast.LENGTH_SHORT).show(); TextView textView = (TextView) view; Toast.makeText(getContext(), textView.getText().toString() + "文本", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getContext(), MainActivity.class); intent.putExtra("id", textView.getText().toString()); getContext().startActivity(intent); } }); view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View view) { Toast.makeText(getContext(), finalI + ":长按位置", Toast.LENGTH_SHORT).show(); removeView(view); return true; } }); }}}

}

三色梯的工具类



package com.example.yue.utils; import android.content.Context; import android.util.DisplayMetrics; /** * Author:kson * E-mail:19655910@qq.com * Time:2018/05/30 * Description: */ public class AppUtil { /** * * @param context * @return 屏幕宽度 */ public static int screenWidth(Context context){ DisplayMetrics metrics = context.getResources().getDisplayMetrics(); returnmetrics.widthPixels; } }


自定义View的Mainactivity



package com.example.yue.view; import android.animation.ObjectAnimator; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.yue.R; import com.example.yue.utils.AppUtil; import com.example.yue.zidingyi.ThreeColorView; public class DonghuaActivity extends AppCompatActivity {private ThreeColorView threeColorView; private int count=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_donghua); threeColorView= findViewById(R.id.three); }public void bt(View view){ count++; int width= AppUtil.screenWidth(this); TextView textView=new TextView(this); textView.setText(count+""); textView.setGravity(Gravity.CENTER); textView.setTextColor(getResources().getColor(R.color.ssss)); ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(textView,"translationX",(width-width/3),0); objectAnimator.setDuration(3000); objectAnimator.start(); if (count % 3 == 1) { textView.setBackgroundColor(Color.RED); } else if (count % 3 == 2) { textView.setBackgroundColor(Color.YELLOW); } else { textView.setBackgroundColor(Color.BLUE); } threeColorView.addView(textView); ViewGroup.LayoutParams params = textView.getLayoutParams(); params.width = width/3; params.height = 70; textView.setLayoutParams(params); }}


Xrecyclerview的MainActivity

package com.example.yue.view; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.util.Log; import android.view.View; import com.example.yue.MyAdapter.MyAdapter; import com.example.yue.R; import com.example.yue.bean.Bean; import com.example.yue.model.NewsAdapter; import com.example.yue.presenter.Presenter; import com.example.yue.utils.Api; import com.jcodecraeer.xrecyclerview.XRecyclerView; import java.util.List; public class MainActivity extends AppCompatActivity implements IMActivity{ private int page = 5010; private XRecyclerView xRecyclerView; private boolean isRefresh = true; //判断是下啦刷新还是上啦加载 private Presenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); }private void initData() { if (getIntent().getExtras() != null) { page = 5010 + Integer.parseInt(getIntent().getExtras().getString("id")); } presenter = new Presenter(this); presenter.getUrl(Api.LEFT_URL,page); }private void initView() { xRecyclerView = findViewById(R.id.rv); xRecyclerView.setLayoutManager(new LinearLayoutManager(this)); xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() { @Override public void onRefresh() { isRefresh=true; page=5010; presenter.getUrl(Api.LEFT_URL,page); xRecyclerView.refreshComplete(); }@Override public void onLoadMore() { isRefresh=true; page++; presenter.getUrl(Api.LEFT_URL,page); xRecyclerView.loadMoreComplete(); } }); }@Override public void onSucces(final Bean bean) { runOnUiThread(new Runnable() { @Override public void run() { List data = https://www.it610.com/article/bean.getData(); Log.d("zzz",data.get(0).getDate()); MyAdapter myAdapter = new MyAdapter(data, MainActivity.this); xRecyclerView.setAdapter(myAdapter); } }); } }


XrecyclerView的Adapter

package com.example.yue.MyAdapter; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; 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.example.yue.R; import com.example.yue.bean.Bean; import com.example.yue.utils.Api; import com.jcodecraeer.xrecyclerview.XRecyclerView; import java.util.List; public class MyAdapter extends XRecyclerView.Adapter{ private List data; private Context context; public MyAdapter(List data, Context context) { this.data = https://www.it610.com/article/data; this.context = context; }@NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {if(viewType==Api.TYPE2){ View view=LayoutInflater.from(context).inflate(R.layout.news_item_layout,null); return new Type2ViewHolder(view); }else { View view=LayoutInflater.from(context).inflate(R.layout.news_item2_layout,null); return new Type1ViewHolder(view); }}@Override public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) { holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("删除"); builder.setNegativeButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int pos = holder.getLayoutPosition()-1; //得到下标 if(pos>=1) { data.remove(pos); notifyItemRemoved(pos); } } }); builder.setNeutralButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) {} }); builder.show(); return true; }}); Bean.DataBean dataBean = data.get(position); if(holder instanceof Type1ViewHolder){ ((Type1ViewHolder) holder).title.setText(dataBean.getTopic()); }else if(holder instanceof Type2ViewHolder){ String miniimgBean = dataBean.getMiniimg().get(0).getSrc(); ((Type2ViewHolder) holder).title.setText(dataBean.getTopic()); Glide.with(context).load(miniimgBean).into(((Type2ViewHolder) holder).iv1); Glide.with(context).load(miniimgBean).into(((Type2ViewHolder) holder).iv2); Glide.with(context).load(miniimgBean).into(((Type2ViewHolder) holder).iv3); } }@Override public int getItemCount() { return data.size(); }@Override public int getItemViewType(int position) { if(position%3==2){ return Api.TYPE2; }else { return Api.TYPE1; }}class Type1ViewHolder extends XRecyclerView.ViewHolder {private TextView title; public Type1ViewHolder(View itemView) { super(itemView); title = itemView.findViewById(R.id.title1); } }class Type2ViewHolder extends XRecyclerView.ViewHolder {private TextView title; private ImageView iv1, iv2, iv3; public Type2ViewHolder(View itemView) { super(itemView); iv1 = itemView.findViewById(R.id.img1); iv2 = itemView.findViewById(R.id.img2); iv3 = itemView.findViewById(R.id.img3); title = itemView.findViewById(R.id.title3); } } }

OkHttp工具类

package com.example.yue.utils; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; public class OkHttp3Util { private static OkHttpClient okHttpClient =null; public static OkHttpClient getInstance() { if (okHttpClient == null) { okHttpClient = new OkHttpClient.Builder()//构建器 .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))//添加的是应用拦截器 //.addNetworkInterceptor(new CacheInterceptor())//添加的网络拦截器 .build(); } return okHttpClient; }public static void doGet(String oldUrl, Callback callback) { OkHttpClient okHttpClient = getInstance(); Request request = new Request.Builder().url(oldUrl).build(); Call call = okHttpClient.newCall(request); call.enqueue(callback); }public static void doPost(String url, Map params, Callback callback) { OkHttpClient okHttpClient = getInstance(); FormBody.Builder builder = new FormBody.Builder(); Request request = new Request.Builder().url(url).post(builder.build()).build(); Call call = okHttpClient.newCall(request); call.enqueue(callback); } }

数据库

package com.example.yue.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbHelper extends SQLiteOpenHelper{ public DbHelper(Context context) { super(context,"dbname",null,1); }@Override public void onCreate(SQLiteDatabase db) { String sql="create table datable(id,integer primary key,json,text)"; db.execSQL(sql); }@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} }
















    推荐阅读