Android ListView的使用

來源:互聯網
上載者:User

 1、定義簡單的適配器形式。

首先定義一個Layout為listviewitem.xml. 裡面有三個TextView。分別代表學號,姓名,班級。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/cuslistViewItem"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView"         android:layout_marginLeft="10dp"        android:layout_marginBottom="10dp"/>    <TextView        android:id="@+id/textView3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView"        android:layout_marginLeft="10dp"         android:layout_marginBottom="10dp"/>    <TextView        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView"        android:layout_marginLeft="10dp"        android:layout_marginBottom="10dp" /></LinearLayout>

 在activity_main.xml中放一個ListView控制項,很簡單,不解釋。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />    <ListView        android:id="@+id/listView1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/textView1"        android:layout_marginTop="50dp" >    </ListView></RelativeLayout>

 

然後建立資料來源

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ListView lv = (ListView)this.findViewById(R.id.listView1);ArrayList<HashMap<String,String>> listSource = new ArrayList<HashMap<String,String>>();for(int num=1; num< 10; num++){HashMap<String,String> map = new HashMap<String, String>();map.put("num",String.valueOf(num));map.put("name", "stu"+num );map.put("className", "software 2");listSource.add(map);}SimpleAdapter mStuInfo = new SimpleAdapter(this,listSource,R.layout.listviewitem, new String[] {"num","name","className"}, new int[]{R.id.textView1, R.id.textView2, R.id.textView3});lv.setAdapter(mStuInfo);}}

 最後將listview綁定適配器的資料來源。如。

 當然可以加入ItemClick事件。

 lv.setOnItemClickListener(new ItemClickListener());

然後實現ItemClickListener。

 class ItemClickListener implements OnItemClickListener { //arg2 is the position //arg3 is row number@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {// TODO Auto-generated method stubHashMap<String, String> item=(HashMap<String, String>) arg0.getItemAtPosition(arg2); Toast.makeText(MainActivity.this, item.get("name"), Toast.LENGTH_LONG).show();}}

 ListView和GridView在此用法是一樣的。可以把ListView控制項換成GridView控制項。

 

二、下面採用新的適配器形式。將新增學生圖片,並重新組織布局。效果如:

代碼如下:

重新設計的listviewitem.xml.

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/cuslistViewItem"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="10dp"        android:layout_marginBottom="10dp" />    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView"         android:layout_toRightOf="@+id/imageView1"        android:layout_marginLeft="10dp"        android:layout_marginBottom="10dp"/>    <TextView        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView"        android:layout_toRightOf="@+id/textView1"         android:layout_marginLeft="10dp"         android:layout_marginBottom="10dp"/>    <TextView        android:id="@+id/textView3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView"        android:layout_toRightOf="@+id/imageView1"        android:layout_below="@+id/textView1"        android:layout_marginLeft="10dp"        android:layout_marginBottom="30dp" /></RelativeLayout>

 

重新的資料來源。建立了MyListViewAdapter類繼承BaseAdapter。

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ListView lv = (ListView)this.findViewById(R.id.listView1);ArrayList<HashMap<String,String>> listSource = new ArrayList<HashMap<String,String>>();for(int num=1; num< 10; num++){HashMap<String,String> map = new HashMap<String, String>();map.put("photo", String.valueOf(R.drawable.ic_launcher));map.put("num",String.valueOf(num));map.put("name", "stu"+num );map.put("className", "software 2");listSource.add(map);}lv.setAdapter(new MyListViewAdapter(listSource));}public class MyListViewAdapter extends BaseAdapter{View[] itemViews;public MyListViewAdapter(ArrayList<HashMap<String,String>> listSource){itemViews = new View[listSource.size()];Iterator<HashMap<String, String>> it = listSource.iterator();HashMap<String,String> hash;int i = 0;try{while(it.hasNext()){hash = it.next();itemViews[i] =  makeItemView(hash);i++;}}catch(Exception e){Log.e("Error", e.getMessage());e.printStackTrace();}}private View makeItemView(HashMap<String,String> map) {              if(map == null || map.isEmpty()) return null;            LayoutInflater inflater = (LayoutInflater) MainActivity.this                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);                          // 使用View的對象itemView與R.layout.item關聯               View itemView =  inflater.inflate(R.layout.listviewitem, null);                TextView title = (TextView) itemView.findViewById(R.id.textView1);              title.setText(map.get("num"));              Log.e("num" , map.get("num"));                        TextView text = (TextView) itemView.findViewById(R.id.textView2);              text.setText(map.get("name"));            Log.e("name", map.get("name"));                        TextView text2 = (TextView) itemView.findViewById(R.id.textView3);              text2.setText(map.get("className"));             Log.e("className", map.get("className"));                        ImageView image = (ImageView) itemView.findViewById(R.id.imageView1);              image.setImageResource(Integer.parseInt(map.get("photo")));             Log.e("photo", map.get("photo"));                          return itemView;         } @Overridepublic int getCount() {// TODO Auto-generated method stubreturn itemViews.length;}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn itemViews[position];}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubif(convertView == null)return itemViews[position];return convertView;}}}}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.