2015-08-27 60 views
1

我試圖在點擊recyclerview項目時將recyclerview項目中的值傳遞給另一個活動。這裏我使用OnItemTouchListener如何將recyclerview項目中的值傳遞給另一個活動

我從JSON中檢索數據並將其解析到ArrayList中。我保存了5個參數。標題,ID,評分,ReleaseDate,urlPoster,但現在我只顯示2個參數,標題和來自urlposter的圖像。

我想將其他參數傳遞給另一個活動,但我無法找到如何做到這一點。

還有另外一個類似的問題(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); 
    } 

} 

任何幫助,將不勝感激。謝謝!

回答

4

您需要將其他兩個值添加到意圖中的包中。因此,像這樣:

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"); 
+0

但我直接將解析的數據存儲到RecyclerView,查看private void parseResult(JSONObject response)。如何從那裏獲取項目數據? –

+0

是在您的recyclerview中顯示的電影項目嗎? – Sree

+0

是的,他們正在出現。我已經找到了解決方案。 只需將代碼中的「id」更改爲movies.get(position).getId(); 謝謝 –

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); 

然後用

Intent startingIntent = getIntent(); 
String title = startingIntent.getStringExtra("title"); // or whatever. 

拉出來的其他活動的OnCreate迴應下面的評論: 我不是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); 
} 

只要你有一個有效的範圍內引用(他們不能在一個視圖中單擊沒有一個有效的上下文),你就可以開始從活動無論你喜歡哪裏。

+0

我直接存儲解析數據到RecyclerView,看看私人無效parseResult(JSONObject的響應)。如何從那裏獲得每個項目的「ID」,「標題」? –

+0

我上面編輯過。只要你有一個有效的上下文(你可以從onclick傳入的視圖中獲取),你可以從任何地方開始一個活動。 – MrPlow

相關問題