简单的ListView

最后更新于:2022-04-01 14:43:03

每天进步一点点(今天最大的收获是懂了这么多eclipse的快捷键,感觉好方便啊) 下面是一个简单的ListView,前面好像写了一篇类似的文章,只不过前面只是略懂一二,虽然现在也是略懂二三而已。 ~~~ package com.example.mylistview; import java.util.Random; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends Activity { private ListView lv; private MyAdapter adapter; private Random rd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); rd = new Random(); adapter = new MyAdapter(); lv.setAdapter(adapter); } private class MyAdapter extends BaseAdapter { @Override public int getCount() { // TODO Auto-generated method stub return 50; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub TextView tv = new TextView(getApplicationContext()); tv.setText(String.valueOf(rd.nextInt(5000))); return tv; } } } ~~~ ~~~ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <ListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </LinearLayout> ~~~ 如果用inflate的话,getView函数可以这样写(不过这之前请写好list_item.xml) ~~~ @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub //TextView tv = new TextView(getApplicationContext()); //tv.setText(String.valueOf(rd.nextInt(5000))); //return tv; View view = View.inflate(MainActivity.this, R.layout.list_item, null); TextView num = (TextView) view.findViewById(R.id.item_num); num.setText(rd.nextInt(5000)+""); return view; } ~~~
';