ListView 和 Adapter的关系: 就是将ListView绑定的界面中的数据与adapter相适配
MainActivity.java
package com.example.listviewtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Bean bean;
private List<Bean> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i <100 ; i++) {
bean = new Bean();
bean.setName("zjx"+i);
data.add(bean);
}
ListView listView = findViewById(R.id.lv);
listView.setAdapter(new MyAdapter(data,this));
}
}
MyAdapter.java
package com.example.listviewtest;
/*
*todo author:张建新
*todo @since :2021/12/13/0013
*todo 作用:
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MyAdapter extends BaseAdapter {
private List<Bean> data = new ArrayList<>();
private Context context;
public MyAdapter(List<Bean> data, Context context) {
this.data = data;
this.context = context;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.list_view,parent,false);
}
TextView textView = convertView.findViewById(R.id.tv);
textView.setText(data.get(position).getName());
return convertView;
}
}
一个固定的写java的模式 javaBean
Bean.java
package com.example.listviewtest;
/*
*todo author:张建新
*todo @since :2021/12/13/0013
*todo 作用:
*/
public class Bean {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name ;
}
list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
|