继承ListActivity实现ListView
一、通过继承ListActivity实现ListView
ListActivity直接继承了Activity类。以下代码使用Android系统提供的布局文件,所有不需要调用setContentView();就能显示出所需的界面。
Java代码如下所示:
package my.list.namespace;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private String[] dispItems = {"中国","美国","德国","法国"};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, dispItems));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
switch(position){
case 0:
dispToast("选择了第一行:中国");
break;
case 1:
dispToast("选择了第二行:美国");
break;
case 2:
dispToast("选择了第三行:德国");
break;
case 3:
dispToast("选择了第四行:法国");
break;
default:
dispToast("选择了未知的行");
break;
}
}
public void dispToast(String text){
Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
toast.show();
}
}
参数:
ListView l 是你点击的列表控件,
View v 是你当前正点击的在ListView中的一项,
int positon 是被点击的行在列表中的位置,这个位置从0开始算起,
long id 是被点击的行号。
原文:
@param l:The ListView where the click happened
@param v:The view that was clicked within the ListView
@param position:The position of the view in the list
@param id:The row id of the item that was clicked
ListView l 是你点击的列表控件,
View v 是你当前正点击的在ListView中的一项,
int positon 是被点击的行在列表中的位置,这个位置从0开始算起,
long id 是被点击的行号。
原文:
@param l:The ListView where the click happened
@param v:The view that was clicked within the ListView
@param position:The position of the view in the list
@param id:The row id of the item that was clicked