简单Adapter

简单Adapter
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class FirstActivity extends Activity {
private ListView myListView;
//to define a array to set the data
String[] listData = { "Exit this way", "Far away from home",
"from sarah with love", "God is a girl" };


@Override
protected void onCreate(Bundle savedInstanceState) {
//and there i define the list view to get the data
super.onCreate(savedInstanceState);
setContentView(R.layout.first_main);
//to get the listview
myListView = (ListView) findViewById(R.id.listview);
setTitle("listview  示列 ");
First_initData();
}


private void First_initData() {
//实例化一个数组 adapter(arrayadapter)
//三个参数,this表示当前引用上下文,第二个参数利用条目显示的布局
//这里调用了系统自带的布局,第三个参数,绑定显示的数据 传入数组
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listData);


//绑定 adapter
myListView.setAdapter(adapter);
//添加点击事件
myListView.setOnItemClickListener( new OnItemClickListener() {
//adapter  绑定的 adapter
//v 条目显示的内容
//position v 对应的位置
//id 条目的id
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
//显示一句
new_Toast(v + "");
}
});
}


public void new_Toast(String str) {
//这里我们把 toast 封装一下
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
}




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/mybut" 
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:text="启动第二个Activity程序" />


<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="启动第二个Activity程序" />
</LinearLayout>



你可能感兴趣的:(简单Adapter)