
接着上一篇项目的进度。上一篇讲了怎样利用fragment来实现下拉菜单。公用菜单,以实现切换主界面数据的功能,这时候遇到的问题是:使用了fragment的切换界面方法。但载入的数据太多。用户从一个界面切换到这个界面的时候。至少有一两秒的卡顿,这是无法忍受的,代码例如以下:
private void initOpenMenuItem(View popupWindow_view) {
DrawableCenterTextView menu_price = (DrawableCenterTextView) popupWindow_view
.findViewById(R.id.menu_price); menu_price.setOnClickListener(new OnClickListener() {
FragmentTransaction transaction; @Override
public void onClick(View v) {
transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, priceFragment);
titleView.setText(priceFragment.getFragmentTitle());
transaction.commit();
popupWindow.dismiss();
}
});
}
上述代码在切换fragment界面的时候,依据fragment的方法api,replace是要又一次生成实例的,这就势必导致数据又一次载入,我们必须得採取隐藏的方式或者加一个进度条来缓解。这里我採用的是fragment提供的hide方法,来实现数据的高速显示,改动代码例如以下:
private void initOpenMenuItem(View popupWindow_view) {
DrawableCenterTextView menu_price = (DrawableCenterTextView) popupWindow_view
.findViewById(R.id.menu_price); menu_price.setOnClickListener(new OnClickListener() {
FragmentTransaction transaction; @Override
public void onClick(View v) {
transaction = manager.beginTransaction();
/*
* qiulinhe:2015年7月21日10:54:51
* 解决切换卡顿的问题
*/
if (!priceFragment.isAdded()) { // 先推断是否被add过
transaction.hide(openPositionFragment).add(R.id.fragment_container, priceFragment).commit(); // 隐藏当前的fragment。add下一个到Activity中
titleView.setText(priceFragment.getFragmentTitle());
} else {
transaction.hide(openPositionFragment).show(priceFragment).commit(); // 隐藏当前的fragment,显示下一个
titleView.setText(priceFragment.getFragmentTitle());
}</span> popupWindow.dismiss();
}
}); }
原理就是:
翻看了Android官方Doc。和一些组件的源码。发现,replace()这种方法仅仅是在上一个Fragment不再须要时採用的简便方法。
正确的切换方式是add()。切换时hide()。add()还有一个Fragment。再次切换时,仅仅需hide()当前,show()还有一个。
这样就能做到多个Fragment切换不又一次实例化:
因为是公司项目。不能上传整个project文件,只是能够參考一下我的解决方案,有相同的问题的同学能够交流一下还有没有更优雅的解决的方法。