效果图一:
效果图二:
原理:(1)ListView外面套一层相对布局,隐藏一个标题
(2)监听ScrollView的滚动
Demo地址:http://download.csdn.net/download/baopengjian/10000169
关键代码:
效果一:
private ListView lv;
private View ll_hide,mHeadView,ll_title;
private int[] mHideLocation = new int[2];
private int[] mTitleLocation = new int[2];
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo1);
lv = (ListView) findViewById(R.id.lv);
ll_hide = findViewById(R.id.ll_hide);
mHeadView = View.inflate(this,R.layout.lv_head,null);
ll_title = mHeadView.findViewById(R.id.ll_title);
lv.addHeaderView(mHeadView);
String[] array = new String[100];
for(int i = 0;i<array.length;i++){
Random random = new Random();
array[i] = String.valueOf(random.nextInt(i+1));
}
lv.setAdapter(new ArrayAdapter<String>(Demo1Activity.this,android.R.layout.simple_list_item_1,array));
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
ll_hide.getLocationOnScreen(mHideLocation);
ll_title.getLocationOnScreen(mTitleLocation);
//比较y方向坐标
if(mTitleLocation[1]<mHideLocation[1]){
ll_hide.setVisibility(View.VISIBLE);
}else {
ll_hide.setVisibility(View.GONE);
}
}
});
}
效果二:
private ListView lv;
private View mHeadView,ll_title;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo2);
lv = (ListView) findViewById(R.id.lv);
mHeadView = View.inflate(this,R.layout.lv_head2,null);
ll_title = findViewById(R.id.ll_title);
lv.addHeaderView(mHeadView);
final List<NewStockCalendar> list = DataSupport.getDatas();
Adapter2 adapter = new Adapter2(this,list);
lv.setAdapter(adapter);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(firstVisibleItem>0){
ll_title.setVisibility(View.VISIBLE);
((TextView)ll_title.findViewById(R.id.tv_date)).setText(list.get(firstVisibleItem).getSgsx());
}else{
ll_title.setVisibility(View.GONE);
}
}
});
}