Android RecyclerView实现数据列表展示效果
本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下
1.首先导入依赖:
compile 'com.android.support:recyclerview-v7:25.3.1'
2.适配器类:
public class NewsAdapter extends RecyclerView.Adapter { private View view; private Context mcontext; private ArrayList<NewsData.DataBean> mlist=new ArrayList<>(); public NewsAdapter(Context mcontext) { this.mcontext = mcontext; } //找到需要导入的布局 @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { view = LayoutInflater.from(mcontext).inflate(R.layout.news_item, null); return new ViewHolder(view); } //加载相应的内容 @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ViewHolder viewholder=(ViewHolder)holder; viewholder.textview.setText(""+getItem(position).getNews_title()); Glide.with(mcontext).load(getItem(position).getPic_url()).into(viewholder.ima); } //手写的重置数据的方法 public void setdata(ArrayList<NewsData.DataBean> list){ if (list!=null&&list.size()>0){ mlist.addAll(list); } } //手写的获得视图的方法 public NewsData.DataBean getItem(int position){ return mlist.get(position); }; @Override public int getItemCount() { return mlist.size(); } //定义的ViewHolder类继承RecyclerView.ViewHolder 并找到布局中的ID public class ViewHolder extends RecyclerView.ViewHolder{ private TextView textview; private ImageView ima; public ViewHolder(View itemView) { super(itemView); textview=(TextView)itemView.findViewById(R.id.tv); ima=(ImageView)itemView.findViewById(R.id.image); } } }
3.主界面(用到RecyclerView的主要是initdata()方法和Handler):
public class MainActivity extends AppCompatActivity implements IMainView{ private MainPresenter mainp; private NewsAdapter md; private RecyclerView recy; private ArrayList<NewsData.DataBean> mlist=new ArrayList<>(); private String url="http://api.expoon.com/AppNews/getNewsList/type/1/p/1"; private Handler hand=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Gson gson=new Gson(); if (msg.what==1) { NewsData newsData = gson.fromJson(msg.obj.toString(), NewsData.class); mlist=(ArrayList<NewsData.DataBean>) newsData.getData(); md.setdata((ArrayList<NewsData.DataBean>) mlist); md.notifyDataSetChanged(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initview(); initdata(); initdatafromserver(); } private void initview() { recy=(RecyclerView)findViewById(R.id.recy); } private void initdatafromserver() { //加载网络数据,找P层去要 mainp.loadDataFromServer(url); } private void initdata() { mainp=new MainPresenter(this); //设置适配器 md=new NewsAdapter(this); //创建默认的线性LayoutManager recy.setLayoutManager(new LinearLayoutManager(this)); recy.setAdapter(md); } //重写的IMainView类接口的两个方法 @Override public void successfulCallback(String str) { Message msg = Message.obtain(); msg.what=1; msg.obj=str; hand.sendMessage(msg); } @Override public void errCallback(int code, String msg) { } }
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)