My adapter :
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.AdsViewHolder> {
private List<Ads> adsList;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public class AdsViewHolder extends RecyclerView.ViewHolder {
public TextView txtAdTitle, txtCompanyName;
public NetworkImageView imgCompany;
public SwitchCompat adState;
public AdsViewHolder(View view) {
super(view);
txtAdTitle = (TextView) view.findViewById(R.id.txt_ad_title);
txtCompanyName = (TextView) view.findViewById(R.id.txt_company);
imgCompany = (NetworkImageView) view.findViewById(R.id.img_company);
adState = (SwitchCompat) view.findViewById(R.id.btn_ad_state);
if (GlobalValues.switchCompat.equals("My Advertisements"))
adState.setVisibility(View.VISIBLE);
else
adState.setVisibility(View.GONE);
}
}
public AdsAdapter(List<Ads> adsList) {
this.adsList = adsList;
}
@Override
public AdsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.ads_list_row, parent, false);
return new AdsViewHolder(itemView);
}
@Override
public void onBindViewHolder(AdsViewHolder holder, int position) {
Ads ads = adsList.get(position);
holder.txtAdTitle.setText(ads.getAdTitle());
holder.txtCompanyName.setText(ads.getCompanyName());
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
holder.imgCompany.setImageUrl(ads.getImageUrl(), imageLoader);
if (GlobalValues.switchCompat.equals("My Advertisements")) {
holder.adState.setChecked(ads.getAdState());
holder.adState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
Log.d("SwitchCompat", String.valueOf(isChecked));
}
});
}
}
@Override
public int getItemCount() {
return adsList.size();
}
}
Fragment :
public class MyAdvertisementFragment extends Fragment {
private static final String TAG = MyAdvertisementFragment.class.getSimpleName();
private Button addNewAd;
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog pDialog;
private String uid, api_key;
private List<Ads> adsList = new ArrayList<>();
private RecyclerView recyclerView;
private AdsAdapter mAdapter;
public MyAdvertisementFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_myadvertisements, container, false);
GlobalValues.switchCompat = "My Advertisements";
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// session manager
session = new SessionManager(getActivity().getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
uid = user.get("uid");
api_key = user.get("api_key");
addNewAd = (Button) rootView.findViewById(R.id.btn_add_advertisement);
addNewAd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Launch main activity
Intent intent = new Intent(getActivity(), AddNewAdActivity.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView) rootView.findViewById(R.id.ads_recycler_view);
mAdapter = new AdsAdapter(adsList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity().getApplicationContext(), recyclerView, new ClickListener() {
@Override
public void onClick(View view, int position) {
String adId = adsList.get(position).getAdId();
Intent i = new Intent(getActivity(), AdDetailsActivity.class);
i.putExtra("adId", adId);
startActivity(i);
}
@Override
public void onLongClick(View view, int position) {
}
}));
getUserAdsList();
// Inflate the layout for this fragment
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MyAdvertisementFragment.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MyAdvertisementFragment.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = 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.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void getUserAdsList() {
// Tag used to cancel the request
String tag_string_req = "req_get_user_ads";
pDialog.setMessage("Lütfen Bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.GET,
ApiRoutes.URL_ADS+ "/" + uid, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "User Ads Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
adsList.clear();
mAdapter.notifyDataSetChanged();
JSONArray adsArray = jObj.getJSONArray("ads");
Ads ads;
for (int i = 0; i < adsArray.length(); i++) {
JSONObject jsonobject = adsArray.getJSONObject(i);
boolean ad_state = (jsonobject.getString("ad_state").equals("1")) ? true : false;
ads = new Ads(jsonobject.getString("id"), jsonobject.getString("title"), jsonobject.getString("company_name"), ApiRoutes.FOLDER_IMG + "/" + uid + "/profile_img.png", ad_state);
adsList.add(ads);
}
mAdapter.notifyDataSetChanged();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity().getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "User Ads Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("uid", uid);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", api_key);
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
getActivity().finish();
}
}
I have switchcompat for every recyclerviewer' s rows. I add the switchcompat listener in adapter. But how can i handle, which switchcompat changed ? Because my recyclerviewer' s touchlistener in fragment. But switchcompat listener in adapter so i could not get position of which row's switchcompat clicked.