简体   繁体   English

无法从RecyclerView项目中打开片段请点击

[英]Can't open fragment from RecyclerView item Click

Hi I have a simple app that features a recyclerView with list items (each representing a "Movie" object. The content for the movie list items is generated from an API call (themoviedb.org). I'm trying to open a "detail fragment" by clicking on a recyclerView list item. I want all of the content from the Movie item clicked to appear in the next fragment as well. Right now when I click the list item, nothing happens. No crash, even. I thought I had set up the listener interface correctly, but maybe that's the problem. Can anyone see where I'm going wrong? Thanks in advance. 嗨,我有一个简单的应用程序,带有带有列表项的recyclerView(每个列表项代表一个“电影”对象。电影列表项的内容是通过API调用(themoviedb.org)生成的。我正在尝试打开“详细信息片段”。我也希望单击电影项目中的所有内容也出现在下一个片段中。现在,当我单击列表项目时,什么也没有发生。甚至没有崩溃。我以为我已经正确设置了侦听器界面,但这可能就是问题所在。有人可以看到我要去哪里了吗?

Here is the Fragment where the RecyclerView (movie list) first appears: 这是RecyclerView(电影列表)首次出现的片段:

public class ResultsFragment extends Fragment {
private RecyclerView mRecyclerView;
Movie_Results_Adapter results_adapter;
ArrayList<Movie> movieList;
onMovieSelectedListener listener;
public ResultsFragment(){
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_layout_1, container, false);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);
    mRecyclerView.setVisibility(View.VISIBLE);
    results_adapter = new Movie_Results_Adapter(movieList, listener);
    listener = new onMovieSelectedListener() {
        @Override
        public void onMovieSelected(Movie selectedMovie) {
            Intent launchIntent = new Intent(getContext(), MovieDetailActivity.class);
            launchIntent.putExtra(MovieDetailActivity.EXTRA_MOVIE, "movie");
            Log.d("PaulsApp", selectedMovie + "");
            launchIntent.putExtra(MovieDetailActivity.NEW_EXTRA, (Serializable) selectedMovie);
            startActivity(launchIntent);
        }
    };
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(results_adapter);
    Log.d("TAGG", "AAAH" + movieList.toString());
    return rootView;
}

public void parseJson(String jsonToParse) throws JSONException {


    JSONObject responseObject= new JSONObject(jsonToParse);
    JSONArray resultsArray = responseObject.getJSONArray("results");
    for(int i = 0; i < resultsArray.length(); i++){
        JSONObject movie = resultsArray.getJSONObject(i);
        String movieName = movie.getString("title");
        String movieReleaseDate = movie.getString("release_date");
        String movieScore = movie.getString("vote_average");
        String moviePopularity = movie.getString("vote_count");
        String movieImage = movie.getString("poster_path");
        String movieDescription = movie.getString("overview");
        Movie movie1 = new Movie(movieName, movieReleaseDate, movieScore, moviePopularity, movieImage, movieDescription);
        movieList.add(movie1);
    }

}

@Override
public void setArguments(Bundle args) {
    movieList = new ArrayList<>();
    String arguments = args.getString("JSON_STRING");
    try {
        parseJson(arguments);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    super.setArguments(args);
}

public interface onMovieSelectedListener{
    public void onMovieSelected(Movie selectedMovie);
}

} }

Here is the RecyclerView Adapter for the "results" fragment: 这是“结果”片段的RecyclerView适配器:

public class Movie_Results_Adapter extends RecyclerView.Adapter<Movie_Results_Adapter.ResultViewHolder>{
    ArrayList<Movie> MovieListArray;
    ResultsFragment.onMovieSelectedListener listener;
    private Activity mActivity;



    public class ResultViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView titleText;
        TextView dateText;
        TextView scoreText;
        TextView popularityText;
        ImageView movieImage;
        public Movie movie;
        public ResultViewHolder(View itemView){
            super(itemView);
            titleText = (TextView) itemView.findViewById(R.id.movie_title_text);
            dateText = (TextView) itemView.findViewById(R.id.movie_date_text);
            scoreText = (TextView) itemView.findViewById(R.id.movie_score_text);
            popularityText = (TextView) itemView.findViewById(R.id.movie_popularity_text);
            movieImage = (ImageView) itemView.findViewById(R.id.movie_image);
        }

        @Override
        public void onClick(View view) {
            if (listener != null) {
                listener.onMovieSelected(MovieListArray.get(getAdapterPosition()));
                Toast.makeText(view.getContext(), "clicked: " + MovieListArray.get(getAdapterPosition()), Toast.LENGTH_SHORT).show();

            }
        }
    }

    public Movie_Results_Adapter(ArrayList<Movie> movieList, ResultsFragment.onMovieSelectedListener listener){
        MovieListArray = movieList;
        this.listener = listener;
    }


    @Override
    public ResultViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_result_list_item, parent, false);

        ResultViewHolder vh = new ResultViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ResultViewHolder holder, int position) {
        holder.titleText.setText(MovieListArray.get(position).getmTitle());
        Log.d("TAGG", MovieListArray.toString());
        holder.dateText.setText("Released "+MovieListArray.get(position).getmReleaseYear());
        holder.scoreText.setText("TMDB Score:  "+MovieListArray.get(position).getmScore());
        holder.popularityText.setText(MovieListArray.get(position).getmPopularity()+" votes");
        Context context = holder.movieImage.getContext();
        Picasso.with(context).load(Constants.TMDB_POSTER+MovieListArray.get(position).getmImage()).into(holder.movieImage);
    }

    @Override
    public int getItemCount() {
        return MovieListArray.size();
    }


}

Here is the detail fragment (and accompanying activity): 这是详细信息片段(以及相应的活动):

package jetsetpaul.movienerd;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

/**
 * Created by pauljoiner on 8/17/16.
 */
public class MovieDetailFragment extends Fragment {
    public String movieTitle;
    public String movieImage;
    public String movieDate;
    public String movieDescription;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.movie_detail_fragment, container, false);
        TextView mTitleText = (TextView) rootView.findViewById(R.id.movie_detail_title);
        ImageView mMovieImage = (ImageView) rootView.findViewById(R.id.movie_detail_image);
        TextView mDateText = (TextView) rootView.findViewById(R.id.movie_detail_release_date);
        TextView mDescriptionText = (TextView) rootView.findViewById(R.id.movie_detail_description);
        mTitleText.setText(movieTitle);
        mDateText.setText(movieDate);
        mDescriptionText.setText(movieDescription);
        Context context = mMovieImage.getContext();
        Picasso.with(context).load(Constants.TMDB_POSTER+movieImage);

        return rootView;
    }
    public void setMovieTitle(String title){
        this.movieTitle = title;
    }
    public void setMovieImage(String image){
        this.movieImage = image;
    }
    public void setMovieDate(String date){
        this.movieDate = date;
    }
    public void setMovieDescription(String description){
        this.movieDescription = description;
    }
}

Activity: package jetsetpaul.movienerd; 活动:包jetsetpaul.movi​​enerd;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

/**
 * Created by pauljoiner on 8/17/16.
 */
public class MovieDetailActivity extends AppCompatActivity {
    public static final String EXTRA_MOVIE = "movie";
    public static final String NEW_EXTRA = "movie2";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_detail);

        Intent i = getIntent();
        if(i.hasExtra(NEW_EXTRA)) {
            Log.d("PaulsApp", "Had Extra!");
            //set the text in my fragment
           Movie movie = (Movie) i.getSerializableExtra(NEW_EXTRA);
            Fragment newFragment = new MovieDetailFragment();

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.detail_fragment, newFragment);
            transaction.commit();
            ((MovieDetailFragment) newFragment).setMovieTitle(movie.getmTitle());
            ((MovieDetailFragment) newFragment).setMovieImage(movie.getmImage());
            ((MovieDetailFragment) newFragment).setMovieDate(movie.getmReleaseYear());
            ((MovieDetailFragment) newFragment).setMovieDescription(movie.getmDescription());

        }
    }
}

I can post more code if necessary. 如果需要,我可以发布更多代码。 Thanks again! 再次感谢!

Your listener needs to be created before your results_adapter 您的监听器需要在results_adapter之前创建

listener = new onMovieSelectedListener() {
    @Override
    public void onMovieSelected(Movie selectedMovie) {
        Intent launchIntent = new Intent(getContext(), MovieDetailActivity.class);
        launchIntent.putExtra(MovieDetailActivity.EXTRA_MOVIE, "movie");
        Log.d("PaulsApp", selectedMovie + "");
        launchIntent.putExtra(MovieDetailActivity.NEW_EXTRA, (Serializable) selectedMovie);
        startActivity(launchIntent);
    }
};
results_adapter = new Movie_Results_Adapter(movieList, listener);

To be honest though, it would be best for your fragment to implement the listener (interface) instead of having to create it by using new onMovieSelectedListener(). 不过,老实说,最好是您的片段实现监听器(接口),而不是必须使用新的onMovieSelectedListener()创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM