片段每次更改方向时都会添加选项菜单项

时间:2016-03-12 13:13:06

标签: android android-fragments

我在我的应用中遇到了一个错误,每次我更改详细活动的方向时,共享操作项都会添加到操作栏中。

当我开始详细活动并附加片段时,这应该只发生一次。出于某种原因,每次我改变方向时都会发生这种情况。 我知道当我改变方向时,我实际上正在摧毁并重新创建活动,但是遵循这个逻辑,每当我改变方向时,共享行动项目也应该被销毁,不应该被摧毁吗?

这是我的详细活动片段:

$ ls -b
\177.txt

我的详细活动如下:

/**
 * Fragment where the information about a selected movie will be displayed
 */
public class DetailActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int MY_LOADER_ID = 2;
    private static final int NON_FAVORITE = 0;


    List<Trailer> mTrailerList;
    List<Review> mReviewList;
    TrailerAdapter mTrailerAdapter;
    ReviewAdapter mReviewAdapter;
    Movie mMovie;
    private final int FAVORITE = 2;



    @Bind(R.id.movie_name) TextView mMovieTitle;
    @Bind(R.id.release_date) TextView mReleaseDate;
    @Bind(R.id.plot_synopsis) TextView mSynopsis;
    @Bind(R.id.vote_average) TextView mRating;
    @Bind(R.id.movie_thumbnail) ImageView mMovieThumbnail;
    private String mMovieId;
    private boolean FAVORITE_MOVIE = false;
    private ShareActionProvider mShareActionProvider;

    public DetailActivityFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mMovieId = getActivity().getIntent().getStringExtra(MovieListFragment.EXTRA_MOVIE);

        Cursor trailerCursor = getActivity().getContentResolver().query(
                TrailersEntry.CONTENT_URI,
                null,
                TrailersEntry.COLUMN_MOVIE_ID + " = ?",
                new String[] {mMovieId},
                null
        );

        Cursor reviewCursor = getActivity().getContentResolver().query(
                ReviewsEntry.CONTENT_URI,
                null,
                ReviewsEntry.COLUMN_MOVIE_ID + " = ?",
                new String[]{mMovieId},
                null
        );

        mTrailerList = Utility.getTrailersFromCursor(trailerCursor);
        mReviewList = Utility.getReviewsFromCursor(reviewCursor);

        getLoaderManager().initLoader(MY_LOADER_ID, null, this);

        //If the movie is a favorite, we will change the appearance of the favorite button and its callback
        Cursor checkFavouriteCursor = getActivity().getContentResolver().query(
                MoviesEntry.CONTENT_URI,
                null,
                MoviesEntry.COLUMN_MOVIE_ID + " = ? AND " + MoviesEntry.COLUMN_MOVIE_TYPE + " = ?",
                new String[] {mMovieId,String.valueOf(FAVORITE)},
                null
        );
        if (checkFavouriteCursor != null && checkFavouriteCursor.getCount() >0) {
            FAVORITE_MOVIE = true;
            //Free cursor for resources
            checkFavouriteCursor.close();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.detail_fragment, menu);
        // Retrieve the share menu item
        MenuItem menuItem = menu.findItem(R.id.action_share);

        // Get the provider and hold onto it to set/change the share intent.
        mShareActionProvider =
                (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

        // Attach an intent to this ShareActionProvider.  You can update this at any time,
        // like when the user selects a new piece of data they might like to share.
        if (mShareActionProvider != null ) {
            mShareActionProvider.setShareIntent(createShareTrailerIntent());
        }
    }

    private Intent createShareTrailerIntent() {
        if (mTrailerAdapter.getCount() == 0) return null;
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, mTrailerAdapter.getItem(0).getTrailerPath());
        return shareIntent;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);

        //We target the appropriate views
        ButterKnife.bind(this, rootView);

        //Initialize the trailer adapter
        mTrailerAdapter = new TrailerAdapter(
                getContext(),
                R.id.trailer,
                (ArrayList<Trailer>) mTrailerList,
                inflater
        );
        //Initialize the trailer adapter
        mReviewAdapter = new ReviewAdapter(
                getContext(),
                R.id.review_holder,
                (ArrayList<Review>) mReviewList,
                inflater
        );

        ListView trailerListView = (ListView) rootView.findViewById(R.id.trailer_listview);
        ListView reviewListView = (ListView) rootView.findViewById(R.id.review_listview);
        trailerListView.setAdapter(mTrailerAdapter);
        reviewListView.setAdapter(mReviewAdapter);

        //We assign a callback method when the favourites_button is clicked
        final Button favouritesButton = (Button) rootView.findViewById(R.id.favourites_button);
        updateButtonStyling(favouritesButton);

        favouritesButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateMovieAsFavourite(mMovie);
                updateButtonStyling(favouritesButton);
            }
        });

        //We assign a callback method to the trailer elements
        trailerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Trailer trailer = (Trailer) parent.getItemAtPosition(position);
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trailer.getTrailerPath())));
            }
        });

        //If the movie we have selected


        return rootView;
    }

    //Method to save a movie into the database
    private void updateMovieAsFavourite(Movie movie) {

        ContentValues values = new ContentValues();
        values.put(MoviesEntry.COLUMN_MOVIE_ID, movie.getMovieId());
        values.put(MoviesEntry.COLUMN_POSTER_URL,movie.getUrlPath());
        values.put(MoviesEntry.COLUMN_TITLE, movie.getOriginalTitle());
        values.put(MoviesEntry.COLUMN_PLOT,movie.getPlotSynopsis());
        values.put(MoviesEntry.COLUMN_RATING_AVERAGE, movie.getUserRating());
        values.put(MoviesEntry.COLUMN_RATING_COUNT, movie.getVoteCount());
        values.put(MoviesEntry.COLUMN_RELEASE_DATE, movie.getReleaseDate());
        //Actually updated field, marking movie as a favorite
        if (FAVORITE_MOVIE) {
            values.put(MoviesEntry.COLUMN_MOVIE_TYPE, NON_FAVORITE);
        } else {
            values.put(MoviesEntry.COLUMN_MOVIE_TYPE, FAVORITE);
        }
        //Return value from the insertion
        int numrows = 0;
        //Actual insertion, if the movie is not saved, we do it now
        try {
            getActivity().getContentResolver().update(
                    MoviesEntry.CONTENT_URI,
                    values,
                    MoviesEntry.COLUMN_MOVIE_ID + " = ?",
                    new String[]{String.valueOf(movie.getMovieId())}
            );
            if (FAVORITE_MOVIE) {
                Toast.makeText(getActivity(),
                        String.format(
                                "%s removed from your favorites list",
                                movie.getOriginalTitle()),
                        Toast.LENGTH_LONG
                ).show();
            } else {
                Toast.makeText(getActivity(),
                        String.format(
                                "%s added to your favorites list",
                                movie.getOriginalTitle()),
                        Toast.LENGTH_LONG
                ).show();
            }


        } catch (SQLException e) {e.printStackTrace();}
        //Clicking the button changes wether the movie is a favourite or not
        FAVORITE_MOVIE = !FAVORITE_MOVIE;
    }

    private void updateButtonStyling(Button button) {
        if (FAVORITE_MOVIE) {
            button.setText(R.string.remove_favorite);
            button.setBackgroundColor(getResources().getColor(R.color.danger_button));
        } else {
            button.setText(R.string.favorite);
            button.setBackgroundColor(getResources().getColor(R.color.success_button));
        }
    }


    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(getContext(),
                MoviesEntry.CONTENT_URI,
                null,
                MoviesEntry.COLUMN_MOVIE_ID + " = ?",
                new String[] {mMovieId},
                null
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

        mMovie = Utility.makeMovieFromCursor(data);

        if (mMovie != null) {
            mMovieTitle.setText(Html.fromHtml("<b>Original Title: </b>" + mMovie.getOriginalTitle()));
            mReleaseDate.setText(Html.fromHtml("<b>Release date: </b>" + mMovie.getReleaseDate()));
            mSynopsis.setText(Html.fromHtml("<b>Synopsis: </b><br></br>" + mMovie.getPlotSynopsis()));
            mRating.setText(Html.fromHtml("<b>Rating: </b>"
                    + String.format("%.2f / 10 - Based on %d reviews",
                    mMovie.getUserRating(),
                    mMovie.getVoteCount()
            )));
            Picasso.with(getContext())
                    .load(mMovie.getUrlPath())
                    .resize(300,450)
                    .into(mMovieThumbnail);
        }

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }
}

共享操作项所在的XML文件是:

public class DetailActivity extends AppCompatActivity {
    public final String DETAIL_TAG = "detail fragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // We include the fragment into the Activity's layout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.detail_container, new DetailActivityFragment(),DETAIL_TAG )
                .commit();

        // We display the up button but we get rid of the activity name as we'll use an icon
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }
}

如果你能指出我正确的方向,我会很感激。

非常感谢。

0 个答案:

没有答案