片段叫了两声 [英] Fragment called twice

查看:215
本文介绍了片段叫了两声的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开始从活动片段,但每次我启动应用程序,该片段启动两次。这当我运行一个平板设备上的应用程序只发生。
有谁知道能这个问题是什么,我怎么能解决呢?

I'm trying to start a fragment from an activity, but everytime I start the app, the fragment is started twice. This is only happening when I run the app on a tablet device. Does anyone know what can this issue be, and how can I solve it?

下面是我的code:

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()被调用两次,; 被称为两次。

推荐答案

当你开始你的活动你打电话:

When you're starting your Activity you're calling:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

在调用这个方法,你的活动可能是重新开始,如果平板电脑处于纵向模式时,应用程序启动。这是在文档说。

When calling this method, your Activity is possibly restarted, if the tablet is in portrait mode when the app starts up. This is stated in the documentation.

当你活动重新启动,的onCreate 再次打来电话,你的片段再次创建。

When you're Activity is restarted, onCreate is called once again and your Fragment is created once again.

在一个侧面说明:这不是很好的做法,迫使你的应用程序到一个特定的方向

On a side-note: It's not good practice to force your app into a specific orientation.

这篇关于片段叫了两声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆