Android 应用内分屏查看(使用fragment)

来源:互联网 发布:mt4 一键下单脚本源码 编辑:程序博客网 时间:2024/06/06 06:39

说的不是安卓系统的应用分屏功能,而是在应用内一个界面想要分屏查看,例如在看文章答题app中,一个界面是文章,一个界面是题目,想要一边看文章一边答题的话,只能来回切换界面,所以需要两者在一个界面,各自分屏可滑动(fragment可实现),并且滑动中间线可重新划分各自高度。
分屏界面


  • 首先在一个界面中布置了两个FrameLayout,中间一个横线用于调整两者高度。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity">    <FrameLayout        android:id="@+id/frag0"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" />    <View        android:id="@+id/addLine"        android:layout_width="match_parent"        android:layout_height="30dp"        android:background="#8a8a8a" />    <FrameLayout        android:id="@+id/frag1"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" /></LinearLayout>
  • 两个fragment就不贴出来了,fragment本来就是为了碎片化屏幕的,在onCreate方法中find到view并把两个fragment填充到到frameLayout中
frameLayout0 = (FrameLayout) findViewById(R.id.frag0);frameLayout1 = (FrameLayout) findViewById(R.id.frag1);mLine = findViewById(R.id.addLine);        getSupportFragmentManager().beginTransaction().add(R.id.frag0, new MineFragment(0)).commit();        getSupportFragmentManager().beginTransaction().add(R.id.frag1, new MineFragment(1)).commit();
  • 至此分屏查看的功能是完成了,最重要的就是来触摸滑动动态改变两个View高度,所以对activity进行onTouchEvent的触摸监听,符合条件的滑动情况在对两个frameLayout进行重新设置高度。
 @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                if (!(event.getY() > mLine.getTop() && event.getY() < mLine.getBottom())) {                    return super.onTouchEvent(event);                }                beforeY = event.getY();                mtop = event.getY() - mLine.getTop();                mbottom =mLine.getBottom()- event.getY();                break;            case MotionEvent.ACTION_MOVE:                frameLayout0.getLayoutParams().height =(int)(event.getY()-getStatusBarHeight(this)-mtop+0.5f);                frameLayout1.getLayoutParams().height = (int)(GetScreenHeight(this) - event.getY()-mbottom+0.5f);                frameLayout0.requestLayout();                frameLayout1.requestLayout();                break;            case MotionEvent.ACTION_UP:                beforeY = event.getY();                break;        }        return true;    }

可以看到
在触摸的ACTION_DOWN事件中,如果触摸点的位置不在mLine上,则不进行拦截,触摸事件会传递到fragment中的控件中去,如果在mLine上,则会 return true;进行拦截,不会把触摸事件传递到fragment中。
在触摸的ACTION_MOVE事件中,frameLayout0的高度就等于移动的触摸点的y值减去状态栏高度,再减去触摸点距离mline顶部的值。frameLayout1的高度等于屏幕高度减去触摸点的y值,再减去触摸点距离mline底部的值。下图可见
触摸屏幕示意图
两个layout的高度设置后,requestLayout方法触发重新布局操作就实现高度的改变了。


至此功能完成,但一些细节就需要自己去添加了,比如线的高度以及触摸后的动画,还有线移动到屏幕底部或顶部后退出分屏状态等等,。。