[英]Android: How to scroll header to top when there is no/limited items in ListView?
我正在开发一个Android应用程序,其中在ListView中添加了标题视图。 现在,我希望仅当用户向下滚动ListView时显示该标题视图。 我尝试了以下操作,但未成功实现所需的输出。
即使列表中只有一项,我也需要相同的行为。 但是,当列表中的数据受到限制时,标题始终可见。
任何建议将不胜感激。
谢谢阿玛
通过一个简单的技巧就可以轻松实现此效果,请确保在build.gradle
包含compile 'com.android.support:support-v13:20.0.0'
;如果您使用的是Eclipse,则下载最新的支持jar文件:
使用以下xml布局:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pullToShowBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:orientation="vertical">
<TextView
android:id="@+id/searchBar"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginTop="-48dp"
android:background="@android:color/darker_gray"
android:gravity="center"
android:text="My Hidden Search Bar" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world" />
</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
这是您的Activity
的代码:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final View searchBar = findViewById(R.id.searchBar);
final SwipeRefreshLayout sw = (SwipeRefreshLayout) findViewById(R.id.pullToShowBar);
sw.setColorSchemeColors(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT);
sw.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
sw.setRefreshing(false);
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) searchBar.getLayoutParams();
layoutParams.setMargins(0, 0, 0, 0);
searchBar.setLayoutParams(layoutParams);
}
});
}
}
最后一件:
import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.widget.AbsListView;
public class PullToSearchBarLayout extends SwipeRefreshLayout {
private AbsListView mListView;
public PullToSearchBarLayout(Context context) {
super(context);
}
public PullToSearchBarLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean canChildScrollUp() {
if (mListView == null) {
mListView = (AbsListView) findViewById(android.R.id.list);
}
if (android.os.Build.VERSION.SDK_INT < 14) {
final AbsListView absListView = mListView;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return ViewCompat.canScrollVertically(mListView, -1);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.