网上搜索侧滑关闭Activity,几乎没有系统状态栏跟随页面一起联动的,有明显的撕裂感,而这里则是状态栏跟随页面联动的,说来集成也是简单,等会你就知道了。
个人习惯,写博客前喜欢先截图
1.首先以项目的形式导入到你的项目中
2.然后在你要侧滑的Activity集成SwipeBackActivity,注意只要集成就好的,其他的什么都不要你写,就能实现侧滑了
现在已经把SwipeBackActivity库上传到jCenter上去了,不想下载的伙伴可以直接使用compile ‘org.dync.kathline:swipebackactivity:1.0.1’进行依赖
下面列出代码:
Mainactivity.java
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
}
public void click(View view) {
if (view.getId() == R.id.button) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
} else {
startActivityForResult(new Intent(MainActivity.this, ThirdActivity.class), 1);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String result = data.getStringExtra("result");
if (requestCode == 1 && resultCode == 0) {
textView.setText(result);
}
}
}
SecondActivity.java
public class SecondActivity extends SwipeBackActivity {
private ViewPager viewPager;
private int []imageIdArray;//图片资源的数组
private List<View> viewList;//图片资源的集合
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
viewPager = (ViewPager)findViewById(R.id.viewpager);
//此处修改状态栏颜色
setStatusBarColor(getResources().getColor(R.color.colorPrimary));
imageIdArray = new int[]{R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
viewList = new ArrayList<>();
//获取一个Layout参数,设置为全屏
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
//循环创建View并加入到集合中
int len = imageIdArray.length;
for (int i = 0;i<len;i++){
//new ImageView并设置全屏和图片资源
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(params);
imageView.setBackgroundResource(imageIdArray[i]);
//将ImageView加入到集合中
viewList.add(imageView);
}
viewPager.setAdapter(new ViewPagerAdapter(viewList));
}
}
ThirdActivity.java
public class ThirdActivity extends SwipeBackActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
}
@Override
public void dothingBeforeFinish() {//这里是你要返回一些数据个启动的那个Activity,你可以在此做操作
super.dothingBeforeFinish();
Intent intent = new Intent();
intent.putExtra("result", "来自ThirdActivity返回的值");
setResult(0, intent);
}
}
代码是不是很简单,这样就轻易的实现了沉浸式侧滑了。至于侧滑的Activity状态栏为什么是灰色的,是因为我在SwipeBackActivity中写死了,你可以修改此颜色。通过在onCreate()方法中调用
setStatusBarColor(getResources().getColor(R.color.colorPrimary));修改状态栏的颜色,参照上面的SecondActivity.java代码中的onCreate()。
好了,在此附上github源码,喜欢的请start、fork。
https://github.com/DyncKathline/SwipeBackLayout
转载请注明出处,谢谢!