这次我主要遇到的问题是fragment的平滑切换,根据一大堆的用户体验什么的来说就是在左右滑动切换activit时,基本体验是没fragment好的,所以在用fragment做切换的时候我遇到的问题是,按返回键时,要确定是切换到了第一个fragment才退出activity,如果用到fragment的堆栈,多次向一个方向滑动,监听返回键返回前一个fragment,会出现bug的,一直滑动一直压当前fragment,(ps:可能是小y太菜,各位大腿谅解,顺便给我更牛b的方法,给点注释,看鸿洋大哥的着实。。。看不到,太菜了不好意思哈),然后我就用死办法,。。
public class MainActivityLj extends Activity { private TextView text1; private boolean flag = true; private Fragment_two mFriend; private Frgment_one mWeixin; //手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2) float x1 = 0; float x2 = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main_lj); // 设置默认的Fragment setDefaultFragment(); findViewById(R.id.right_return).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void setDefaultFragment() { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mWeixin = new Frgment_one(); transaction.replace(R.id.id_fragment_title, mWeixin); transaction.commit(); } @Override public boolean onTouchEvent(MotionEvent event) { //继承了Activity的onTouchEvent方法,直接监听点击事件 if(event.getAction() == MotionEvent.ACTION_DOWN) { //当手指按下的时候 x1 = event.getX(); } if(event.getAction() == MotionEvent.ACTION_UP) { //当手指离开的时候 x2 = event.getX(); if(x1 - x2 > 50) { if(flag){ FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mFriend = new Fragment_two(); transaction.replace(R.id.id_fragment_title, mFriend); transaction.commit(); text1 = (TextView)findViewById(R.id.right_tv1); text1.setText("热点入网"); flag = false; } }else if(x2 - x1 > 50){ if(!flag){ FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mWeixin = new Frgment_one(); transaction.replace(R.id.id_fragment_title, mWeixin); transaction.commit(); text1 = (TextView)findViewById(R.id.right_tv1); text1.setText("智联入网"); flag = true; } } } return false; } @Override public void onBackPressed() { if(!flag){ FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mWeixin = new Frgment_one(); transaction.replace(R.id.id_fragment_title, mWeixin); transaction.commit(); flag = true; text1 = (TextView)findViewById(R.id.right_tv1); text1.setText("智联入网"); }else if(flag){ super.onBackPressed(); } } }
开始定义个flag,反正只是一个标记啦,返回键判断就ok了,办法是复杂了点,这也说明了需要各位大腿给我更好的办法呀,谢谢,(注:还可以用visible、invisible、gone,等属性隐藏布局,通过事件激发,调整布局的属性,效果也是差不多跟fragment差不多啦,貌似还减少了代码呢,)谢谢