你的位置:首页 > 操作系统

[操作系统]Android listview和ListAdapter搭配使用


ListView时Android中自带的数据显示控件,要使用ListView填充数据,必须要通过适配器来填充,这里给大家介绍一下ListAdapter适配器,效果图如下:

java源码:

package com.example.listview1;import java.util.ArrayList;import java.util.List;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.Adapter;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;public class MainActivity extends Activity {  private ListView listview;  private ListAdapter adapter;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    listview=(ListView) findViewById(R.id.listView1);    listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);    adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_single_choice,getsource());    listview.setAdapter(adapter);    listview.setOnItemClickListener(new OnItemClickListener() {      @Override      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,          long arg3) {        // TODO 自动生成的方法存根        Toast.makeText(MainActivity.this, ">>"+adapter.getItem(arg2),1).show();      }    });  }  @Override  public boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.main, menu);    return true;  }    public List<String> getsource()  {    List<String> list=new ArrayList<String>();    for(int i=0;i<20;i++)    {      list.add("欢迎您,"+i);    }    return list;  }}