使用AsyncTask和导航抽屉的片段 - 最佳实践

时间:2015-07-14 13:02:46

标签: android performance android-fragments android-asynctask navigation-drawer

我写这个问题因为我想知道哪个是管理这个上下文的最佳方式:我有一个带导航抽屉的MainActivity,每当我在Navigation Drawer中选择一个项目时,我创建一个新片段并通过FragmentTransaction I用新的片段替换上一个片段。

现在,在每个片段中,我都有一个执行某项任务的AsyncTask(例如从Web下载数据或在本地sqlite数据库上执行查询)。

我的问题是:当我按下导航抽屉中的元素时,如何避免每次重新创建片段并重新启动AsyncTask?哪种方法可以解决这种情况呢?

当我按导航抽屉中的项目时,这是我在MainActivity中用来显示片段的方法:

private void displayView(int index) {

    Fragment f = null;

    switch(index) {
        case 1:
            f = Fragment1.newInstance();
            break;
        case 2:
            f = Fragment2.newInstance();
            break;
    }

    if(f !=  null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.container, f);

        ft.commit();
    }
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

隐藏片段是删除它的另一种方法。删除(如果没有添加到backstack)会导致片段被完全拆除(暂停,停止,destroyView,销毁,分离)。隐藏并不会改变片段的生命周期状态,只是让它不可见。 getSupportFragmentManager() .beginTransaction() .hide(oldSelectedFrag) .show(newSelectedFrag) .commit(); 方法为hide()show()。最初,您将添加两个片段,然后隐藏未选择的片段。从导航抽屉中选择片段时,如果它尚未显示,则会隐藏旧选择并使新选择可见。像这样:

Fragment

使用isHidden()可以获得片段的可见/隐藏状态。还有一个FragmentManager回调:onHiddenChanged()。请记住,当片段被隐藏时,它仍然处于启动或恢复状态的意义上。您可能希望使用隐藏状态来禁用刷新或仅在可见时才需要的其他操作。如果片段有一个选项菜单,您可能还希望在隐藏片段时使用setMenuVisibility()禁用它。我不认为 public class ExpListAdapter extends BaseExpandableListAdapter { private ArrayList<ArrayList<String>> mGroups; private ArrayList<DeviceObject> deviceObList; private ArrayList<RoomSuggestion> roObjList; private Context mContext; public ExpListAdapter (Context context,ArrayList<ArrayList<String>> groups, ArrayList<DeviceObject> deviceObList, ArrayList<RoomSuggestion> roObjList){ mContext = context; mGroups = groups; this.deviceObList = deviceObList; this.roObjList = roObjList; } @Override public int getGroupCount() { return mGroups.size(); } @Override public int getChildrenCount(int groupPosition) { return mGroups.get(groupPosition).size(); } @Override public Object getGroup(int groupPosition) { return mGroups.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return mGroups.get(groupPosition).get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.group_view, null); } if (isExpanded){ //Изменяем что-нибудь, если текущая Group раскрыта } else{ //Изменяем что-нибудь, если текущая Group скрыта } Typeface lightFace = Typeface.createFromAsset(mContext.getAssets(), "font/GothamProLight.ttf"); TextView textGroup = (TextView) convertView.findViewById(R.id.textGroup); textGroup.setTypeface(lightFace); textGroup.setText("Thereses gate 46"); return convertView; } @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.child_view, null); } Typeface mediumFace = Typeface.createFromAsset(mContext.getAssets(), "font/GothamProMedium.ttf"); TextView textChild = (TextView) convertView.findViewById(R.id.textChild); textChild.setTypeface(mediumFace); textChild.setText( mGroups.get(groupPosition).get(childPosition) ); RelativeLayout rl = (RelativeLayout) convertView.findViewById(R.id.bg_button_screen); if( !deviceObList.get(childPosition).getProduct_id().equals("0") ) { rl.setBackgroundColor(Color.parseColor("#4fcc54")); View linearLayoutG = convertView.findViewById(R.id.container); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(10, 0, 10, 30); linearLayoutG.setLayoutParams(layoutParams); RelativeLayout spinnerOpen = (RelativeLayout) convertView.findViewById(R.id.spinnerOpen); View linearLayout = convertView.findViewById(R.id.spinnerL); ImageView imageS = (ImageView)convertView.findViewById(R.id.spinnerImage); imageS.getLayoutParams().width = 20; imageS.getLayoutParams().height = 20; imageS.setImageResource(R.drawable.spin_ok); ArrayList<String> list = new ArrayList<String>(); for(int i = 0; i < roObjList.size(); i++) { list.add(roObjList.get(i).getName() ); } final Spinner spinner = new Spinner(mContext); //Make sure you have valid layout parameters. spinner.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100)); spinner.setBackgroundResource(R.drawable.bg_spinner); ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(mContext, R.layout.spinner_item, list); spinner.setAdapter(spinnerArrayAdapter); //open spinner spinnerOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { spinner.performClick(); } }); ((LinearLayout) linearLayout).addView(spinner); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.e("selected", String.valueOf(parent.getItemAtPosition(position)) ); Log.e("childPosition", String.valueOf(childPosition)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } else { rl.setBackgroundColor(Color.parseColor("#e5910d")); } return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } 会自动为您做这件事。