简单来说,ListView简单是一个可以垂直滚动的列表控件。
ListView的简单使用:
在布局中加入ListView控件,并为ListView制定一个id,具体代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> 然后通过ListView的实例化和适配器的构建以及数据的传入来实现滚动列表ListView:
public class MainActivity extends AppCompatActivity { private String[] data = {"Apple","Banana","Orange","Watermelon","pear","Grape","Pineapple","Strawberry","Cherry","Mango", "Apple","Banana","Orange","Watermelon","pear","Grape","Pineapple","Strawberry","Cherry","Mango"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.list_view); ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,data); listView.setAdapter(adapter); }} 如何想要实现列表数据的单选和多选模式:多选模式:public class MainActivity extends AppCompatActivity {
private String[] data = {"Apple","Banana","Orange","Watermelon","pear","Grape","Pineapple","Strawberry","Cherry","Mango", "Apple","Banana","Orange","Watermelon","pear","Grape","Pineapple","Strawberry","Cherry","Mango"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.list_view); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice,data); listView.setAdapter(adapter);
}}单选模式:
public class MainActivity extends AppCompatActivity { private String[] data = {"Apple","Banana","Orange","Watermelon","pear","Grape","Pineapple","Strawberry","Cherry","Mango", "Apple","Banana","Orange","Watermelon","pear","Grape","Pineapple","Strawberry","Cherry","Mango"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.list_view); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_single_choice,data); listView.setAdapter(adapter); }}
时间: 2024-11-04 20:46:35