我过去曾使用(或者更确切地说,尝试使用)该StickyListHeaders
库。在遇到一些问题后,我想出了以下内容。这与其他海报的建议没有太大区别。
主布局文件由默认不可见activity_layout.xml
的 aListView
和 a组成。LinearLayout
使用 OnScrollListener 的 onScroll() 方法,LinearLayout's
切换可见性。您不需要膨胀另一个布局或将视图动态添加到布局的父级。这是该onScroll
方法的样子:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 3) { // 5th row will stick
llHeader.setVisibility(View.VISIBLE);
} else {
llHeader.setVisibility(View.GONE);
}
}
简单地说,切换可见性以获得所需的效果。你可以看看下面的代码。它是您可以期待的工作示例。该活动包含ListView
具有严格准系统扩展的BaseAdapter
. 填充有编号按钮(ListView
每行一个,从 0 开始,一直到 19)。
public class StickyHeader extends Activity {
LinearLayout llHeader;
ListView lv;
SHAdapter shAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
lv = (ListView) findViewById(R.id.listView1);
llHeader = (LinearLayout) findViewById(R.id.llHeader);
shAdapter = new SHAdapter();
lv.setAdapter(shAdapter);
lv.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 3) {
llHeader.setVisibility(View.VISIBLE);
} else {
llHeader.setVisibility(View.GONE);
}
}
});
}
public class SHAdapter extends BaseAdapter {
Button btCurrent;
int[] arr = new int[] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
@Override
public int getCount() {
return 20;
}
@Override
public Object getItem(int arg0) {
return arr[arg0];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.list_item_layout, null);
btCurrent = (Button) convertView.findViewById(R.id.button1);
if ((Integer)getItem(position) == 4) {
btCurrent.setText("Number " + getItem(position) + " is sticky");
} else {
btCurrent.setText("" + getItem(position));
}
return convertView;
}
}
}
活动布局.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<!-- This LinearLayout's visibility is toggled -->
<!-- Improvement suggested by user 'ar34z'
(see comment section below) -->
<include layout="@layout/list_item_layout" />
</RelativeLayout>
list_item_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llHeader"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/white"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>