I am making an android application using java and xml, the application allows to debate by generating arguments and counter arguments. To display the argument list create an "external" recyclerview that inflates a view which contains linear layout. To display the list of counter arguments create an internal recyclerview that inflates a view which contains a cardview which allows counterarguments on a specific argument. The problem is that the internal recyclerview does not show the complete list of counterarguments. I leave you part of my code hoping that you can help me
adapterArgument.class
public class adapterArguments extends RecyclerView.Adapter<adapterArguments.ViewHolder> {
private List<ListArguments> data;
private LayoutInflater inflater;
private Context context;
public String position_selected;
public static String argument;
public adapterArguments(List<ListArguments> itemList, Context context) {
this.data = itemList;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.compontents_arguments_recyclerview,null);
return new adapterArguments.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ConexionSQliteHelper conn=new ConexionSQliteHelper(context,"db_testwuad_7",null,31);
holder.arguments.setText(data.get(position).getArguments());
holder.name_user.setText(data.get(position).getName_user());
holder.date.setText(data.get(position).getDate_arguments());
holder.position.setText(data.get(position).getPosition());
int id_argument_selected = data.get(position).getId();
position_selected = holder.position.getText().toString();
holder.list_contrarguments = conn.getContrarguments(id_argument_selected);
holder.recyclerView_contrarguments.setLayoutManager(new LinearLayoutManager(context));
holder.recyclerView_contrarguments.setHasFixedSize(true);
holder.listContrarguments = new adapterContrarguments(holder.list_contrarguments,context);
holder.recyclerView_contrarguments.setAdapter(holder.listContrarguments);
final int[] checkedItem = {-1};
if(position_selected.equals("A favor")){
holder.position.setBackgroundColor(Color.parseColor("#073FD7"));
}
else{
holder.position.setBackgroundColor(Color.parseColor("#FC0C1E"));
}
holder.addContrarguments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("Añadir un Contrargumento");
alertDialog.setMessage("¿Quieres añadir un contrargumento a este texto?");
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
argument = holder.arguments.getText().toString();
contrargument fragment = new contrargument();
Bundle args = new Bundle();
args.putString("argument", argument);
args.putInt("id",id_argument_selected);
fragment.setArguments(args);
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
holder.deleteDiscuss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("¿Deseas eliminar este argumento?");
alertDialog.setMessage("¿Quieres añadir un contrargumento a este texto?");
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
boolean user_create_debate = conn.verifyCreatorDebate(holder.name_user.getText().toString());
Toast.makeText(context, "el valor es"+user_create_debate, Toast.LENGTH_SHORT).show();
if(user_create_debate){
conn.deleteArgument(id_argument_selected);
}
else{
Toast.makeText(context, "No puede eliminar el argumento,ya que no es el creador del texto", Toast.LENGTH_SHORT).show();
}
opinionUserOnPostDebate fragment = new opinionUserOnPostDebate();
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.detach(fragment).attach(fragment).commit();
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
holder.changePosition.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Cambio de postura");
final String[] listItems = new String[]{"Cambie de opinión","Me equivoque de botón","Otro"};
alertDialog.setSingleChoiceItems(listItems, checkedItem[0], new DialogInterface.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(DialogInterface dialog, int which) {
checkedItem[0] = which;
}
});
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(position_selected.equals("A favor")){
//conn.changePosition(id_argument_selected,"En contra");
}
else{
//conn.changePosition(id_argument_selected,"A favor");
}
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
holder.Report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Reportar post");
final String[] listItems = new String[]{"Opinión contiene lenguaje ofensivo","Opinión contiene información personal","Otro"};
alertDialog.setSingleChoiceItems(listItems, checkedItem[0], new DialogInterface.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(DialogInterface dialog, int which) {
checkedItem[0] = which;
}
});
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(position_selected.equals("A favor")){
//conn.changePosition(id_argument_selected,"En contra");
}
else{
//conn.changePosition(id_argument_selected,"A favor");
}
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView arguments,name_user,date,position;
ImageButton addContrarguments,deleteDiscuss,addFriend,changePosition,Report;
List<ListContrarguments> list_contrarguments;
RecyclerView recyclerView_contrarguments;
public adapterContrarguments listContrarguments;
public ViewHolder(#NonNull View itemView) {
super(itemView);
arguments = itemView.findViewById(R.id.arguments_posted);
name_user = itemView.findViewById(R.id.name_arguments);
date = itemView.findViewById(R.id.date_arguments);
position = itemView.findViewById(R.id.position);
addContrarguments = itemView.findViewById(R.id.comments);
deleteDiscuss = itemView.findViewById(R.id.delete);
changePosition = itemView.findViewById(R.id.change_position);
addFriend = itemView.findViewById(R.id.add_friend);
Report = itemView.findViewById(R.id.report_argument);
recyclerView_contrarguments = itemView.findViewById(R.id.recycler_contrargument);
}
}
}
layout.compontents_arguments_recyclerview.xml
<LinearLayout 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"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="500dp"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="#+id/position"
android:textColor="#color/white"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textStyle="bold"
android:textSize="25dp"
android:background="#0AA842">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/image_person_contrarguments"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="15dp"
android:layout_marginRight="5dp">
</ImageView>
<TextView
android:id="#+id/name_arguments"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="15dp"
android:textSize="14sp"
>
</TextView>
<TextView
android:id="#+id/date_arguments"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
>
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="360dp"
android:orientation="vertical"
>
<TextView
android:id="#+id/arguments_posted"
android:layout_width="match_parent"
android:layout_height="140dp"
>
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"
android:background="#FEFEFE"
>
<ImageButton
android:id="#+id/comments"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/add_comments"
android:background="#FEFEFE"
android:layout_marginLeft="50dp"
>
</ImageButton>
<ImageButton
android:id="#+id/delete"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/delete"
android:background="#FEFEFE"
>
</ImageButton>
<ImageButton
android:id="#+id/change_position"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/change_opinion"
android:background="#FEFEFE"
>
</ImageButton>
<ImageButton
android:id="#+id/add_friend"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/add_friend"
android:background="#FEFEFE"
>
</ImageButton>
<ImageButton
android:id="#+id/report_argument"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/display_report"
android:background="#FEFEFE"
>
</ImageButton>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#A4A1A1"
>
</View>
<include
android:layout_width="match_parent"
android:layout_height="179dp"
layout="#layout/recyclerview_contrarguments"
>
</include>
</LinearLayout>
</LinearLayout>
</LinearLayout>
adapterContrarguments.class
public class adapterContrarguments extends RecyclerView.Adapter<adapterContrarguments.ViewHolder> {
private List<ListContrarguments> data;
private LayoutInflater inflater;
private Context context;
public adapterContrarguments(List<ListContrarguments> itemlist, Context context) {
this.data = itemlist;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.cardview_contrarguments,null);
return new adapterContrarguments.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.name_user_posted_contrarguments.setText(data.get(position).getName_user_posted_contrarguments());
holder.contrarguments.setText(data.get(position).getPost_contrarguments());
holder.date_contrarguments.setText(data.get(position).getDate_contrarguments());
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name_user_posted_contrarguments,date_contrarguments,contrarguments;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name_user_posted_contrarguments = itemView.findViewById(R.id.user_post_contrargument);
date_contrarguments = itemView.findViewById(R.id.date_contrargument);
contrarguments = itemView.findViewById(R.id.contrargument_post);
}
}
}
cardview_contrarguments.xml
<androidx.cardview.widget.CardView 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:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
app:cardCornerRadius="20dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="395dp"
android:layout_height="200dp"
android:padding="26dp">
<TextView
android:id="#+id/user_post_contrargument"
android:layout_width="168dp"
android:layout_height="19dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/contrargument_post"
android:layout_width="336dp"
android:layout_height="115dp"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.493"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:ignore="SpeakableTextPresentCheck" />
<TextView
android:id="#+id/date_contrargument"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.89"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
You cant get a recyclerview inside a recyclerview. If the number of counter argument is constant for every external recyclerview item, like every argument has 4 counter argument, then I suggest you to add counter arguments design to arguments xml.
Maybe check this answer
Related
I have a custom dialog that has a ViewPager inside of it, when the dialog shows the ViewPager is just blank, not progressing on swipe or when pressing the "Next" button I implemented. I tried slightly altering my code and it didn't work. I saw several posts like this, but none of their solutions worked. PS if some things don't make sense or have mismatched names then that's because I renamed/removed some of the files/variables to simplify.
SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> text;
public SliderAdapter(Context context, ArrayList<String> text) {
this.context = context;
this.text = text;
}
public String[] txtH = {
"test1",
"test2",
"test3"
};
#Override
public int getCount() {
return txtH.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_wr, container, false);
TextView txt1 = view.findViewById(R.id.txt11);
TextView txt2 = view.findViewById(R.id.txt22);
txt1.setText(txtH[position]);
txt2.setText(text.get(position));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Dialog itself:
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.Dialog);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
preferences = getActivity().getSharedPreferences("label", 0);
Random random = new Random();
text.add("test1");
text.add("test2");
text.add("test3");
viewPager = view.findViewById(R.id.viewPager);
dotLayout = view.findViewById(R.id.dotLayout);
next = view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (next.getText().toString().equals("Proceed")) {
dismiss();
} else {
viewPager.setCurrentItem(currentPage + 1);
}
}
});
back = view.findViewById(R.id.back);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPage--);
}
});
builder.setView(view)
.setCancelable(true);
addDotsIndicator(0);
viewPager.setOnPageChangeListener(viewListener);
adapter = new SliderAdapter(getActivity(), text);
return builder.create();
}
private void addDotsIndicator(int position) {
dots = new TextView[3];
dotLayout.removeAllViews();
for (int i = 0; i<dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(Color.parseColor("#404040"));
dotLayout.addView(dots[i]);
}
if(dots.length > 0) {
dots[position].setTextColor(Color.BLACK);
}
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
currentPage = position;
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
} else if (currentPage == 1) {
back.setEnabled(true);
next.setEnabled(true);
back.setText("Back");
next.setText("Next");
} else if (currentPage == 2) {
back.setEnabled(true);
next.setEnabled(false);
back.setText("Back");
next.setText("Proceed");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
Dialog XML:
<RelativeLayout
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"
android:background="#drawable/dialog_bg"
app:cardCornerRadius="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/dotLayout"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:layout_below="#+id/viewPager"
android:orientation="horizontal" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="#+id/viewPager"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Back"
android:textColor="#android:color/black" />
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/viewPager"
android:layout_margin="5dp"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Next"
android:textColor="#android:color/black" />
</RelativeLayout>
ViewPager's slide layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:background="#android:color/white">
<TextView
android:id="#+id/txt11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textColor="#android:color/black"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.24000001" />
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Test"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/txt11"
app:layout_constraintStart_toStartOf="#+id/txt11"
app:layout_constraintTop_toBottomOf="#+id/txt11"
app:layout_constraintVertical_bias="0.26" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you didn't set the ViewPager adapter
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
viewPager = view.findViewById(R.id.viewPager);
...
adapter = new SliderAdapter(getActivity(), text);
viewPager.setAdapter(adapter); // <<<<<< change here
return builder.create();
}
...
Here is my test
I have created a wallpaper app where I'm loading images from the firebase database in recyclerview. When I click on recyclerview item(image) that item's image URL is sent to the next activity and then that URL is loaded into imageView using glide.
I want to change this to something like Image-Slider. By clicking on the recyclerView item I want to show that image in full screen and slide from left or right(next or previous). But I don't know how to do that.
Here is my code.
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
adapter = new FeaturedAdapter(list);
recyclerView.setAdapter(adapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Wallpaper All");
Query query = databaseReference.orderByChild("dark").equalTo(true);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
FeaturedModel model = dataSnapshot1.getValue(FeaturedModel.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("TAG_DATABASE_ERROR", databaseError.getMessage());
}
});
FeaturedAdapter.java
public class FeaturedAdapter extends RecyclerView.Adapter<FeaturedAdapter.ViewHolder> {
private List<FeaturedModel> featuredModels;
public FeaturedAdapter(List<FeaturedModel> featuredModels) {
this.featuredModels = featuredModels;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(featuredModels.get(position).getImageLink()
, position,
featuredModels.get(position).isPremium());
}
#Override
public int getItemCount() {
return featuredModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private ImageView premiumImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
premiumImage = itemView.findViewById(R.id.premium);
}
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), PremiumViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), ViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
}
}
}
}
ViewActivity
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
relativeLayout.setBackgroundColor(color);
Glide.with(this)
.load(getIntent().getStringExtra("images"))
.timeout(6000)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(imageView);
setBackgroundWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackgroundImage();
}
});
}
private void setBackgroundImage() {
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toasty.success(getApplicationContext(), "Set Wallpaper Successfully", Toast.LENGTH_SHORT, true).show();
} catch (IOException e) {
Toasty.warning(this, "Wallpaper not load yet!", Toast.LENGTH_SHORT, true).show();
}
}
activity_view.xml
<?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"
tools:context=".activity.PremiumViewActivity">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#00BCD4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottieSuccess"
android:layout_width="180dp"
android:layout_height="180dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_fileName="checked.json" />
<RelativeLayout
android:id="#+id/wallpaper_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent">
<ImageButton
android:id="#+id/saveImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:contentDescription="#null"
android:src="#drawable/save" />
<Button
android:id="#+id/setWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
android:background="#drawable/set_as_wallpaper_btn"
android:minWidth="230dp"
android:text="Set as wallpaper"
android:textColor="#000"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:orientation="horizontal">
<CheckBox
android:id="#+id/favoritesBtn_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:button="#drawable/favourite_checkbox_selector" />
<ImageButton
android:id="#+id/shareBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:background="#drawable/share"
android:contentDescription="#null" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/ads_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent">
<Button
android:id="#+id/watch_ads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/advertizing"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Watch Video Ad"
android:textColor="#000"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/watch_ads">
<Button
android:id="#+id/unlock_withCoins"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/diamond"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Unlock with diamonds"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/diamonds_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="Total Diamonds: 0"
android:textSize="10sp"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
custom_image.xml
<?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="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:background="#fff"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#color/colorPrimary" />
<ImageView
android:id="#+id/premium"
android:contentDescription="#null"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_margin="10dp"
app:srcCompat="#drawable/diamond" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
Structure
MainActivity
|
| //Click button to open
|
FragActivity
|
| //FrameLayout
|
Fragment
|
| //here is the recyclerView
| //Open new Activity to view image
ViewActivity
Screen Recording
This can be solved by using ViewPager or ViewPager2 in Android
First create an Adapter
ImageSwiperAdapter2.java
public class ImageSwiperAdapter2 extends RecyclerView.Adapter<ImageSwiperAdapter2.ImageSwiper> {
private List<FeaturedModel> list;
private Context context;
public ImageSwiperAdapter2(List<FeaturedModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public ImageSwiper onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.slidingimages,
parent, false);
return new ImageSwiper(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageSwiper holder, int position) {
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
holder.relativeLayout.setBackgroundColor(color);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageLink())
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
class ImageSwiper extends RecyclerView.ViewHolder {
private ImageView imageView;
public ImageSwiper(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
In ViewActivity/SwiperActivity.java
public class SwiperActivity extends AppCompatActivity {
private ViewPager2 viewPager;
private List<FeaturedModel> list;
private ImageSwiperAdapter2 adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swiper);
viewPager = findViewById(R.id.view_pager);
final int pos = getIntent().getIntExtra("pos", 0);
Singleton singleton = Singleton.getInstance();
list = new ArrayList<>();
list = singleton.getListSin();
adapter2 = new ImageSwiperAdapter2(list, this);
viewPager.setAdapter(adapter2);
viewPager.setCurrentItem(pos);
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Toast.makeText(SwiperActivity.this, "Selected: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
}
You can pass the list and clicked item position in FeaturedAdapter.
In your FeaturedAdapter's setData method
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
final Singleton a = Singleton.getInstance();
a.setListSin(featuredModels);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
}
}
slidingimages.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop" />
</RelativeLayout>
activity_swiper.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SwiperActivity">
<androidx.viewpager2.widget.ViewPager2
android:orientation="horizontal"
android:id="#+id/view_pager"
android:layoutDirection="inherit"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Since the ViewActivity must show all the images(when slided) it must contain the adapter with the set of image urls.
Instead of using an ImageView, use a RecyclerView in the ViewActivity and attach the adapter. In your code, do the following to make the recycler view horizontal and add slide functionality.
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
Few Days ago, I had been looking for similar requirement for showing slid-able image View.
This situation can be solved using ViewPager in Android.
You can use following Tutorials for building such Slide Image View using ViewPager
Java Resources
Blog Tutorial
Video Tutorial
Kotlin Resources
Video Tutorial
Here is my recyclerView Adapter which shows a list from the database, View button is for downloading and the delete button deletes the file from device storage, it works perfectly. But how can I set Visibility of the delete button invisible/gone, if the file does not exist in the device storage.
MainActivity mainActivity;
ArrayList<DownModel> downModels;
public MyAdapter(MainActivity mainActivity, ArrayList<DownModel> downModels) {
this.mainActivity =mainActivity;
this.downModels = downModels;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(mainActivity.getBaseContext());
View view = layoutInflater.inflate(R.layout.elements, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int i) {
myViewHolder.mName.setText(downModels.get(i).getName());
myViewHolder.mDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(myViewHolder.mDownload.getContext(), PdfView.class);
intent.putExtra("pdf_url", downModels.get(i).getLink());
intent.putExtra("pdf_name",downModels.get(i).getName());
myViewHolder.mDownload.getContext().startActivity(intent);
}
});
myViewHolder.mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = myViewHolder.itemView.getContext();
String pdfName = downModels.get(i).getName()+".pdf";
File file = new File(context.getFilesDir(), pdfName);
try {
if (file.exists())
file.delete();
Log.e("file","file"+file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public int getItemCount() {
return downModels.size();
}
}
RecyclerView
public class MainActivity extends AppCompatActivity {
FirebaseFirestore db;
RecyclerView mRecyclerView;
ArrayList<DownModel> downModelArrayList = new ArrayList<>();
MyAdapter myAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView= findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
db=FirebaseFirestore.getInstance();
dataFromFirebase();
}
#Override
protected void onResume() {
super.onResume();
myAdapter.notifyDataSetChanged();
}
private void dataFromFirebase() {
if(downModelArrayList.size()>0)
downModelArrayList.clear();
db.collection("chapter1").orderBy("value")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for(DocumentSnapshot documentSnapshot: Objects.requireNonNull(task.getResult())) {
DownModel downModel= new DownModel(documentSnapshot.getString("name"),
documentSnapshot.getString("link"));
downModelArrayList.add(downModel);
}
myAdapter= new MyAdapter(MainActivity.this,downModelArrayList);
mRecyclerView.setAdapter(myAdapter);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error ;-.-;", Toast.LENGTH_SHORT).show();
}
})
;
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:text="Name"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
android:weightSum="2"
>
<Button
android:id="#+id/down"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:background="#A00303"
android:elevation="7dp"
android:text="View"
android:textColor="#FFFFFF"
tools:visibility="visible" />
<Button
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginStart="10dp"
android:layout_weight="1"
android:background="#A00303"
android:elevation="7dp"
android:text="Delete"
android:textColor="#FFFFFF"
tools:visibility="gone" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
Check if file exists in onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int i) {
//check if file exists
Context context = myViewHolder.itemView.getContext();
String pdfName = downModels.get(i).getName()+".pdf";
File file = new File(context.getFilesDir(), pdfName);
if(file.exits()){
//file exists, show delete button
myViewHolder.mDelete.setVisibility(View.VISIBLE);
}else{
//file doesn't exist, hide delete button
myViewHolder.mDelete.setVisibility(View.GONE);
}
.........
.........
.........
}
UPDATE:
After the download is complete call this method on the adapter:
adapter.notifyDataSetChanged();
UPDATE 2:
#Override
protected void onResume() {
super.onResume();
if(myAdapter != null){
myAdapter.notifyDataSetChanged();
}
}
I have updated the layout, replaced the ImageViews with Buttons instaed, and the Listview OnCLick listener is not working now, when I used the old layout with ImageViews. Please let me know if this needs to be further formatted properly, any help will be approciated.
Listener in Activity:
lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ItemDetailsActivity.class);
intent.putExtra("Position", position);
startActivity(intent);
}
});
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/ItemNametv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item : "
android:textSize="20sp"
android:layout_marginBottom="8dp"/>
<TextView
android:id="#+id/qtytv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Qty : "
android:layout_marginBottom="8dp"/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_marginBottom="8dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/EditItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:minWidth="0dp"
android:minHeight="0dp"
style="#style/Widget.AppCompat.Button.Borderless"/>
<Button
android:id="#+id/DeleteItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:textColor="#color/btn_logut_bg"
android:minWidth="0dp"
android:minHeight="0dp"
style="#style/Widget.AppCompat.Button.Borderless"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
ItemDetailsAdapter.java:
public class ItemDetailsAdapter extends BaseAdapter {
private ArrayList<Item> arrayListItem;
private Context context;
private LayoutInflater inflater;
public ItemDetailsAdapter(Context context, ArrayList<Item> arrayListItem) {
this.context = context;
this.arrayListItem = arrayListItem;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayListItem.size();
}
#Override
public Object getItem(int position) {
return arrayListItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
Holder holder;
if (v == null) {
v = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.ItemName = (TextView) v.findViewById(R.id.ItemNametv);
holder.qty = (TextView) v.findViewById(R.id.qtytv);
holder.EditItem = (Button) v.findViewById(R.id.EditItem);
holder.DeleteItem = (Button) v.findViewById(R.id.DeleteItem);
v.setTag(holder);
}
else {
holder = (Holder) v.getTag();
}
holder.ItemName.setText(arrayListItem.get(position).getItem());
holder.qty.setText(arrayListItem.get(position).getQty());
holder.EditItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AddOrUpdateItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("Position", position);
context.getApplicationContext().startActivity(intent);
}
});
holder.DeleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowConfirmDialog(context, position);
}
});
return v;
}
class Holder {
TextView ItemName, qty;
Button DeleteItem, EditItem;
}
public static void ShowConfirmDialog(Context context, final int position) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Are you sure you want to delete this entry?")
.setCancelable(true)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.getInstance().deleteItem(position);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
There is issue of views getting in conflict i.e. views might be getting over lapped by others so add
android:descendantFocusability="blocksDescendants" on your parent layout and list item and for all views for which you want to handle click events, for them, android:focusable="false" add this as well like here in button...
TRY this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent">
Step 1: In list_item.xml, add android:descendantFocusability="blocksDescendants" to your root Linearlayout.
Step 2: In list_item.xml, add android: focusable="false" to android.support.v7.widget.CardView
Note: If there is android:clickable="true" in android.support.v7.widget.CardView remove it.
I need to validate the each field inside recylerview. I didn't find the best approach to perform the validation. The each Edittext field need to validation if the value is empty.Show the toast message on each empty value
Custom XML File
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/carview_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<EditText
android:id="#+id/ET_CT_foodeaten"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Food Eaten"
android:imeActionLabel="Food Eaten"
android:imeOptions="actionUnspecified"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/rel_serving"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linear_ser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="#dimen/carview_margin"
android:text="Servings Eaten"
android:textSize="18dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="-10dp"
android:background="#drawable/linear_layout_radius_custom"
android:orientation="horizontal">
<ImageView
android:layout_width="60sp"
android:id="#+id/minus_foodeaten"
android:layout_height="50sp"
android:padding="#dimen/carview_margin"
android:src="#drawable/minus" />
<View
android:layout_width="1dp"
android:layout_height="35sp"
android:layout_gravity="center"
android:background="#color/TabHeaderColor" />
<ImageView
android:layout_width="60sp"
android:layout_height="50sp"
android:id="#+id/add_foodeaten"
android:padding="#dimen/carview_margin"
android:src="#drawable/ic_add" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/linear_ser"
android:orientation="vertical">
<ImageView
android:id="#+id/IMG_info"
android:layout_width="wrap_content"
android:layout_marginRight="15dp"
android:layout_height="wrap_content"
android:src="#drawable/info" />
<TextView
android:id="#+id/value_serving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="15dp"
android:text="0"
android:textSize="18dp" />
</LinearLayout>
</RelativeLayout>
<View
android:layout_width="1dp"
android:id="#+id/space_view"
android:layout_height="80sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#color/TabHeaderColor" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/rel_serving">
<TextView
android:id="#+id/label_food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_gravity="center"
android:layout_margin="#dimen/carview_margin"
android:text="Food Group"
android:textSize="18dp" />
<Spinner
android:id="#+id/CS_food_group_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/label_food"
android:layout_margin="#dimen/carview_margin"
android:drawSelectorOnTop="true"
android:spinnerMode="dropdown" />
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Adapter code
public class CustomDataAdapterRecylerview extends RecyclerView.Adapter {
private List values;
private Activity activity;
AlertDialog alertDialogStores;
String[] foodLists;
FoodList[] val_list;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
FoodList food_list_value;
public CustomDataAdapterRecylerview(List<String> values, Activity context) {
this.values = values;
this.activity = context;
}
#Override
public CustomDataAdapterRecylerview.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.edittext_twospinner, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final ViewHolder holder = viewHolder;
final int pos = position;
viewHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopUp();
}
});
final ArrayAdapter<CharSequence> foodGroup_adapter = ArrayAdapter.createFromResource(activity, R.array.Food_Group, android.R.layout.simple_spinner_item);
foodGroup_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.FoodGroup_spinner.setAdapter(foodGroup_adapter);
foodLists = new String[100];
val_list = new FoodList[100];
food_list_value = new FoodList();
viewHolder.FoodGroup_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
food_list_value.setServingsEaten(parent.getItemAtPosition(position).toString());
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewHolder.setClickListener(new RecyclerViewItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
if (view.getId() == holder.Add_Food_Item.getId()) {
int val = Integer.parseInt(holder.valueserving.getText().toString());
if (val < 15) {
val++;
food_list_value.setServingsEaten(String.valueOf(val));
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
holder.valueserving.setText(String.valueOf(val));
} else if (view.getId() == holder.Minus_Food_Item.getId()) {
int val = Integer.parseInt(holder.valueserving.getText().toString());
if (val != 0) {
val--;
food_list_value.setServingsEaten(String.valueOf(val));
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
holder.valueserving.setText(String.valueOf(val));
}
{
//Toast.makeText(view.getContext(), "ROW PRESSED = " + String.valueOf(position), Toast.LENGTH_SHORT).show();
}
}
});
viewHolder.Food_Eaten.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
foodLists[pos] = String.valueOf(s);
food_list_value.setFoodEaten(foodLists[pos]);
val_list[pos] = food_list_value;
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
});
}
#Override
public int getItemCount() {
return values.size();
}
public void addItem(String country) {
values.add(country);
notifyItemInserted(values.size());
}
public void removeItem(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
private void showPopUp() {
// add your items, this can be done programatically
// your items can be from a database
List<FoodTrackerAlertDialogModel> ObjectItemData = new ArrayList<FoodTrackerAlertDialogModel>();
ObjectItemData.add(new FoodTrackerAlertDialogModel("Fruit", "1 medium-sized piece of fruit", "1/2 cup berries", "3/4 cup fruit/veggie juice"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Vege\ntables", "1/2 cup raw not-leafy veggies", "1 cup raw leafy veggies", "1 small baked potato"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Dairy", "8 ounces milk", "1 cup yogurt", "1/2 ounces of cheese"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Grains", "1 slice bread", "1 ounce dry cereal", "1/2 cup cooked rice or pasta"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Lean\nMeat\nPoultry", "3 ounces cooked lean meat", "skinless poultry (about the size of a deck of cards)", "1 egg"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Fish", "", "2 to 3 oz. (about the size of the palm of a woman's hand)", ""));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Snacks", "15 potato chips", "2 small cookies", "1/2 cup ice cream"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Fats\nOils", "2 tablespoons light salad dressing", "1 tablespoon low-fat margarine or mayonnaise", "1 teaspoon vegetable oil"));
// our adapter instance
ListViewArrayAdapter adapter = new ListViewArrayAdapter(activity, R.layout.listview_fourtextview, ObjectItemData);
// create a new ListView, set the adapter and item click listener
ListView listViewItems = new ListView(activity);
listViewItems.setAdapter(adapter);
//listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());
// put the ListView in the pop up
alertDialogStores = new AlertDialog.Builder(activity)
.setView(listViewItems)
.setTitle("Examples of what a serving\n").setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialogStores.dismiss();
}
})
.show();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
EditText Food_Eaten;
ImageView info, Add_Food_Item, Minus_Food_Item;
Spinner FoodGroup_spinner;
TextView valueserving;
private RecyclerViewItemClickListener clickListener;
public ViewHolder(View view) {
super(view);
info = (ImageView) view.findViewById(R.id.IMG_info);
Food_Eaten = (EditText) view.findViewById(R.id.ET_CT_foodeaten);
FoodGroup_spinner = (Spinner) view.findViewById(R.id.CS_food_group_spinner);
valueserving = (TextView) view.findViewById(R.id.value_serving);
Add_Food_Item = (ImageView) view.findViewById(R.id.add_foodeaten);
Minus_Food_Item = (ImageView) view.findViewById(R.id.minus_foodeaten);
view.setOnClickListener(this);
view.setOnLongClickListener(this);
Add_Food_Item.setOnClickListener(this);
Minus_Food_Item.setOnClickListener(this);
}
public void setClickListener(RecyclerViewItemClickListener recyclerViewItemClickListener) {
this.clickListener = recyclerViewItemClickListener;
}
#Override
public void onClick(View v) {
clickListener.onClick(v, getPosition(), false);
}
#Override
public boolean onLongClick(View view) {
clickListener.onClick(view, getPosition(), true);
return true;
}
}
}
On click of correct icon if the edit text is empty a validation needs perform and show a toast message.
You need to use this check and print your toast in else part and your implementation in if part -
if (edittext.getText().length() > 0) {
// perform action here
} else {
// show toast here if edittext is empty
}
Hope it may be of help to you.