使用自定义列表视图。
您还可以通过自定义背景来自定义行的外观。activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#0095FF"> //background color
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="@android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
主要活动
在 MainActivity 中定义 populateString()
public class MainActivity extends Activity {
String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data_array = populateString();
ListView ll = (ListView) findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter();
ll.setAdapter(cus);
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data_array.length;//listview item count.
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder vh;
vh= new ViewHolder();
if(convertView==null )
{
convertView=mInflater.inflate(R.layout.row, parent,false);
//inflate custom layour
vh.tv2= (TextView)convertView.findViewById(R.id.textView2);
}
else
{
convertView.setTag(vh);
}
//vh.tv2.setText("Position = "+position);
vh.tv2.setText(data_array[position]);
//set text of second textview based on position
return convertView;
}
class ViewHolder
{
TextView tv1,tv2;
}
}
}
行.xml。每行的自定义布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Header" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TextView" />
</LinearLayout>
为自定义布局充气。使用视图支架来实现平滑滚动和性能。
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
http://www.youtube.com/watch?v=wDBM6wVEO70。演讲是关于 android 开发人员的 listview 性能。