学习Fragment途中知道了开源库Fragmentation,本文用于介绍相关的使用方法和注意点。
Fragmentation
版本:2018/3/12-1
滑动退出Fragment:SwipeBackFragment
使用步骤
1、SwipeBackFragment集成
- 可以通过依赖集成
- 也可以直接将项目中的代码添加到自己工程中
2、Fragment需要继承自SwipeBackFragment
public class BlankFragment extends SwipeBackFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
//【注意!】一定要添加该内容
return attachToSwipeBack(view);
}
...
}
3、Activity继承SwipeBackActivity
public class MainActivity extends SwipeBackActivity{
/**
* 限制SwipeBack的条件,默认栈内Fragment数 <= 1时 , 优先滑动退出Activity , 而不是Fragment
*
* @return true: Activity可以滑动退出, 并且总是优先; false: Activity不允许滑动退出
*/
@Override
public boolean swipeBackPriority() {
return super.swipeBackPriority();
}
// 添加Fragment的相关操作
private void addFragment(Fragment fromFragment, Fragment toFragment) {
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.h_fragment_enter, R.anim.h_fragment_exit, R.anim.h_fragment_pop_enter, R.anim.h_fragment_pop_exit)
.add(R.id.main2_activity_container, toFragment, toFragment.getClass().getSimpleName())
.hide(fromFragment)
.addToBackStack(toFragment.getClass().getSimpleName())
.commit();
}
private void loadFragment(Fragment toFragment) {
getSupportFragmentManager().beginTransaction()
.add(R.id.main2_activity_container, toFragment, toFragment.getClass().getSimpleName())
.addToBackStack(toFragment.getClass().getSimpleName())
.commit();
}
// @Override
// public void onAddFragment(Fragment fromFragment, Fragment toFragment) {
// addFragment(fromFragment, toFragment);
// }
}
4、使用自定义style防止出现滑动的黑色页面
- styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
<style name="AppTheme.SwipeBack">
<item name="android:windowBackground">@android:color/darker_gray</item>
<item name="android:windowIsTranslucent">true</item>
</style>
- AndroidManifest.xml
<activity android:name=".MainActivity"
android:theme="@style/AppTheme.SwipeBack" ></activity>
SwipeBackFragment更多方法
// 设置滑动方向
getSwipeBackLayout().setEdgeOrientation(SwipeBackLayout.EDGE_RIGHT); // EDGE_LEFT(默认),EDGE_ALL
// 设置侧滑触摸生效区域 MAX,MED,MIN,custom
setEdgeLevel(SwipeBackLayout.EdgeLevel edgeLevel)
// 滑动过程监听
getSwipeBackLayout().addSwipeListener(new SwipeBackLayout.OnSwipeListener() {
@Override
public void onDragStateChange(int state) {
// Drag state
}
@Override
public void onEdgeTouch(int edgeFlag) {
// 触摸的边缘flag
}
@Override
public void onDragScrolled(float scrollPercent) {
// 滑动百分比
}
});