2

我遵循材料設計。那麼我可以在CardViewonClick()方法中將Fragment替換爲Fragment,並將一些數據從RecyclerView.Adapter傳遞到另一個Fragment如何替換cardview的onClick()上的片段?

這裏是我的代碼:

fragment_states.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    xmlns:ads="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/state" 
    tools:context="nmittal.indiatour.States"> 

    <!--<include android:id="@+id/toolbar"--> 
     <!--layout="@layout/toolbar"/>--> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recyclerView" 
     android:divider="#ffffff" 
     android:orientation= "vertical" 
     android:dividerHeight="1px" 
     android:layout_weight="1" 
     android:gravity= "center_horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 
    <!--android:scrollbars="vertical"--> 
</RelativeLayout> 

States.java

public class States extends Fragment{ 

     private LinearLayoutManager linearLayoutManager; 
     RecyclerView recyclerView; 
     StateRecyclerViewAdapter stateRecyclerViewAdapter; 
     List<StateName> stateNameList; 
     String url1; 
     JSONObject jsonObject; 
     JSONArray cityArray; 
     public static String Key; 

     class GetFixture extends AsyncTask<Void, Void, Void>{ 

      private GetFixture(){ 

      } 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
      } 

      @Override 
      protected Void doInBackground(Void... params) { 

       String json = new AuthJSON().makeServiceCall(States.this.url1, 2); 

       if (json!=null){ 
        try { 
         States.this.jsonObject = new JSONObject(json); 
         Log.d("jsonObject", "new json Object"); 

         States.this.cityArray = States.this.jsonObject.getJSONArray("Credentials"); 
         Log.d("json Array", "User point array"); 
         Log.d("Array Length", String.valueOf(States.this.cityArray.length())); 
         Log.d("len", "getarray length"); 

         for (int i=0; i<States.this.cityArray.length(); i++){ 
          States.Key = States.this.cityArray.getJSONObject(i).getString("AuthKey"); 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
       else { 
        Log.e("JSON Data", "Didn't receive any data from server!"); 
       } 
       return null; 
      } 

      @Override 
      protected void onPostExecute(Void aVoid) { 
       super.onPostExecute(aVoid); 
      } 
     } 
     public States() { 
      // Required empty public constructor 

     } 

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

      recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); 
      recyclerView.setHasFixedSize(true); 

      linearLayoutManager = new LinearLayoutManager(getActivity()); 
      recyclerView.setLayoutManager(linearLayoutManager); 

      stateRecyclerViewAdapter = new StateRecyclerViewAdapter(getDataSet()); 

      recyclerView.setAdapter(stateRecyclerViewAdapter);    
      return view; 
     } 

     public List<StateName> getDataSet() { 
      stateNameList = new ArrayList(); 
      stateNameList.add(new StateName("WestBengal")); 
stateNameList.add(new StateName("Gujarat")); 
stateNameList.add(new StateName("Delhi")); 
stateNameList.add(new StateName("Kerala")); 

      return stateNameList; 
     } 
    } 

card_view.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <android.support.v7.widget.CardView 
     xmlns:card_view="http://schemas.android.com/apk/res-auto" 
     android:layout_width="match_parent" 
     android:layout_height="80dp" 
     android:id="@+id/cardView" 
     android:layout_marginLeft="-3dp" 
     android:layout_marginRight="0dp" 
     android:gravity="center_horizontal" 
     android:focusable="true" 
     android:clickable="true" 
     android:foreground="?android:attr/selectableItemBackground" 
     card_view:cardElevation="4dp" 
     card_view:cardUseCompatPadding="true" 
     card_view:cardCornerRadius="2dp">  

      <TextView 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:padding="8dp" 
       android:textStyle="bold" 
       android:textAlignment="center" 
       android:textAppearance="?android:attr/textAppearanceMedium" 
       android:layout_gravity="center_horizontal" 
       android:gravity="fill" 
       android:text= "" 
       android:textColor="#ffffff" 
       android:layout_centerHorizontal= "true" 
       android:id="@+id/text" /> 

     </android.support.v7.widget.CardView> 

</RelativeLayout> 

StateRecyclerViewAdapter.java

public class StateRecyclerViewAdapter extends RecyclerView.Adapter<StateRecyclerViewAdapter.PlaceViewHolder>{ 

      static int i; 
      private List<StateName> stateNameList; 
      String string; 

      public StateRecyclerViewAdapter(List<StateName> list){ 
       i=1; 
       stateNameList = list; 

      } 

      public PlaceViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){ 

       View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view, viewGroup, false); 
       PlaceViewHolder placeViewHolder = new PlaceViewHolder(itemView); 
       placeViewHolder.cardView.setOnClickListener(new StateRecyclerViewAdapter1(placeViewHolder, viewGroup)); 
       return placeViewHolder; 
      } 

      public void onBindViewHolder(PlaceViewHolder placeViewHolder, int i) { 
       StateName stateName = stateNameList.get(i); 
       placeViewHolder.stateName.setText(stateName.getName()); 
placeViewHolder.cardView.setOnClickListener(new View.OnClickListener(){ 
      @Override 
      public void onClick(View view){ 
       //Here goes your desired onClick behaviour. Like: 
       Toast.makeText(view.getContext(), "You have clicked " + view.getId(), Toast.LENGTH_SHORT).show(); //you can add data to the tag of your cardview in onBind... and retrieve it here with with.getTag().toString().. 
       //You can change the fragment, something like this, not tested, please correct for your desired output: 
       Activity activity = view.getContext(); 
       Fragment CityName = new CityName(); 
       //Create a bundle to pass data, add data, set the bundle to your fragment and: 
       activity.getFragmentManager().beginTransaction().replace(R.id.fragment_container, cityName).addToBackStack(null).commit();  //Here m getting error         
      } 
     }); 
      } 

      @Override 
      public long getItemId(int position) { 
       return 0; 
      } 

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

      @Override 
      public int getItemViewType(int position) { 
       return 0; 
      } 

      public static class PlaceViewHolder extends RecyclerView.ViewHolder { 

       protected TextView stateName; 
       protected CardView cardView; 

       public PlaceViewHolder(View view) { 
        super(view); 

        stateName = (TextView) view.findViewById(R.id.text); 
        cardView = (CardView) view.findViewById(R.id.cardView); 

        switch (StateRecyclerViewAdapter.i) { 
         case CompletionEvent.STATUS_FAILURE: 
          cardView.setCardBackgroundColor(Color.parseColor("#DDEC407A")); 
          i++; 
         case CompletionEvent.STATUS_CONFLICT: 
          cardView.setCardBackgroundColor(Color.parseColor("#DD7986CB")); 
          i++; 
         case CompletionEvent.STATUS_CANCELED: 
          cardView.setCardBackgroundColor(Color.parseColor("#DD5E35B1")); 
          i++; 
         default: 
          cardView.setCardBackgroundColor(Color.parseColor("#DDFF6F00")); 
          StateRecyclerViewAdapter.i = 1; 
        } 

       } 
      } 
     } 

的AndroidManifest.xml:

<activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" 
      android:screenOrientation="portrait" 
      android:configChanges="keyboardHidden|orientation" 
      android:theme="@style/AppTheme.NoActionBar"> 
     </activity> 

我應該怎麼做,以取代Fragments。我在stateRecyclerview課上評論過它應該被替換的地方。 Thx提前!

+0

你想有相同'onClick'行動的所有'CardView's執行? – yennsarah

+0

@Amy是啊! sam onClick查看所有CardView。例如。 OnClick指出,它應該禁止旅遊目的地的清單可見。 –

+0

但是您確實需要取決於哪個'CardView'被點擊的數據,對吧? – yennsarah

回答

9
public class StateRecyclerViewAdapter extends RecyclerView.Adapter<StateRecyclerViewAdapter.PlaceViewHolder>{ 

    static int i; 
    private List<StateName> stateNameList; 
    String string; 

    //You don't need another class for the onClick behaviour: 

    public StateRecyclerViewAdapter(List<StateName> list){ 
     i=1; 
     stateNameList = list; 
    } 

    public PlaceViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){ 

     View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view, viewGroup, false); 
     return new PlaceViewHolder(itemView); 
    } 

    public void onBindViewHolder(PlaceViewHolder placeViewHolder, int i) { 
     StateName stateName = stateNameList.get(i); 
     placeViewHolder.stateName.setText(stateName.getName()); 
     placeViewHolder.cardView.setOnClickListener(new View.OnClickListener(){ 
      @Override 
      public void onClick(View view){ 
       //Here goes your desired onClick behaviour. Like: 
       Toast.makeText(view.getContext(), "You have clicked " + view.getId(), Toast.LENGTH_SHORT).show(); //you can add data to the tag of your cardview in onBind... and retrieve it here with with.getTag().toString().. 
       //You can change the fragment, something like this, not tested, please correct for your desired output: 
       AppCompatActivity activity = (AppCompatActivity) view.getContext(); 
       MyFragment myFragment = new MyFragment(); 
       //Create a bundle to pass data, add data, set the bundle to your fragment and: 
       activity.getSupportFragmentManager().beginTransaction().replace(R.id.yourContainerId, myFragment).addToBackStack(null).commit();          
      } 
     }); 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0;  //you should not return 0 for every item, change it to position or your a possible id, if you have one. 
    } 

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

    @Override 
    public int getItemViewType(int position) { 
     return 0; 
    } 
+0

它的nt採取setOnClickListener() –

+0

Ups,更改添加一個.cardView它,我會改變代碼;) – yennsarah

+0

它沒有采取myFragment太沒有找到替換方法作爲參數 –

0

你可以試試這個嗎?

public static class PlaceViewHolder extends RecyclerView.ViewHolder { 

    protected TextView stateName; 
    protected CardView cardView; 

    public PlaceViewHolder(View view) { 
     super(view); 

    stateName = (TextView) view.findViewById(R.id.text); 
    cardView = (CardView) view.findViewById(R.id.cardView); 

    cardView.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     // Perform click listener of CardView 
    } 
    }); 

// Other tasks 

    } 
} 

希望這會對你有幫助。

0

做..

public static class PlaceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ 

      protected TextView stateName; 
      protected CardView cardView; 

      public PlaceViewHolder(View view) { 
       super(view); 
       view.setOnClickListener(this); 
       stateName = (TextView) view.findViewById(R.id.text); 
       cardView = (CardView) view.findViewById(R.id.cardView); 

       switch (StateRecyclerViewAdapter.i) { 
        case CompletionEvent.STATUS_FAILURE: 
         cardView.setCardBackgroundColor(Color.parseColor("#DDEC407A")); 
         i++; 
        case CompletionEvent.STATUS_CONFLICT: 
         cardView.setCardBackgroundColor(Color.parseColor("#DD7986CB")); 
         i++; 
        case CompletionEvent.STATUS_CANCELED: 
         cardView.setCardBackgroundColor(Color.parseColor("#DD5E35B1")); 
         i++; 
        default: 
         cardView.setCardBackgroundColor(Color.parseColor("#DDFF6F00")); 
         StateRecyclerViewAdapter.i = 1; 
       } 

       @Override 
       public void onClick(View v) { 
         FragmentManager fm = getFragmentManager(); 

         OtherFragment otherFragment = OtherFragment.newInstance(cityName); 

         fm.beginTransaction().replace(R.id.fragment_container, otherFragment).commit(); 
       } 

     } 
} 

還有你的另一片段會是這個樣子..

public class OtherFragment extends Fragment { 

    private static final String ARG_CITY_NAME = "city_name"; 

    public static OtherFragment newInstance(String cityName) { 

     Bundle args = new Bundle(); 
     args.putSerializable(ARG_CITY_NAME, cityName); 

     OtherFragment fragment = new OtherFragment(); 
     fragment.setArguments(args); 
     return fragment; 

    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     String cityName = (String) getArguments().getSerializable(ARG_CITY_NAME); 

    } 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.fragment_layout, container, false); 

     return view; 
    } 
}