首页 > 代码库 > android开发之BaseAdapter

android开发之BaseAdapter

BaseAdapter可以最灵活地实现ListView,里面的控件也可以获得焦点,允许点击.示例如下:

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent" ><ListView    android:id="@+id/myList"    android:layout_width="match_parent"    android:layout_height="match_parent"/></LinearLayout>

主方法:

public class BaseAdapterTest extends Activity{    ListView myList;    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        myList = (ListView) findViewById(R.id.myList);        BaseAdapter adapter = new BaseAdapter()        {            @Override            public int getCount()            {                // 指定一共包含40个选项                return 40;            }            @Override            public Object getItem(int position)            {                return null;            }            // 重写该方法,该方法的返回值将作为列表项的ID            @Override            public long getItemId(int position)            {                return position;            }            // 重写该方法,该方法返回的View将作为列表框            @Override            public View getView(int position                    , View convertView , ViewGroup parent)            {                // 创建一个LinearLayout,并向其中添加2个组件                LinearLayout line = new LinearLayout(BaseAdapterTest.this);                line.setOrientation(0);                ImageView image = new ImageView(BaseAdapterTest.this);                image.setImageResource(R.drawable.ic_launcher);                TextView text = new TextView(BaseAdapterTest.this);                text.setText("第" + (position +1 ) + "个列表项");                text.setTextSize(20);                text.setTextColor(Color.RED);                line.addView(image);                line.addView(text);                // 返回LinearLayout实例                return line;            }        };        myList.setAdapter(adapter);    }}

效果如下:

技术分享

android开发之BaseAdapter