Android开发中如何将滑动组件固定在顶部-创新互联
今天就跟大家聊聊有关Android开发中如何将滑动组件固定在顶部,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

效果是如下:

场景:有些时候是内容中间的组件当滑动至顶部的时候固定显示在顶部。
实现的思路:
1.目标组件(button)有两套,放在顶部和内容中间;
2.当内容中间的组件滑动至顶部栏位置时控制显示/隐藏顶部和中间的组件(涉及到组件获取在屏幕的位置知识点);
activity代码:
public class MainActivity extends AppCompatActivity implements ObservableScrollView.ScrollViewListener {
private ObservableScrollView scrollView;
private Button topBtn1, topBtn2, middleBtn1, middleBtn2;
private View topPanel, middlePanel;
private int topHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initListeners();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;//状态栏高度
int titleBarHeight = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();//标题栏高度
topHeight = titleBarHeight + statusBarHeight;
}
private void initViews() {
scrollView = (ObservableScrollView) findViewById(R.id.scrollView);
topPanel = findViewById(R.id.topPanel);
topBtn1 = (Button) topPanel.findViewById(R.id.button1);
topBtn2 = (Button) topPanel.findViewById(R.id.button2);
middlePanel = findViewById(R.id.middlePanel);
middleBtn1 = (Button) middlePanel.findViewById(R.id.button1);
middleBtn2 = (Button) middlePanel.findViewById(R.id.button2);
}
private void initListeners() {
topBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
middleBtn1.setBackgroundColor(Color.WHITE);
topBtn1.setBackgroundColor(Color.WHITE);
}
});
middleBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
middleBtn1.setBackgroundColor(Color.BLUE);
topBtn1.setBackgroundColor(Color.BLUE);
}
});
scrollView.setScrollViewListener(this);
}
@Override
public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
int[] location = new int[2];
middleBtn1.getLocationOnScreen(location);
int locationY = location[1];
Log.e("locationY", locationY + " " + "topHeight的值是:" + topHeight);
if (locationY <= topHeight && (topPanel.getVisibility() == View.GONE || topPanel.getVisibility() == View.INVISIBLE)) {
topPanel.setVisibility(View.VISIBLE);
}
if (locationY > topHeight && topPanel.getVisibility() == View.VISIBLE) {
topPanel.setVisibility(View.GONE);
}
}
} 分享名称:Android开发中如何将滑动组件固定在顶部-创新互联
当前路径:http://www.jxjierui.cn/article/dcegsd.html


咨询
建站咨询
