片段叫了两次

时间:2014-08-28 18:54:12

标签: android android-fragments

我正在尝试从活动中启动片段,但每次启动应用程序时,片段都会启动两次。这只发生在我在平板电脑设备上运行应用程序时。 有谁知道这个问题是什么,我该如何解决呢?

这是我的代码:

public class TestSearch extends FragmentActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    // private ActionBarDrawerToggle mDrawerToggle;
    private ArrayList<Device> devices;
    private ArrayList<Recepie> recepies, mainRecepies;
    private ArrayList<Recepie> searchResult;
    private LinearLayout sideWrapper;
    private EditText src;

    ArrayList<Categories> cats;

    boolean isTablet = false;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_search);
        Log.v("--", "started");
        if (Constants.isTablet(this)) {
            isTablet = true;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        devices = new ArrayList<Device>();
        recepies = new ArrayList<Recepie>();
        mainRecepies = new ArrayList<Recepie>();

        devices = (ArrayList<Device>) getIntent().getSerializableExtra(
                Constants.DEVICES_EXTRA);

        recepies = getIntent().getParcelableArrayListExtra("all");
        mainRecepies = getIntent().getParcelableArrayListExtra(
                Constants.MAINRECEPIES);
        // mTitle = mDrawerTitle = getTitle();
        cats = new ArrayList<Categories>();
        cats = (ArrayList<Categories>) getIntent().getSerializableExtra("cats");

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        sideWrapper = (LinearLayout) findViewById(R.id.listwraper);

        // set a custom shadow that overlays the main content when the drawer
        // opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
                GravityCompat.START);

        // set up the drawer's list view with items and click listener

        // View header = getLayoutInflater().inflate(R.layout.search_item,
        // null);
        src = (EditText) findViewById(R.id.search_est);
        src.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    Log.v("--", "Start search");
                    if (src.getText().length() > 0) {
                        searchResult = new ArrayList<Recepie>();
                        final ProgressDialog progress = ProgressDialog.show(
                                TestSearch.this,
                                getString(R.string.please_wait),
                                getString(R.string.getting_search_results),
                                true);
                        new AsyncTask<Void, Void, Void>() {
                            protected void onPreExecute() {
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.hideSoftInputFromWindow(
                                        src.getWindowToken(), 0);
                            };

                            @Override
                            protected Void doInBackground(Void... params) {
                                searchResult = getSearchResults(src.getText()
                                        .toString());
                                return null;
                            }

                            protected void onPostExecute(Void result) {

                                // set screen to search fragment
                                Fragment fragment = new SideSearchFragment();
                                Bundle args = new Bundle();
                                args.putString("cat-title", src.getText()
                                        .toString());
                                args.putSerializable("cats", cats);
                                args.putBoolean(Constants.SEARCH, true);
                                args.putParcelableArrayList(
                                        Constants.SEARCH_RESULTS, searchResult);
                                fragment.setArguments(args);
                                progress.dismiss();
                                FragmentManager fragmentManager = getFragmentManager();
                                fragmentManager.beginTransaction()
                                        .add(R.id.content_frame, fragment)
                                        .addToBackStack("search_results")
                                        .commit();

                                // setTitle(mPlanetTitles[position]);
                                mDrawerLayout.closeDrawer(sideWrapper);

                                // clear search text and hide keyboard
                                src.setText("");

                            };
                        }.execute();
                    }
                    return true;
                }
                return false;
            }
        });

        // mDrawerList.addHeaderView(header);
        SideAdapter adapter = new SideAdapter(this, cats);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        initActionBar();
        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(false);
        getActionBar().setHomeButtonEnabled(true);

        if (savedInstanceState == null) {
            showMainFragment();
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            selectItem(position);
        }
    }

    private void showFavoritesFragment() {

        Fragment fragment = new FavoritesFragment();
        Bundle args = new Bundle();
        args.putSerializable("all", recepies);
        args.putBoolean("search", true);
        args.putSerializable("cats", cats);
        fragment.setArguments(args);
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().add(R.id.content_frame, fragment)
                .addToBackStack("favorites").commit();
    }

    private void showMainFragment() {
        Fragment fragment = new MainFragment();
        Bundle args = new Bundle();
        Log.v("--", "START MAIN FRAGMENT !!");
        args.putParcelableArrayList("all", recepies);
        args.putSerializable("cats", cats);
        args.putParcelableArrayList(Constants.MAINRECEPIES, mainRecepies);
        args.putBoolean("search", true);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();

        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment)
                .commit();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            if (mDrawerLayout.isDrawerOpen(sideWrapper))
                mDrawerLayout.closeDrawer(sideWrapper);
            else
                mDrawerLayout.openDrawer(sideWrapper);
            return true;

        case R.id.main_action_fav:

            showFavoritesFragment();
            return true;
        case R.id.main_action_choose_cats:
            Intent intent = new Intent(this, CircleListActivity.class);
            intent.putExtra(Constants.DEVICES_EXTRA, devices);
            intent.putExtra("cats", cats);
            startActivity(intent);
            // finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private void initActionBar() {
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#e91a34")));
        getActionBar().setCustomView(R.layout.actionbar_custom_view_home);
        // actionBar.setcu
        getActionBar().setDisplayShowTitleEnabled(false);
        getActionBar().setDisplayShowCustomEnabled(true);
        getActionBar().setDisplayUseLogoEnabled(false);
        getActionBar().setDisplayShowHomeEnabled(true);
        getActionBar().setHomeButtonEnabled(false);
        getActionBar().setIcon(R.drawable.menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putString("cat-title", cats.get(position).getTitle());
        args.putInt(Constants.CATEGORY_ID, cats.get(position).getId());
        args.putSerializable("cats", cats);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().add(R.id.content_frame, fragment)
                .addToBackStack(null).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        // setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(sideWrapper);
    }

    @Override
    public void setTitle(CharSequence title) {
        // mTitle = title;
        // getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        // mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        // mDrawerToggle.onConfigurationChanged(newConfig);
    }

    // This function gets the search results

    public ArrayList<Recepie> getSearchResults(String keyword) {
        ArrayList<Recepie> resultRecepie = new ArrayList<Recepie>();
        JSONParser jParser = new JSONParser();
        // get JSON data from URL
        JSONObject jObj = jParser
                .getJSONObjectFromUrl("http://oursson-recipes.outsourcingfarm.com/index.php/jsoner/getRecipe?query="
                        + keyword);

        try {
            JSONArray withTechnics = jObj.getJSONArray("with_technics");
            JSONArray withoutTechnics = jObj.getJSONArray("without_technics");
            for (int i = 0; i < withTechnics.length(); i++) {
                JSONObject with = withTechnics.getJSONObject(i);
                boolean bool_tehcnics = true;
                if (with.getInt("with_technics") == 1)
                    bool_tehcnics = false;
                boolean my_devices = false;
                if (with.getInt("mydevices") == 1)
                    my_devices = true;
                JSONArray devices = with.getJSONArray("devices");
                ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
                for (int k = 0; k < devices.length(); k++) {
                    devicesIDs.add(Integer.valueOf(devices.getString(k)));
                }

                resultRecepie.add(new Recepie(bool_tehcnics, my_devices, with
                        .getInt("id"), with.getInt("persons"), with
                        .getString("title"),
                        with.getString("preparation_time"), with
                                .getString("image_1"), devicesIDs));
            }

            for (int i = 0; i < withoutTechnics.length(); i++) {
                JSONObject with = withoutTechnics.getJSONObject(i);
                boolean bool_tehcnics = false;
                if (with.getInt("with_technics") == 1)
                    bool_tehcnics = true;
                boolean my_devices = false;
                if (with.getInt("mydevices") == 1)
                    my_devices = true;
                JSONArray devices = with.getJSONArray("devices");
                ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
                for (int k = 0; k < devices.length(); k++) {
                    devicesIDs.add(Integer.valueOf(devices.getString(k)));
                }

                resultRecepie.add(new Recepie(bool_tehcnics, my_devices, with
                        .getInt("id"), with.getInt("persons"), with
                        .getString("title"),
                        with.getString("preparation_time"), with
                                .getString("image_1"), devicesIDs));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultRecepie;
    }

}

我猜测onCreate()被调用两次,函数showMainFragment();被调用两次。

1 个答案:

答案 0 :(得分:0)

当您启动Activity时,您正在致电:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

调用此方法时,如果应用启动时平板电脑处于纵向模式,则可能会重新启动Activity。这在documentation中说明。

重新启动Activity后,再次调用onCreate,再次创建Fragment

侧面说明:强制您的应用进入特定方向并不是一种好习惯。