[英]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.