欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

第一章,listview的简易用法(Android)

来源: 开发者 投稿于  被查看 14937 次 评论:3

第一章,listview的简易用法(Android)


这篇文章主要是练习了安卓listview的arrayadapter和baseadapter的简单填充。

1.arrayadapter填充

布局:



    


代码:

 

package com.example.demo02;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

	private ListView main_listview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 初始化控件和数据
		initView();
	}

	private void initView() {

		main_listview = (ListView) this.findViewById(R.id.main_listview);

		// 初始化数据
		ArrayAdapter adapter = new ArrayAdapter(this,
				android.R.layout.simple_list_item_1);

		for (int i = 0; i < 20; i++) {
			adapter.add("item-->" + i);
		}
		
		// 为listview添加item
		main_listview.setAdapter(adapter);
		
	}

}
调试截图:

 

\

 

2.baseadapter填充

布局:

 



    
    

mainactivity:

 

 

package com.example.demo03;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {

	private ListView main_listview;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
//        初始化数据
        initView();
    }

	private void initView() {
		// TODO Auto-generated method stub
		
		main_listview = (ListView) this.findViewById(R.id.main_listview);
		
		MainAdapter adapter = new MainAdapter(this);
		
		main_listview.setAdapter(adapter);
		
	}
    
}

 

mainadapter:

 

package com.example.demo03;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MainAdapter extends BaseAdapter {

	private Context context;
	
	public MainAdapter(Context context) {
		this.context = context;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return 10;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		
		TextView tv = new TextView(context);
		tv.setText("item···>"+arg0);
		
		return tv;
	}

}
调试截图:

 

\
 


用户评论