說的不是安卓系統的應用分屏功能,而是在應用內一個界面想要分屏查看,例如在看文章答題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方法觸發重新佈局操作就實現高度的改變了。
至此功能完成,但一些細節就需要自己去添加了,比如線的高度以及觸摸後的動畫,還有線移動到屏幕底部或頂部後退出分屏狀態等等,。。