ListView介绍
ListView已经被RecycleView替代
ListView 本博客内容
实现上述三种的代码
1.实现arrayAdapter
main_activity.xml 布局页面需要添加一个
ListView
LinearLaout布局,布局走向可以水平
MainActivity.java
private ListView listView;
private ArrayAdapter arr_adapter;
listView = findViewById(R.id.listView);
// 数组适配器
String [] arr_data = {"慕课网","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院","极客学院"};
arr_adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,arr_data);
listView.setAdapter(arr_adapter);
2.简单适配器
main_activity.xml (内容和arrayAdapter的main_activity.xml一样)
自定义界面
R.layout.simple_listview_sytle.xml (LinearLayout布局)
MainActivity.java
private ListView listView;
private SimpleAdapter simp_adapter;
private List
3.实现ListView滚动监听事件(接到simpleAdapter示例 的那个文件后写的滚动监听示例)
MainActivity.java (实现类方法 )
//onCreate()里写
// 点击事件监听器
listView.setOnItemClickListener(this);
listView.setOnScrollListener(this); //alt + enter 就导入包,继而实现方法
//实现方法
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState){
case SCROLL_STATE_FLING:
Log.i("Main","用户在手指离开屏幕之前,由于用力了滑了一下,视图仍然依靠惯性继续滑动");
Map map = new HashMap<>();
map.put("pic",R.mipmap.ic_launcher_round);
map.put("text","增加项");
dataList.add(map);
simp_adapter.notifyDataSetChanged(); //重新更新UI
break;
case SCROLL_STATE_IDLE:
Log.i("Main","视图停止滑动");
break;
case SCROLL_STATE_TOUCH_SCROLL:
Log.i("Main","手指没有离开屏幕,视图正在滑动");
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
String text = listView.getItemAtPosition(position) +"";
Toast.makeText(this, "position:"+position+",text:"+text, Toast.LENGTH_SHORT).show();
try {
JSONObject text2 = new JSONObject(text);
System.out.println(text2.getString("text")); //点击第一行 显示数据为 : 慕课网0
System.out.println(text2.getString("pic")); // 2131361793
System.out.println(text2); //转为json对象后的数据 : {"text":"慕课网0","pic":2131361793}
} catch (JSONException e) {
e.printStackTrace();
}
}