安卓学习第13课——BaseAdapter

分享到:

BaseAdapter创建这么一个对象,需要些四个方法。 int getCount(); Object getItem(int position); long getItemId(int position);View getView(int position, View convertView, ViewGroup parent);(1)列表中的项数(2)返回值的列表内容(3)获得postion处的列表项的ID(4)该列表项里的组件

package com.example.baseadapter;



import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    ListView mylist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mylist=(ListView) findViewById(R.id.myList);
        BaseAdapter adapter=new BaseAdapter(){

            @Override
            public int getCount() {
                return 40;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                //创建一个LinearLayout,并向其中添加两个组件
                LinearLayout line=new LinearLayout(MainActivity.this);
                line.setOrientation(0);
                ImageView image=new ImageView(MainActivity.this);
                image.setImageResource(R.drawable.ic_launcher);
                TextView textview=new TextView(MainActivity.this);
                textview.setText("第"+(position+1)+"个列表项");
                textview.setTextSize(20);
                textview.setTextColor(Color.RED);
                line.addView(image);
                line.addView(textview);
                
                //返回LinearLayout 实例
                return line;
            }
            
            
        };
        mylist.setAdapter(adapter);
    }    
}
昵    称:
验证码:

相关文档: