kotlin achieve ListView
Sub-layout files
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img"
android:layout_centerVertical="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/img"
android:id="@+id/titles"
/>
</RelativeLayout>
Master layout file
<android.support.constraint.ConstraintLayout 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=".Demo">
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list"
></com.handmark.pulltorefresh.library.PullToRefreshListView>
</android.support.constraint.ConstraintLayout>
The main class
class Demo : AppCompatActivity() {
companion object {
var lists : ArrayList<Map<String,String>> = ArrayList()
var adapter:MyAdapter? = null
}
var page: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_demo)
adapter = MyAdapter(this, lists)
list.setAdapter(adapter)
var ss:String = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page = 1";
//调用下载方法
download(ss)
}
// download method
fun download(ss:String){
Thread(Runnable {
var readText = URL(ss).readText()
var jsonObject = JSONObject(readText)
var jsonArray:JSONArray = jsonObject.getJSONArray("data")
for (arr in 0..jsonArray.length()-1 step 1){
var jo = jsonArray.getJSONObject(arr)
var string = jo.getString("pic")
var title = jo.getString("title")
var map = HashMap<String, String>()
map.put("pic",string)
map.put("title",title)
lists.add(map)
}
Demo.adapter!!.notifyDataSetChanged()
}).start()
}
adapter
class MyAdapter(context: Context, lists: ArrayList<Map<String, String>>) : BaseAdapter() {
var context: Context = context
var lists: ArrayList<Map<String, String>> = lists
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view = View.inflate(context, R.layout.item, null)
var img: ImageView = view.findViewById(R.id.img);
var title: TextView = view.findViewById(R.id.titles)
var map = lists.get(position)
title.setText(map.get("title"))
Picasso.with(context).load(map.get("pic")).into(img)
return view
}
override fun getItem(position: Int): Any {
return lists.get(position)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return lists.size
}
}