I have multiple recyclerViews ,which should appear after another XML view, but they just don't , am using an adapter class to manage this. after using log.v I found that the the functions itself"in Adappter class" arent called , and i don't know why ??
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<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"
tools:context="com.example.linah.movielessonapp.Detailed_Movie">
<TextView
android:id="#+id/MovieTitle"
... />
<ImageView
android:id="#+id/MovieImage"
.../>
<TextView
android:id="#+id/MovieReview"
... />
<Button
android:id="#+id/Favbutton"
... />
<TextView
android:id="#+id/Date"
... />
<TextView
android:id="#+id/Rate"
.../>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/Trailers_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/MovieReview" />
<android.support.v7.widget.RecyclerView
android:id="#+id/reviews_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/Trailers_recycler_view"
/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
public class Detailed_Movie extends AppCompatActivity {
public static List<Movie_Details> movieDetailsList = new ArrayList<>();
private String ID;
public String Trailer_OR_Review = "trailer";
private boolean noConnection;
private boolean trailersDone;
private int trailersSize;
private static MoviesDetailedAdapter mAdapter;
private RecyclerView TrailerRecyclerView, ReviewsRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__movie);
TrailerRecyclerView = (RecyclerView) findViewById(R.id.Trailers_recycler_view);
ReviewsRecyclerView = (RecyclerView) findViewById(R.id.reviews_recycler_view);
new getData().execute("trailer");
// adapter
mAdapter = new MoviesDetailedAdapter(movieDetailsList,TrailerRecyclerView.getContext(),Trailer_OR_Review);
// mAdapter = new MoviesDetailedAdapter(movieDetailsList,ReviewsRecyclerView.getContext(),Trailer_OR_Review);
TrailerRecyclerView.setLayoutManager(new LinearLayoutManager(TrailerRecyclerView.getContext()));
// ReviewsRecyclerView.setLayoutManager(new LinearLayoutManager(ReviewsRecyclerView.getContext()));
TrailerRecyclerView.setItemAnimator(new DefaultItemAnimator());
// ReviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());
noConnection = false;
if(isOnline(Detailed_Movie.this)) {
new getData().execute("trailer");
mAdapter.notifyDataSetChanged();
}
// set the adapter
TrailerRecyclerView.setAdapter(mAdapter);
prepareMovieData();
Intent i = getIntent();
// http://api.themoviedb.org/3/movie/{id}/videos
String ImgPath = "http://image.tmdb.org/t/p/w185/";
String VideoPath = "http://www.youtube.com/watch?v=";
String MovieTitle = i.getExtras().getString("title");
Toast.makeText(getApplicationContext(),MovieTitle+" is selected!", Toast.LENGTH_SHORT).show();
ImageView img = (ImageView)findViewById(R.id.MovieImage);
TextView Title = (TextView)findViewById(R.id.MovieTitle);
TextView Review = (TextView)findViewById(R.id.MovieReview);
TextView Date = (TextView)findViewById(R.id.Date);
TextView Rate = (TextView)findViewById(R.id.Rate);
Button Fav = (Button) findViewById(R.id.Favbutton);
// get data from intent
assert Title != null;
Title. setText(i.getExtras().getString("title"));
assert Review != null;
Review.setText(i.getExtras().getString("review"));
assert Rate != null;
Rate. setText(i.getExtras().getString("rate"));
assert Date != null;
Date. setText(i.getExtras().getString("date"));
ID = i.getExtras().getString("id");
String Imgurl = i.getExtras().getString("img");
// append ImgPath
switch (ImgPath = new StringBuilder()
.append(ImgPath)
.append(Imgurl)
.toString()) {
}
// append VideoPath
VideoPath = new StringBuilder()
.append(VideoPath)
.append("6uEMl2BtcqQ")
.toString();
// VideoPath = VideoPath + getString(R.string.API_KEY);
final String finalVideoPath = VideoPath;
if (Fav != null) {
Fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(finalVideoPath));
startActivity(intent);
}
});
}
Picasso.with(this)
.load(ImgPath)
.placeholder(R.drawable.loading) //this is optional the image to display while the url image is downloading
.error(R.drawable.error) //this is also optional if some error has occurred in downloading the image
.into(img);
TrailerRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), TrailerRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Movie_Details movie = movieDetailsList.get(position);
if (position < trailersSize) {
// String link = ((TextView) findViewById(R.id.Link)).getText().toString();
// String link = movie.getKey();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.getKey())));
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void prepareMovieData() {
Movie_Details movie = new Movie_Details("MovieTrailer","6uEMl2BtcqQ","Linah","verynice");
movieDetailsList.add(movie);
mAdapter.notifyDataSetChanged();
}
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 MainActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.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));
}
}
});
}
public RecyclerTouchListener(Context applicationContext, RecyclerView trailerRecyclerView, ClickListener clickListener) {
}
#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) {
}
}
public class getData extends AsyncTask<String, Void, Void> {
...
}
}
class MoviesDetailedAdapter
public class MoviesDetailedAdapter extends RecyclerView.Adapter {
private List<Movie_Details> moviesList;
private Context context;
public String Trailer_OR_Review = "trailer";
public TextView TrailerName , Author , Content , TrailerLink ;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public MyViewHolder(View view) {
super(view);
Log.v("here","MyViewHolder");
TrailerName = (TextView) view.findViewById(R.id.Name);
Author = (TextView) view.findViewById(R.id.Author);
TrailerLink = (TextView) view.findViewById(R.id.Link);
Content = (TextView) view.findViewById(R.id.Content);
view.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public MoviesDetailedAdapter(List<Movie_Details> moviesList,Context context, String trailerORReview) {
this.moviesList = moviesList;
this.context = context;
Trailer_OR_Review = trailerORReview;
Log.v("here","madapter");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
Log.v("here","onCreateViewHolder");
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
/*
if (Trailer_OR_Review.equals("trailers")){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
}
else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reviews_layout, parent, false);
}*/
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.v("here","onBindViewHolder");
Movie_Details movie_details = moviesList.get(position);
Log.v("here",movie_details.getContent());
Log.v("here",movie_details.getName());
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
/*
if (Trailer_OR_Review.equals("trailers")){
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
}
else{
Author.setText(movie_details.getAuthor());
Content.setText(movie_details.getContent());
}*/
}
Related
FRAGMENT CODE
public class MyMallFragment extends Fragment {
public MyMallFragment() {
}
public static SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView homepageRecyclerview;
private MyMallAdapter myMallAdapter;
private ImageView noInternet;
private Button retryBtn;
private List<MyMallModel> myMallModelFakeList = new ArrayList<>();
NetworkInfo networkInfo;
ConnectivityManager connectivityManager;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_mall, container, false);
swipeRefreshLayout = view.findViewById(R.id.refresh_layout);
noInternet = view.findViewById(R.id.no_internet);
retryBtn = view.findViewById(R.id.retry_btn);
homepageRecyclerview = view.findViewById(R.id.my_mall_recyclerview);
swipeRefreshLayout.setColorSchemeColors(getContext().getResources().getColor(R.color.colorPrimary), getContext().getResources().getColor(R.color.colorPrimary), getContext().getResources().getColor(R.color.colorPrimary));
LinearLayoutManager testingLayoutManager = new LinearLayoutManager(getContext());
testingLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
homepageRecyclerview.setLayoutManager(testingLayoutManager);
////////home page fake list
List<SliderModel> sliderModelFakeList = new ArrayList<>();
sliderModelFakeList.add(new SliderModel("null", "#dfdfdf"));
sliderModelFakeList.add(new SliderModel("null", "#dfdfdf"));
sliderModelFakeList.add(new SliderModel("null", "#dfdfdf"));
sliderModelFakeList.add(new SliderModel("null", "#dfdfdf"));
sliderModelFakeList.add(new SliderModel("null", "#dfdfdf"));
List<HorizontalProductScrollModel> horizontalProductScrollModelFakeList = new ArrayList<>();
horizontalProductScrollModelFakeList.add(new HorizontalProductScrollModel("", "", "", "", ""));
horizontalProductScrollModelFakeList.add(new HorizontalProductScrollModel("", "", "", "", ""));
horizontalProductScrollModelFakeList.add(new HorizontalProductScrollModel("", "", "", "", ""));
horizontalProductScrollModelFakeList.add(new HorizontalProductScrollModel("", "", "", "", ""));
horizontalProductScrollModelFakeList.add(new HorizontalProductScrollModel("", "", "", "", ""));
horizontalProductScrollModelFakeList.add(new HorizontalProductScrollModel("", "", "", "", ""));
horizontalProductScrollModelFakeList.add(new HorizontalProductScrollModel("", "", "", "", ""));
myMallModelFakeList.add(new MyMallModel(0, sliderModelFakeList));
myMallModelFakeList.add(new MyMallModel(1, "", "#dfdfdf"));
myMallModelFakeList.add(new MyMallModel(2, "", "#dfdfdf", horizontalProductScrollModelFakeList, new ArrayList<WishlistModel>()));
myMallModelFakeList.add(new MyMallModel(3, "", "#dfdfdf", horizontalProductScrollModelFakeList));
////////home page fake list
myMallAdapter = new MyMallAdapter(myMallModelFakeList);
connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected() == true) {
MainActivity.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
noInternet.setVisibility(View.GONE);
retryBtn.setVisibility(View.GONE);
homepageRecyclerview.setVisibility(View.VISIBLE);
if (lists.size() == 0) {
lists.add(new ArrayList<MyMallModel>());
myMallAdapter = new MyMallAdapter(lists.get(0));
loadFragmentData(homepageRecyclerview, getContext(), 0, "Home");
} else {
myMallAdapter = new MyMallAdapter(lists.get(0));
myMallAdapter.notifyDataSetChanged();
}
homepageRecyclerview.setAdapter(myMallAdapter);
} else {
MainActivity.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
homepageRecyclerview.setVisibility(View.GONE);
Glide.with(this).load(R.drawable.no_internet).into(noInternet);
noInternet.setVisibility(View.VISIBLE);
retryBtn.setVisibility(View.VISIBLE);
}
///refresh layout
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
reloadPage();
}
});
///refresh layout
retryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reloadPage();
}
});
return view;
}
private void reloadPage() {
networkInfo = connectivityManager.getActiveNetworkInfo();
categoryModelList.clear();
lists.clear();
loadedCategoriesNames.clear();
DBquerries.clearData();
if (networkInfo != null && networkInfo.isConnected() == true) {
MainActivity.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
noInternet.setVisibility(View.GONE);
retryBtn.setVisibility(View.GONE);
homepageRecyclerview.setVisibility(View.VISIBLE);
myMallAdapter = new MyMallAdapter(myMallModelFakeList);
homepageRecyclerview.setAdapter(myMallAdapter);
loadedCategoriesNames.add("HOME");
lists.add(new ArrayList<MyMallModel>());
loadFragmentData(homepageRecyclerview, getContext(), 0, "Home");
} else {
MainActivity.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
Toast.makeText(getContext(), "No internet Connction!", Toast.LENGTH_SHORT).show();
/// categoryRecyclerView.setVisibility(View.GONE);
homepageRecyclerview.setVisibility(View.INVISIBLE);
Glide.with(getContext()).load(R.drawable.no_internet).into(noInternet);
noInternet.setVisibility(View.VISIBLE);
retryBtn.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void onStart() {
super.onStart();
}
I tried to add and set adaptor in on start method like it worked the content loaded up while opening but as soon as i scrolled down after the recycler view started to repeat the content so the content loaded 2 times.
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/category_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:elevation="3dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.454"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:visibility="gone" />
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/refresh_layout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/category_recycler_view">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/my_mall_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<ImageView
android:id="#+id/no_internet"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/retry_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:textSize="16sp"
android:textAllCaps="false"
android:backgroundTint="#color/black"
android:stateListAnimator="#null"
android:textColor="#color/colorAccent"
android:translationZ="8dp"
android:background="#drawable/slider_background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/category_recycler_view"
app:layout_constraintVertical_bias="0.75" />
</androidx.constraintlayout.widget.ConstraintLayout>
adapter
public class MyMallAdapter extends RecyclerView.Adapter {
private List<MyMallModel> myMallModelList;
private RecyclerView.RecycledViewPool recycledViewPool;
private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
private int lastPos=-1;
public MyMallAdapter(List<MyMallModel> myMallModelList) {
this.myMallModelList = myMallModelList;
recycledViewPool=new RecyclerView.RecycledViewPool();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
switch (myMallModelList.get(position).getType()){
case 0:
return MyMallModel.BANNER_SLIDER;
case 1:
return MyMallModel.STRIP_AD_BANNER;
case 2:
return MyMallModel.HORIZONTAL_PRODUCT_VIEW;
case 3:
return MyMallModel.GRID_PRODUCT_VIEW;
default:
return -1;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType){
case MyMallModel.BANNER_SLIDER:
View BannerSliderview= LayoutInflater.from(parent.getContext()).inflate(R.layout.sliding_ad_layout,parent,false);
return new BannerSliderViewHolder(BannerSliderview);
case MyMallModel.STRIP_AD_BANNER:
View StripAdview= LayoutInflater.from(parent.getContext()).inflate(R.layout.strip_ad_layout,parent,false);
return new StripAdBannerViewHolder(StripAdview);
case MyMallModel.HORIZONTAL_PRODUCT_VIEW:
View horizontalproductview= LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_scoll_layout,parent,false);
return new HorizontalProductViewHolder(horizontalproductview);
case MyMallModel.GRID_PRODUCT_VIEW:
View gridproductview= LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_product_layout,parent,false);
return new GridProductViewHolder(gridproductview);
default:
return null;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (myMallModelList.get(position).getType()){
case MyMallModel.BANNER_SLIDER:
List<SliderModel> sliderModelList=myMallModelList.get(position).getSliderModelList();
((BannerSliderViewHolder) holder).setBannerSliderViewPager(sliderModelList);
break;
case MyMallModel.STRIP_AD_BANNER:
String resource=myMallModelList.get(position).getResource();
String color=myMallModelList.get(position).getBackgroundColor();
((StripAdBannerViewHolder)holder).StripAd(resource,color);
break;
case MyMallModel.HORIZONTAL_PRODUCT_VIEW:
String title=myMallModelList.get(position).getTitle();
String colorr=myMallModelList.get(position).getBackgroundColor();
List<HorizontalProductScrollModel> horizontalProductScrollModelList=myMallModelList.get(position).getHorizontalProductScrollModelList();
List<WishlistModel> viewAllProductList=myMallModelList.get(position).getViewAllProductList();
((HorizontalProductViewHolder) holder).setHorizontalProductLayout(horizontalProductScrollModelList,title,colorr,viewAllProductList);
break;
case MyMallModel.GRID_PRODUCT_VIEW:
String gridcolorr=myMallModelList.get(position).getBackgroundColor();
String gridtitle=myMallModelList.get(position).getTitle();
List<HorizontalProductScrollModel> gridProductScrollModelList=myMallModelList.get(position).getHorizontalProductScrollModelList();
((GridProductViewHolder) holder).setGridProductLayout(gridProductScrollModelList,gridtitle,gridcolorr);
break;
default:
return;
}
if(lastPos<position) {
Animation animation = AnimationUtils.loadAnimation(holder.itemView.getContext(), R.anim.fade_in);
holder.itemView.setAnimation(animation);
lastPos=position;
}
}
#Override
public int getItemCount() {
return myMallModelList.size();
}
public class BannerSliderViewHolder extends RecyclerView.ViewHolder {
private ViewPager bannerSliderViewPager;
private int currentPage;
private Timer timer;
final private long DELAY_TIME=3000;
final private long PERIOD_TIME=3000;
private List<SliderModel> arrangedList;
public BannerSliderViewHolder(#NonNull View itemView) {
super(itemView);
bannerSliderViewPager=itemView.findViewById(R.id.banner_slider_view_pager);
}
public void setBannerSliderViewPager(final List<SliderModel> sliderModelList){
currentPage=2;
if(timer!=null){
timer.cancel();
}
arrangedList=new ArrayList<>();
for(int x=0;x<sliderModelList.size();x++){
arrangedList.add(x,sliderModelList.get(x));
}
arrangedList.add(0,sliderModelList.get(sliderModelList.size()-2));
arrangedList.add(1,sliderModelList.get(sliderModelList.size()-1));
arrangedList.add(sliderModelList.get(0));
arrangedList.add(sliderModelList.get(1));
SliderAdapter sliderAdapter=new SliderAdapter(arrangedList);
bannerSliderViewPager.setAdapter(sliderAdapter);
bannerSliderViewPager.setClipToPadding(false);
bannerSliderViewPager.setPageMargin(20);
bannerSliderViewPager.setCurrentItem(currentPage);
ViewPager.OnPageChangeListener onPageChangeListener=new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
currentPage=position;
}
#Override
public void onPageScrollStateChanged(int state) {
if(state==ViewPager.SCROLL_STATE_IDLE){
pageLooper(arrangedList);
}
}
};
bannerSliderViewPager.addOnPageChangeListener(onPageChangeListener);
startBannerSlideShow(arrangedList);
bannerSliderViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
pageLooper(arrangedList);
stopBannerSlideShow();
if(motionEvent.getAction()==MotionEvent.ACTION_UP){
startBannerSlideShow(arrangedList);
}
return false;
}
});
}
private void pageLooper(List<SliderModel> sliderModelList){
if(currentPage==sliderModelList.size()-2){
currentPage=2;
bannerSliderViewPager.setCurrentItem(currentPage,false);
}
if(currentPage==1){
currentPage=sliderModelList.size()-3;
bannerSliderViewPager.setCurrentItem(currentPage,false);
}
}
private void startBannerSlideShow(final List<SliderModel> sliderModelList){
final Handler handler=new Handler();
final Runnable update=new Runnable() {
#Override
public void run() {
if(currentPage>=sliderModelList.size()){
currentPage=1;
}
bannerSliderViewPager.setCurrentItem(currentPage++,true);
}
};
timer=new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(update);
}
},DELAY_TIME,PERIOD_TIME);
}
private void stopBannerSlideShow(){
timer.cancel();
}
}
public class StripAdBannerViewHolder extends RecyclerView.ViewHolder{
private ImageView stripAdImage;
private ConstraintLayout stripAdContainer;
public StripAdBannerViewHolder(#NonNull View itemView) {
super(itemView);
stripAdImage=itemView.findViewById(R.id.strip_ad_image);
stripAdContainer=itemView.findViewById(R.id.strip_ad_container);
}
public void StripAd(String resource,String color){
Glide.with(itemView.getContext()).load(resource).apply(new RequestOptions().placeholder(R.mipmap.pic)).into(stripAdImage);
stripAdContainer.setBackgroundColor(Color.parseColor(color));
}
}
public class HorizontalProductViewHolder extends RecyclerView.ViewHolder{
private ConstraintLayout container;
private TextView horizontallayoutTitle;
private Button horizontalviewAllBtn;
private RecyclerView horizontalRecyclerView;
public HorizontalProductViewHolder(#NonNull View itemView) {
super(itemView);
container=itemView.findViewById(R.id.container);
horizontalRecyclerView=itemView.findViewById(R.id.horizontal_scroll_layout_recycler_view);
horizontalviewAllBtn=itemView.findViewById(R.id.horizontal_scroll_layout_viewall_button);
horizontallayoutTitle=itemView.findViewById(R.id.horizontal_scroll_layout_title);
horizontalRecyclerView.setRecycledViewPool(recycledViewPool);
}
private void setHorizontalProductLayout(final List<HorizontalProductScrollModel> horizontalProductScrollModelList, final String title, String color, final List<WishlistModel> viewAllProductList){
container.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor(color)));
horizontallayoutTitle.setText(title);
for (final HorizontalProductScrollModel model:horizontalProductScrollModelList) {
if (!model.getProductID().isEmpty() && model.getProductTitle().isEmpty()){
firebaseFirestore.collection("PRODUCTS").document(model.getProductID()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
model.setProductTitle(task.getResult().getString("product_title"));
model.setProductPrice(task.getResult().getString("product_price"));
model.setProductImage(task.getResult().getString("product_image_1"));
WishlistModel wishlistModel = viewAllProductList.get(horizontalProductScrollModelList.indexOf(model));
wishlistModel.setTotalRatings(task.getResult().getLong("total_ratings"));
wishlistModel.setRating(task.getResult().getString("average_rating"));
wishlistModel.setProductTitle(task.getResult().getString("product_title"));
wishlistModel.setProductPrice(task.getResult().getString("product_price"));
wishlistModel.setProductImage(task.getResult().getString("product_image_1"));
wishlistModel.setFreeCoupans(task.getResult().getLong("free_coupans"));
wishlistModel.setCuttedPrice(task.getResult().getString("cutted_price"));
wishlistModel.setCOD(task.getResult().getBoolean("COD"));
wishlistModel.setInStock(task.getResult().getLong("stock_quantity") > 0);
if (horizontalProductScrollModelList.indexOf(model) == horizontalProductScrollModelList.size()-1){
if (horizontalRecyclerView.getAdapter()!= null){
horizontalRecyclerView.getAdapter().notifyDataSetChanged();
}
}
}else{
//do nothing
}
}
});
if(horizontalProductScrollModelList.size() > 8){
horizontalviewAllBtn.setVisibility(View.VISIBLE);
horizontalviewAllBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewAllActivity.wishlistModelList=viewAllProductList;
itemView.getContext().startActivity(new Intent(itemView.getContext(),ViewAllActivity.class)
.putExtra("layout",0)
.putExtra("title",title)
);
}
});
}else {
horizontalviewAllBtn.setVisibility(View.INVISIBLE);
}
}
}
HorizontalProductScrollAdapter horizontalProductScrollAdapter=new HorizontalProductScrollAdapter(horizontalProductScrollModelList);
LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(itemView.getContext());
linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
horizontalRecyclerView.setLayoutManager(linearLayoutManager1);
horizontalRecyclerView.setAdapter(horizontalProductScrollAdapter);
horizontalProductScrollAdapter.notifyDataSetChanged();
}
}
public class GridProductViewHolder extends RecyclerView.ViewHolder{
private ConstraintLayout container;
private TextView gridLayoutTitle;
private Button gridLayoutButton;
private GridLayout gridProductLayout;
public GridProductViewHolder(#NonNull final View itemView) {
super(itemView);
container=itemView.findViewById(R.id.container);
gridLayoutTitle=itemView.findViewById(R.id.grid_product_layout_title);
gridLayoutButton=itemView.findViewById(R.id.grid_product_layout_viewall_button);
gridProductLayout=itemView.findViewById(R.id.grid_layout);
}
private void setGridProductLayout(final List<HorizontalProductScrollModel> horizontalProductScrollModelList, final String title, String color) {
container.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor(color)));
gridLayoutTitle.setText(title);
for(int x=0;x<4;x++){
ImageView productImage=gridProductLayout.getChildAt(x).findViewById(R.id.h_s_product_image);
TextView productTitle=gridProductLayout.getChildAt(x).findViewById(R.id.h_s_product_title);
TextView productDesc=gridProductLayout.getChildAt(x).findViewById(R.id.h_s_product_description);
TextView productPrice=gridProductLayout.getChildAt(x).findViewById(R.id.h_s_product_price);
Glide.with(itemView.getContext()).load(horizontalProductScrollModelList.get(x).getProductImage()).apply(new RequestOptions().placeholder(R.mipmap.pic)).into(productImage);
productTitle.setText(horizontalProductScrollModelList.get(x).getProductTitle());
productDesc.setText(horizontalProductScrollModelList.get(x).getProductDesc());
productPrice.setText("Rs."+horizontalProductScrollModelList.get(x).getProductPrice()+"/-");
gridProductLayout.getChildAt(x).setBackgroundColor(Color.WHITE);
if(!title.equals("")){
final int finalX = x;
gridProductLayout.getChildAt(x).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemView.getContext().startActivity(new Intent(itemView.getContext(),ProductDetailsActivity.class).putExtra("PRODUCT_ID",horizontalProductScrollModelList.get(finalX).getProductID()));
}
});
}
}
if(!title.equals("")) {
gridLayoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewAllActivity.horizontalProductScrollModelList = horizontalProductScrollModelList;
itemView.getContext().startActivity(new Intent(itemView.getContext(), ViewAllActivity.class)
.putExtra("layout", 1)
.putExtra("title", title)
);
}
});
}
}
}
}
please try to help me i am searching for a solution from so long i tried everything but noting worked if you could tell me where i am wrong it will be very greatful.
Hey I'm doing filtering data on my project using bottom Sheet with view-pager and two fragments i can pass data from activity to view-pager adapter and get in fragment through constructor but how can i get data from fragment to activity using bottom-sheet
this is how i send data from activity
adapter = new PagerAdapters(this.getSupportFragmentManager(),
tabLayout.getTabCount(),_id);
and receive data with constructor in fragment
public Filterfragment(String _id) {
this._id = _id;
}
And I'm using recyclerview to show data like this
So how can i send id of the item to activity so i can reload my recyclerview data when the apply button click.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom_sheet"
android:background="#android:color/white"
app:behavior_peekHeight="0dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabPadding="0dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_below="#id/tabs"
android:layout_above="#id/applyBtn"
android:layout_height="match_parent"
/>
<Button
android:id="#+id/applyBtn"
android:layout_width="match_parent"
android:text="Apply"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content" />
</RelativeLayout>
This is main recyclerview adapter
public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.FilterViewHolder> {
private static final String TAG = "FilterAdapter";
Context context;
List<TagTypeResult> tagTypeModels;
public static int current_pos = -1;
TagAdapter tagAdapter;
int rotationAngle = 0;
public FilterAdapter(Context context, List<TagTypeResult> tagTypeModels) {
this.context = context;
this.tagTypeModels = tagTypeModels;
}
#NonNull
#Override
public FilterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.filter_row_item,parent,false);
return new FilterAdapter.FilterViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull FilterViewHolder filterViewHolder, int i) {
TagTypeResult tagTypeModel = tagTypeModels.get(i);
filterViewHolder.txt.setText(tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
if (tagTypeModel.getTagsLists() != null) {
if (tagTypeModel.getTagsLists().size() <= 0) {
filterViewHolder.arrow.setVisibility(View.GONE);
filterViewHolder.arrow.setRotationX(180);
} else {
filterViewHolder.arrow.setVisibility(View.VISIBLE);
filterViewHolder.arrow.setRotationX(0);
}
}else {
filterViewHolder.arrow.setVisibility(View.GONE);
}
tagAdapter = new TagAdapter(context, tagTypeModel.getTagsLists(), new TagInterface() {
#Override
public void tagClick(View view, int pos, String tagID) {
Log.d(TAG, "tagClick: "+tagID);
}
});
filterViewHolder.sub_list_recycler.setAdapter(tagAdapter);
tagAdapter.notifyDataSetChanged();
if (current_pos == filterViewHolder.getAdapterPosition()){
if (filterViewHolder.sub_list_recycler.getVisibility() == View.GONE) {
filterViewHolder.sub_list_recycler.setVisibility(View.VISIBLE);
}else {
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}else {
Log.i(TAG, "onBindViewHolder: sublist gone "+tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return tagTypeModels.size();
}
class FilterViewHolder extends RecyclerView.ViewHolder {
TextView txt;
ImageView arrow;
RecyclerView sub_list_recycler;
RelativeLayout linearLayout;
FilterViewHolder(#NonNull View itemView) {
super(itemView);
txt = itemView.findViewById(R.id.txt);
arrow = itemView.findViewById(R.id.arrow);
linearLayout = itemView.findViewById(R.id.main_cat_lay);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "onClick: "+current_pos);
if (current_pos != getAdapterPosition()) {
current_pos = getAdapterPosition();
notifyDataSetChanged();
}
else{
current_pos = -1;
notifyDataSetChanged();
}
}
});
sub_list_recycler = itemView.findViewById(R.id.sub_list_recycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context) {
#Override
public boolean canScrollVertically() {
return false;
}
};
sub_list_recycler.setLayoutManager(mLayoutManager);
sub_list_recycler.addItemDecoration(new SimpleDividerItemDecoration(context));
}
}
}
sub recyclerView adapter :
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.TagViewHolder> {
private static final String TAG = "SublistAdapter";
Context context;
List<TagsList> tagsLists;
int pos = -1;
TagInterface tagInterface;
public TagAdapter(Context context, List<TagsList> tagsLists,TagInterface tagInterface) {
this.context = context;
this.tagsLists = tagsLists;
this.tagInterface = tagInterface;
}
#NonNull
#Override
public TagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tag_item,parent,false);
return new TagAdapter.TagViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull TagViewHolder tagViewHolder, int i) {
TagsList tagsList = tagsLists.get(i);
tagViewHolder.tagtxt.setText(tagsList.getName());
if (tagsList.isChecked()){
tagViewHolder.tagName.setChecked(true);
}else {
tagViewHolder.tagName.setChecked(false);
}
}
#Override
public int getItemCount() {
return tagsLists.size();
}
public class TagViewHolder extends RecyclerView.ViewHolder {
TextView tagtxt;
CheckBox tagName;
RelativeLayout childClik;
public TagViewHolder(#NonNull View itemView) {
super(itemView);
//pri_txt = itemView.findViewById(R.id.pri_txt);
tagName = itemView.findViewById(R.id.tagName);
tagtxt = itemView.findViewById(R.id.tagtxt);
childClik = itemView.findViewById(R.id.childClik);
tagName.setEnabled(false);
childClik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = true;
if (isChecked)
{
tagsLists.get(getAdapterPosition()).setChecked(true);
tagName.setChecked(true);
tagInterface.tagClick(v,getAdapterPosition(),tagsLists.get(getAdapterPosition()).get_id());
Toast.makeText(context, "[pos]"+tagsLists.get(getAdapterPosition()).get_id(), Toast.LENGTH_SHORT).show();
}else
{
tagsLists.get(getAdapterPosition()).setChecked(false);
tagName.setChecked(false);
}
}
});
}
}
}
I have a recycle view which populates data from a server, the components inside are a textView and a Switch. The server can return n number of data. How can i set a unique id to the Switch2 when I am populating the data, because later I will need to set a listener to the Switches, My server actually returns a unique id but I'm not so sure on how to set it to the Switch2, or is there any alternate parameters that can be used to identify the Switch?
layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="81dp">
<android:android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="1dp"
card_view:cardUseCompatPadding="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:id="#+id/switch2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:paddingLeft="5dip"
android:layout_marginTop="16dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="254dp" />
<TextView
android:id="#+id/user_set_light_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif"
android:text="TextView"
android:textSize="20dp"
tools:layout_editor_absoluteX="27dp"
tools:layout_editor_absoluteY="23dp" />
</RelativeLayout>
</android:android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
adapter
public class populateLights_adapter extends RecyclerView.Adapter<populateLights_adapter.ViewHolder> {
private List<populate_lights> listItems;
private Context context;
public populateLights_adapter(List<populate_lights> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.addlight_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
populate_lights listItem = listItems.get(position);
holder.lightText.setText(listItem.getLightName());
holder.status.setChecked(listItem.getState());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView lightText;
public Switch status;
public ViewHolder(View itemView) {
super(itemView);
lightText = (TextView) itemView.findViewById(R.id.user_set_light_id);
status = (Switch) itemView.findViewById(R.id.switch2);
}
}
}
java class
public class populate_lights {
private String lightName;
private boolean state;
public populate_lights(String lightName, boolean state){
this.lightName = lightName;
this.state = state;
}
public String getLightName(){
return lightName;
}
public boolean getState(){
return state;
}
}
main
public class lightsControl extends Fragment {
View myView;
public static final String URL = "serverurl.com";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<populate_lights> listItems;
private Switch mySwitch;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.lightscontrol, container, false);
recyclerView = (RecyclerView) myView.findViewById(R.id.lightsView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
listItems = new ArrayList<>();
loadData();
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
return myView;
}
private void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(myView.getContext());
progressDialog.setMessage("Loading");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Snackbar mySnackbar = Snackbar.make(myView, "Data Fetched!", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("DATA_RESPONSE", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("lightData");
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
Log.v("LIGHT ID ", "index=" + obj.getString("LightID"));
Log.v("Value ", "index=" + obj.getBoolean("Value"));
populate_lights popLights = new populate_lights(
obj.getString("LightID"), //unique id
obj.getBoolean("Value") //value returns true, or false
);
listItems.add(popLights);
}
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
}
catch(Exception e){
e.printStackTrace();
}
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar mySnackbar = Snackbar.make(myView, "Oops, there was an error communicating with our server, try again", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("LoginFormERROR", "index=" + error);
progressDialog.dismiss();
}
}
)
};
RequestQueue requestQueue = Volley.newRequestQueue(myView.getContext());
requestQueue.add(stringRequest);
}
public void showErrorAlert(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(myView.getContext());
builder1.setMessage("Opps, something went wring");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Main Menu",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().onBackPressed();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
screenshot
See if this code prints the right position in the logs. Put this inside the constructor of the view holder in the adapter class:
status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.d("Position: ", String.valueOf(getLayoutPosition()));
}
});
I have multiple options for a poll and user can select only one option. i am getting options in recycler view with a checkbox and textview.
i want to uncheck previous selected checkbox if user select another checkbox and get selected text by pressing submit button.
here is my recycler view code.
public class Poll_Options_recyclerView_Adapter extends RecyclerView.Adapter<Poll_Options_recyclerView_Adapter.MyViewHolder> {
public List<Poll_Option_Result> result = new ArrayList<>();
Context mycontext;
public Poll_Options_recyclerView_Adapter(List<Poll_Option_Result> result, Context context) {
this.result = result;
this.mycontext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_option_rec_list, parent, false);
return new MyViewHolder(itemView, mycontext, result);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView poll_option;
CheckBox checkBox;
List<Poll_Option_Result> result_List = new ArrayList<>();
Context mycontext;
public MyViewHolder(View itemView, Context mycontext, List<Poll_Option_Result> result_List) {
super(itemView);
this.result_List = result_List;
this.mycontext = mycontext;
poll_option = (TextView) itemView.findViewById(R.id.optionA);
checkBox=(CheckBox)itemView.findViewById(R.id.check_box);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
#Override
public void onBindViewHolder(Poll_Options_recyclerView_Adapter.MyViewHolder holder, int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
}
#Override
public int getItemCount() {
return result.size();
}
}
and here is my recycler view custom xml code.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5"
>
<CheckBox
android:id="#+id/check_box"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_weight="4.5"
android:layout_height="wrap_content"
android:text="xyz"
android:layout_marginLeft="20dp"
android:textColor="#color/colortoolbartitle"
android:padding="5dp"
android:id="#+id/optionA"/>
private int mCheckedPostion = -1;// no selection by default
Done by adding this code in onBindViewHolder
#Override
public void onBindViewHolder(final Poll_Options_recyclerView_Adapter.MyViewHolder holder, final int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
//check checkbox and uncheck previous selected button
holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
StringGen.username = "";
mCheckedPostion = -1;
} else {
mCheckedPostion = position;
StringGen.username = holder.poll_option.getText().toString();
Toast.makeText(mycontext, "select : "+position+holder.poll_option.getText(), Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
}
});
}
I am developing an android app, where I am trying to implement one feature for Image gallary. Now, initially, I want to show some image url with their title name. I am using hashmap for mapping title with their image.I have the model class with two String fields url and title. But The problem is I am very new in the development field and now sure how to show the title based on image click. Here is my model Class
public class ImageModel implements Parcelable {
String name, url;
public ImageModel() {
}
protected ImageModel(Parcel in) {
name = in.readString();
url = in.readString();
}
public static final Creator<ImageModel> CREATOR = new Creator<ImageModel>() {
#Override
public ImageModel createFromParcel(Parcel in) {
return new ImageModel(in);
}
#Override
public ImageModel[] newArray(int size) {
return new ImageModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
}
}
Now the Main activity where I create a Hashmap with image and title to show those into views.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
HashMap<String, String> h1 = new HashMap<>();
String[] imgUrls = {"https://images.unsplash.com/photo-1444090542259-0af8fa96557e?q=80&fm=jpg&w=1080&fit=max&s=4b703b77b42e067f949d14581f35019b",
"https://images.unsplash.com/photo-1439546743462-802cabef8e97?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1441155472722-d17942a2b76a?q=80&fm=jpg&w=1080&fit=max&s=80cb5dbcf01265bb81c5e8380e4f5cc1"};
String[] imgNames = {"name1","name2","name3"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
}));
}
}
GalleryAdapterCode
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<ImageModel> data = new ArrayList<>();
public GalleryAdapter(Context context, List<ImageModel> data) {
this.context = context;
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item, parent, false);
viewHolder = new MyItemHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
((MyItemHolder) holder).mTextView.setText(data.get(position).getName());
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
}
My XML Class for item list row is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="#+id/item_img"
android:layout_width="match_parent"
android:layout_height="188dp"
android:adjustViewBounds="true"
android:background="#color/colorAccent"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7000"
android:orientation="vertical"
android:padding="10dp"
android:layout_alignBottom="#+id/item_img"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textView"
android:text="Headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textSize="15dp"
android:textStyle="normal|bold"
/>
</LinearLayout>
</RelativeLayout>
Create two String arrays one containing image urls and other names in MainActivity.
String[] imgUrls = {"url1","url2","url3"};
String[] imgNames = {"name1","name2","name3"};
Iterate over those arrays and create a list of the model class.
ArrayList<ImageModel> data = new ArrayList<ImageModel>();
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
Add a TextView in your RecyclerView row layout R.layout.list_item.
In your adapter use this TextView to set name of image.
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.item_textview);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
holder.mTextView.setText(data.get(position).getName());
}
Rest of your code will be the same.