求使用ListView控件,定义基本适配器BaseAdapte的子类来实现来展示10个条目数据,给出用Android studio 写的代码
时间: 2023-06-04 15:06:25 浏览: 140
Android(安卓)应用开发技术 运用ListView组件显示ArrayAdapter数据案例源代码.rar
好的,以下是实现使用ListView控件、定义基本适配器BaseAdapter的子类来展示10个条目数据的代码:
1.创建一个数据类MyListItem.java:
```
public class MyListItem {
private String text;
public MyListItem(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
```
2.创建一个自定义适配器MyListAdapter.java:
```
public class MyListAdapter extends BaseAdapter {
private Context context;
private List<MyListItem> dataList;
public MyListAdapter(Context context, List<MyListItem> dataList) {
this.context = context;
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(context).inflate(R.layout.my_list_item, parent, false);
} else {
view = convertView;
}
TextView textView = view.findViewById(R.id.text_view);
textView.setText(dataList.get(position).getText());
return view;
}
}
```
3.在res/layout目录下创建布局文件my_list_item.xml,定义ListView子项的布局:
```
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:textSize="20sp" />
```
4.在Activity中设置ListView和适配器:
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<MyListItem> dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
dataList.add(new MyListItem("Item " + i));
}
MyListAdapter adapter = new MyListAdapter(this, dataList);
listView = findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
}
```
其中,activity_main.xml布局文件中要有一个ListView控件:
```
<?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"
android:orientation="vertical">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
```
希望能对你有所帮助!
阅读全文