码迷,mamicode.com
首页 > 移动开发 > 详细

android开发之BaseAdapter

时间:2015-01-12 00:19:04      阅读:384      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/limaofuyuanzhang/p/4217280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!