如何将值从recyclerview项目传递到另一个活动

时间:2015-08-27 02:58:29

标签: java android parameter-passing android-recyclerview

当我们点击recyclerview项目时,我试图将recyclerview项目中的值传递给另一个活动。在这里,我使用OnItemTouchListener

我从JSON检索数据并将其解析为ArrayList。我保存了5个参数。 Title,ID,Rating,ReleaseDate,urlPoster,但是现在我只显示来自urlposter的2个参数,标题和图像。

我想将其他参数传递给另一个活动,但我无法找到如何做到这一点。

还有另外一个类似这样的问题(Values from RecyclerView item to other Activity),但他使用OnClick,而不是OnItemTouch,他在ViewHolder中这样做。我在互联网上的某处读到,这不是正确的事情。

这是我的代码

public class Tab1 extends Fragment {

    private static final String ARG_PAGE = "arg_page";
    private static final String STATE_MOVIES = "state movies";
    private TextView txtResponse;
    private String passID;

    // Progress dialog
    private ProgressDialog pDialog;


    //private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
    private String urlJsonArry = "http://api.themoviedb.org/3/movie/popular?api_key=someapikeyhere";
    private String urlJsonImg = "http://image.tmdb.org/t/p/w342";

    // temporary string to show the parsed response
    private String jsonResponse = "";

    RecyclerView mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;
    RecyclerView.Adapter mAdapter;

    private ArrayList<Movies> movies = new ArrayList<Movies>();


    public Tab1() {
        // Required empty public constructor
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(STATE_MOVIES, movies);
    }

    public static Tab1 newInstance(int pageNumber){

        Tab1 myFragment = new Tab1();
        Bundle arguments = new Bundle();
        arguments.putInt(ARG_PAGE, pageNumber);
        myFragment.setArguments(arguments);
        return myFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
    }


    /**
     * Method to make json object request where json response starts wtih {
     * */
    private void makeJsonObjectRequest() {

        showpDialog();

        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonArry, new Response.Listener<JSONObject>() {


            @Override
            public void onResponse(JSONObject response) {
                //Log.d(TAG, response.toString());

                try {

                    JSONArray result = response.getJSONArray("results");

                    //Iterate the jsonArray and print the info of JSONObjects
                    for(int i=0; i < result.length(); i++){
                        JSONObject jsonObject = result.getJSONObject(i);

                        String id = jsonObject.getString("id");
                        String originalTitle = jsonObject.getString("original_title");
                        String releaseDate = jsonObject.getString("release_date");
                        String rating = jsonObject.getString("vote_average");
                        String urlThumbnail = urlJsonImg + jsonObject.getString("poster_path");

                        //jsonResponse = "";
                        jsonResponse += "ID: " + id + "\n\n";
                        jsonResponse += "Title: " + originalTitle + "\n\n";
                        jsonResponse += "Release Date: " + releaseDate + "\n\n";
                        jsonResponse += "Rating: " + rating + "\n\n";
                }
                    //Toast.makeText(getActivity(),"Response = "+jsonResponse,Toast.LENGTH_LONG).show();
                    parseResult(response);

                }catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(),"Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
                hidepDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getActivity(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                // hide the progress dialog
                hidepDialog();
            }
        });

        // Adding request to request queue
        VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
    }


    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse);
        //makeJsonArrayRequest();

        // Calling the RecyclerView
        mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view_movie);
        mRecyclerView.setHasFixedSize(true);

        // The number of Columns
        mLayoutManager = new GridLayoutManager(getActivity(),2);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new MovieAdapter(getActivity(),movies);
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
            @Override
            public void onMovieClick(View view, int position) {
                Toast.makeText(getActivity(), "Kepencet " + position, Toast.LENGTH_SHORT).show();

                **//what to do here?**
            }

            @Override
            public void onMovieLongClick(View view, int position) {
                Toast.makeText(getActivity(),"Kepencet Lama "+position,Toast.LENGTH_LONG).show();
            }
        }));

        makeJsonObjectRequest();

        if (savedInstanceState!=null){
            movies=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
            mAdapter.notifyDataSetChanged();
        }
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.tab_1, container, false);


        return view;
    }

    private void parseResult(JSONObject response) {
        try {
            JSONArray arrayMovies = response.getJSONArray("results");


            if (movies == null) {
                movies = new ArrayList<Movies>();
            }



            for (int i = 0; i < arrayMovies.length(); i++) {

                JSONObject currentMovies = arrayMovies.getJSONObject(i);

                Movies item = new Movies();
                item.setTitle(currentMovies.optString("original_title"));
                item.setRating(currentMovies.optString("vote_average"));
                item.setReleaseDate(currentMovies.optString("release_date"));
                item.setId(currentMovies.optString("id"));
                item.setUrlThumbnail(urlJsonImg+currentMovies.optString("poster_path"));
                movies.add(item);
                mAdapter.notifyDataSetChanged();

                //Toast.makeText(getActivity(),"Movie : "+movies,Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
        private GestureDetector mGestureDetector;
        private ClickListener mClickListener;


        public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.mClickListener = clickListener;
            mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
                    if (child!=null && clickListener!=null){
                        clickListener.onMovieLongClick(child,recyclerView.getChildAdapterPosition(child));
                    }
                    super.onLongPress(e);
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
                mClickListener.onMovieClick(child,rv.getChildAdapterPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

    public static interface ClickListener{
        public void onMovieClick(View view, int position);
        public void onMovieLongClick(View view, int position);
    }

}

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:4)

您需要将其他两个值添加到intent中的包中。所以像这样:

Intent intent = new Intent(getActivity(), YourNextActivity.class);
intent.putExtra("movie_id_key", movies.get(position).getId); //you can name the keys whatever you like
intent.putExtra("movie_rating_key", movies.get(position).getRating); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
intent.putExtra("movie_release_date_key", movies.get(position).getReleaseDate);
startActivity(intent)

在您的新活动中,只需执行此操作即可检索:

 String id = getIntent().getExtras().getString("movie_id_key");

答案 1 :(得分:0)

在启动活动的意图中将它们添加为额外内容:

Intent intent = new Intent(currentActivity, targetActivity);
// Sree was right in his answer, it's putExtra, not putStringExtra. =(
intent.putExtra("title", title); 
// repeat for ID, Rating, ReleaseDate, urlPoster
startActivity(intent);

然后用

在其他活动的onCreate中将它们拉出来
Intent startingIntent = getIntent();
String title = startingIntent.getStringExtra("title"); // or whatever.

回应以下评论: 我不是100%肯定你是如何实现它的,但看起来你有onclick处理程序传递位置和视图引用,对吧?根据需要调整它,但基本上......:

public void onClick(View v, int position){
    Movie m = movies.get(position);
    Intent intent = new Intent(v.getContext(), AnotherActivity.class);
    intent.putExtra("my_movie_foo_key", m.getFoo());
    intent.putExtra("my_movie_bar_key", m.getBar());
    // etc.
    v.getContext().startActivity(intent);
}

只要你有一个有效的上下文引用(并且他们无法点击没有有效上下文的视图),你就可以从任何你喜欢的地方开始一个活动。