参考:http://developer.android.com/reference/android/app/ListActivity.html
ListActivity 有一个默认的 Screen Layout(一列,全屏,屏幕居中),如果你想要定制自己的Screen Layout,可以在onCreate()方法中调用 setContentView().
·首先看一个,使用ListActivity 默认layout的例子:
只需要定义一个Activity,代码如下:
-
package com.example.twiter;
-
-
import android.app.ListActivity;
-
import android.os.Bundle;
-
import android.widget.ArrayAdapter;
-
-
public class FooListActivity extends ListActivity {
-
String[] listItems = {"item 1", "item 2 ", "list", "android", "item 3", "foobar", "bar", };
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems));
-
}
-
}
上面代码中ArrayAdapter的第二个构造参数用于指定List的每一行的layout(Row Layout),"android.R.layout.simple_list_item_1"是android自带的一种Row Layout。下文中我们会用到自定义Row Layout。
本例运行效果:
·第二个例子:使用自定义的Row Layout
list_fruit.xml
Row Layout模板
-
<?xml version="1.0" encoding="utf-8"?>
-
<TextView xmlns:android=""
-
android:layout_width="fill_parent"
-
android:layout_height="fill_parent"
-
android:padding="10dp"
-
android:textSize="20sp" >
-
</TextView>
ListFruitActivity.java
-
package com.example.twiter;
-
-
import android.app.ListActivity;
-
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.TextView;
-
import android.widget.Toast;
-
-
public class ListFruitActivity extends ListActivity {
-
-
static final String[] FRUITS = new String[]{
-
"Apple","Pear","Mango","Blueberry","Coconut",
-
"Guava","Olive","Sugar-apple"
-
};
-
-
public void onCreate(Bundle savedInstanceState){
-
super.onCreate(savedInstanceState);
-
-
ArrayAdapter adapter = new ArrayAdapter<String>(
-
this,//Context
-
R.layout.list_fruit,//指定 row template ,这里需要是一个textViewResourceId,所以list_fruit.xml中只能定义一个TextView
-
FRUITS//array of which template objects to bind
-
);
-
setListAdapter(adapter);
-
-
ListView listView = getListView();
-
listView.setTextFilterEnabled(true);
-
-
listView.setOnItemClickListener(new OnItemClickListener() {
-
-
@Override
-
public void onItemClick(AdapterView<?> parent, View view, int position,
-
long id) {
-
Toast.makeText(getApplicationContext(), ((TextView)view).getText(), Toast.LENGTH_SHORT).show();
-
}
-
});
-
-
}
-
}
AndroidManifest.xml
-
<activity android:name="com.example.twiter.ListFruitActivity">
-
<intent-filter>
-
<action android:name="android.intent.action.MAIN" />
-
<category android:name="android.intent.category.LAUNCHER" />
-
</intent-filter>
-
</activity>
效果图:
阅读(1861) | 评论(0) | 转发(0) |