Android Studio中通过View.OnTouchListener实现布局顶部滑动调整
科学计算器滑动布局调整:从底部滑动改为顶部滑动
我正在开发科学计算器的UI,希望通过向下滑动按钮布局的顶部区域来显示隐藏的科学按键。目前已实现滑动功能,但仅支持通过滑动布局底部触发,需要修改为滑动顶部区域即可触发显示。
核心修改思路
- 调整触摸监听的触发区域:将判断触摸点是否在布局底部改为判断是否在顶部区域
- 优化滑动逻辑:确保向下滑动顶部区域时触发科学按键的显示动作
修改后的代码实现
MainActivity 代码
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout buttonLayout = findViewById(R.id.button_layout); // 为按钮布局绑定自定义触摸监听器 buttonLayout.setOnTouchListener(new AnchorTouchListener(this, buttonLayout)); } }
AnchorTouchListener 代码
public class AnchorTouchListener implements View.OnTouchListener { private Context context; private View targetView; private float startY; // 定义顶部可触发滑动的区域高度(占布局总高度的20%) private float topTouchThreshold; public AnchorTouchListener(Context context, View targetView) { this.context = context; this.targetView = targetView; // 布局绘制完成后初始化顶部触发区域高度 targetView.post(() -> topTouchThreshold = targetView.getHeight() * 0.2f); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: startY = event.getY(); // 仅当触摸点在顶部区域内时,拦截后续触摸事件 return startY <= topTouchThreshold; case MotionEvent.ACTION_MOVE: float deltaY = event.getY() - startY; // 向下滑动超过阈值时,触发科学按键显示 if (deltaY > 50) { showScientificKeys(); } break; case MotionEvent.ACTION_UP: startY = 0; break; } return true; } private void showScientificKeys() { // 此处实现科学按键的显示逻辑,例如: View scientificKeys = ((AppCompatActivity)context).findViewById(R.id.scientific_keys); scientificKeys.setVisibility(View.VISIBLE); // 可选:添加平滑展开的属性动画 } }
XML 布局代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/button_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- 顶部透明触发区(可直接用现有布局的顶部元素替代) --> <View android:layout_width="match_parent" android:layout_height="40dp" android:background="@android:color/transparent"/> <!-- 基础计算器按键组 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- 基础按键布局 --> </LinearLayout> <!-- 默认隐藏的科学按键组 --> <LinearLayout android:id="@+id/scientific_keys" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:visibility="gone"> <!-- 科学按键布局 --> </LinearLayout> </LinearLayout>
内容的提问来源于stack exchange,提问作者Julian Docev
相关产品推荐
相关产品推荐

