容器与适配器: http://t.csdnimg.cn/ZfAJ7
activity_main.xml
- "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"
- android:orientation="vertical"
- tools:context=".MainActivity">
-
- <ListView
- android:id="@+id/listVi"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"/>
-
- LinearLayout>
MainActivity
- package com.example.myadpater;
-
- import androidx.appcompat.app.AppCompatActivity;
-
- import android.os.Bundle;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
-
- public class MainActivity extends AppCompatActivity {
-
- private ListView listView;
- //数据源
- String[] str = {"a","b","c","d","e","f","g"};
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- //适配器
- /*
- ArrayAdapter:简单、易用的。 每个列表项只能是TextView
- 最简单的Adapter。创建ArrayAdapter时需要3个参数。
- ArrayAdapter的第1个参数是Context,
- 第2个参数代表了每个列表项的控件,定义组件样式xml文件
- 第3个参数控制要包含多少个列表项,
- */
-
- ArrayAdapter
arrayAdapter = new ArrayAdapter<>(this, R.layout.text_test,str); - listView = findViewById(R.id.listVi);
-
-
-
- //往容器中设置适配器 -
- listView.setAdapter(arrayAdapter);
-
-
-
-
- }
- }
text_test.xml
- "1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android" - android:id="@android:id/text1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:textSize="24sp"
- android:textColor="#ff00ff"
- android:gravity="center"
- />