I have a RecyclerView.Adapter which has some Arrays there.
ArrayList with Strings and ArrayList with Integer. Strings are like url and Integer is the photo.
When the app is open for first time the first item is selected.
I have another method for click which makes another item as selected and this works, but the problem is that the first item stays as selected and so for every image click makes as selected, I want only one item to be selected and take a color.
This is my code.
Adapter of RecyclerView
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
And this is the MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
Initialize your selected item globally
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem = 0;
.....
Then inside your onBindViewHolder whenever you click a new Image notify your adapter for changes in the last selected item cell.
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousSelectedItem = selectedItem;
selectedItem = i;
notifyItemChanged(previousSelectedItem);
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
});
Just remove this line from onBindViewHolder
selectedItem = 0;
and add an else to the background condition, like:
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}else{
viewHolder.image.setBackgroundColor(“YOUR_DEFAULT_COLOR”);
}
and update the onClick:
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedItem = i;
notifyDataSetChanged();
}
});
Related
I am making a feature for my app where the user can add a new food item inside RecyleView. But instead using a new activity I opted out for a popup that appears in the Main Activity where you can enter the food and the price which means the activity doesn't refresh. How can I display the items in the RecycleView without restarting the app?
Code in Main Activity:
public class SecondScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_screen);
myDB = new MyDataBaseHelper(SecondScreen.this);
foodID = new ArrayList<>();
foodName = new ArrayList<>();
foodPrice = new ArrayList<>();
popUp();
//Data from Sql Tables
storeDataInArrays();
customAdapater = new CustomAdapater(SecondScreen.this, foodID, foodName, foodPrice);
recyclerView.setLayoutManager(new LinearLayoutManager(SecondScreen.this));
recyclerView.setAdapter(customAdapater);
//Storing the data from the sql table
public void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
//Gets the count of the rows
if(cursor.getCount() == 0){
Toast.makeText(this, "No data", Toast.LENGTH_SHORT).show();
}else{
while(cursor.moveToNext()){
foodID.add(cursor.getString(0));
foodName.add(cursor.getString(1));
foodPrice.add(cursor.getString(2));
}
}
}
}
public void PopUP(){
btnAddFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyDataBaseHelper myDB = new MyDataBaseHelper(SecondScreen.this);
myDB.addFood(edtFoodName.getText().toString().trim(),
edtFoodPrice.getText().toString().trim());
//Dismisses the popUp after button click
myDialog.dismiss();
}
});
}
}
Code for RecycleView Adapter
public class CustomAdapater extends RecyclerView.Adapter<CustomAdapater.MyViewHolder> {
Context context;
private ArrayList foodID, foodName, foodPrice;
CheckBox chkItem;
//Constructor
CustomAdapater(Context context, ArrayList foodID, ArrayList foodName, ArrayList foodPrice){
//Declares to global variables that can be used in the MainAcivity
this.context = context;
this.foodID = foodID;
this.foodName = foodName;
this.foodPrice = foodPrice;
}
#NonNull
#Override
public CustomAdapater.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Inflates the item_row layout
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CustomAdapater.MyViewHolder holder, int position) {
holder.checkItem.setText(String.valueOf(foodName.get(position)));
holder.foodPrice_txt.setText(String.valueOf(foodPrice.get(position) + "$"));
}
#Override
public int getItemCount() {
return foodID.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView foodPrice_txt;
CheckBox checkItem;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
checkItem = itemView.findViewById(R.id.chkItemRow);
foodPrice_txt = itemView.findViewById(R.id.txtPriceRow);
}
}
}
Call notifyItemInserted after adding the item to your database and array lists, to update your adapter.
Like so:
String foodName = edtFoodName.getText().toString().trim();
String foodPrice = edtFoodPrice.getText().toString().trim();
myDB.addFood(foodName, foodPrice);
foodNames.add(foodName);
foodPrices.add(foodPrice);
customAdapater.notifyItemInserted(foodNames.size() - 1);
I building an app to practice in arraylist and recyclerView.
In the main activity I have "Add" button than I can add things to the arraylit to display in the recyclerView,However,the first time I add new line its working fine,but when I try to add another one,its replacing the first line I added with the new line.
I will be glad if you can point what am I doing wrong,Thank you.
Add Line Activity:
public void AddButton(View view){
if (imageUri != null && !mEditText.getText().toString().isEmpty()){
Intent intent = new Intent(AddCompany.this,MainActivity.class);
intent.putExtra("isAddNewCompany", true);
intent.putExtra("CompanyImage", imageUri.toString());
intent.putExtra("CompanyName", mEditText.getText().toString());
startActivity(intent);
}
}
MainActivity OnCreate with the views:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
ArrayList<String> listTitle = new ArrayList<>();
ArrayList<String> listPicture = new ArrayList<>();
if (intent.getBooleanExtra("isAddNewCompany",false)){
String CompanyImage = intent.getStringExtra("CompanyImage");
String companyName = intent.getStringExtra("CompanyName");
listTitle.add(companyName);
listPicture.add(CompanyImage);
}
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter adapter = new RecyclerAdapter(this,listPicture,listTitle);
adapter.setClickListener(new RecyclerAdapter.ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.e("Position Number - ", String.valueOf(position));
Toast.makeText(MainActivity.this, adapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
recyclerView.setAdapter(adapter);
}
RecyclerView Adapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private final ArrayList<String> mData;
private final ArrayList<String> mImageView;
private final LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
RecyclerAdapter(Context context, ArrayList<String> imageView, ArrayList<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.mImageView = imageView;
}
// inflates the row layout from xml when needed
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
String picture = mImageView.get(position);
Picasso.get().load(picture).into(holder.myImageView);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ImageView myImageView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
myImageView = itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
When you start activity ,every time new list instance will be created that's why you got only one value.if you want already added value, use same list instance.
List<String> listTitle;
List<String> listPicture;
public List<String> getLisPictureInstance(){
if(listPicture ==null)
listPicture = new ArrayList<>();
return listPicture ;
}
public List<String> getListTitleInstance(){
if(listTitle ==null)
listTitle = new ArrayList<>()
return listTitle ;
}
if (intent.getBooleanExtra("isAddNewCompany",false)){
String CompanyImage = intent.getStringExtra("CompanyImage");
String companyName = intent.getStringExtra("CompanyName");
getListTitleInstance().add(companyName);
getLisPictureInstance().add(CompanyImage);
}
I want when user click on item in recycle move on second activity. I have the following adapter:
public class AdapterWassafat extends RecyclerView.Adapter<AdapterWassafat.ViewHolder> {
private ArrayList<Item> itemsList;
private Context mContext;
public AdapterWassafat(ArrayList<Item> itemsList, Context mContext) {
this.itemsList = itemsList;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_wasafat,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Item item = itemsList.get(position);
holder.text.setText(item.getText());
}
#Override
public int getItemCount() {
return itemsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView text;
public ViewHolder(#NonNull View itemView) {
super(itemView);
text = itemView.findViewById(R.id.text_card_main);
}
}
}
and I have this class to add on item list:
public class Item {
private String text;
public Item(String text) {
this.text = text;
}
public Item() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
and this class has recycle:
private AdapterWassafat adapter;
private RecyclerView recyclerView ;
private ArrayList<Item> myList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wasafat);
recyclerView = findViewById(R.id.wasafat_recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getBaseContext()));
adapter = new AdapterWassafat(getMyitem(),getBaseContext());
recyclerView.setAdapter(adapter);
}
private ArrayList<Item> getMyitem() {
ArrayList<Item> list = new ArrayList<>();
Item tips = new Item();
tips.setText("وصفة التمر ");
list.add(tips);
tips = new Item();
tips.setText("وصفة اللبن ");
list.add(tips);
tips = new Item();
tips.setText("وصفة الشاي الاخضر ");
list.add(tips);
return list;}
What do I need to make a recycle view when user click on item move on another activity? Like, as user clicks on item وصفة الشاي, to swap or move on into this activity and so on. I tried a lot of ways to make it both select or click, but that didn't succeed.
In the Adapter:
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Item item = itemsList.get(position);
Context context = holder.itemView.getContext();
holder.text.setText(item.getText());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = Intent(context, YourActivity.class);
intent.putExtra("item", item.getText())
context.startActivity(intent);
}
});
}
In your Other Activity, get data as:
// onCreate()
String value = getIntent().getStringExtra("item", "");
I Have a problem with my Adapter, First I want to display a different Array of data for every item in RecyclerView when clicking on it like this...
Item 1 "display" Array one
Item 2 "display" Array two
And so on... My data will be display in ViewPager on Activity, so I want to pass the data from the RecyclerView Adapter that have the items to the Activity that will display the data "The Activity has Viewpager that will get the data"
So that's what I tried before but it is just open the activity and not display the data.
First Her's My RecyclerView Adapter that has the items And the data
RecyclerViewItems.java
public class RecyclerViewQuran extends RecyclerView.Adapter<RecyclerViewQuran.ViewHolder> {
private ArrayList<QuranListDetail> item;
/* My data "Arrays" */
// first Array for First item
public static int[] mImageIds = new int[]
{
R.drawable.test_heart, R.drawable.test_home,
R.drawable.test_image, R.drawable.test_image, R.drawable.test_video,
};
// second Array for second item
public static int[] mImageIds2 = new int[]
{
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
};
public RecyclerViewQuran(FragmentActivity activity, ArrayList<QuranListDetail> items) {
this.item = items;
}
#Override
public RecyclerViewQuran.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_quran, viewGroup, false));
}
#Override
public void onBindViewHolder(RecyclerViewQuran.ViewHolder holder, final int position) {
holder.itemTitle.setText(item.get(position).getSurahName());
holder.itemDetail.setText(item.get(position).getSurahDetail());
holder.itemNumber.setText(item.get(position).getSurahNumber());
// click listener to open new activity "shurah"
holder.itemClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
// Array 1
if (position == 0) {
int image = mImageIds[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);
}
// Array 2
else if (position == 1) {
int image = mImageIds2[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);}
}
});
}
#Override
public int getItemCount() {
return item.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView itemTitle;
private TextView itemDetail;
private TextView itemNumber;
private View itemClick;
public ViewHolder(View view) {
super(view);
itemTitle = view.findViewById(R.id.surah_name);
itemDetail = view.findViewById(R.id.surah_detail);
itemNumber = view.findViewById(R.id.surah_number);
itemClick = view.findViewById(R.id.item_click);
}
}
.
Second my ViewPagerAdapter.java
public class ViewPagerSurahAdapter extends PagerAdapter {
private Context mContext;
private int[] mImageIds;
public ViewPagerSurahAdapter(Context context, int[] mImageIds) {
mContext = context;
this.mImageIds = mImageIds;
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(#NotNull View view, #NotNull Object object) {
return view == object;
}
#NotNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
// PhotoView to zoom in the image "Instaded of ImageView"
PhotoView imageView = new PhotoView (mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, #NotNull Object object) {
container.removeView((ImageView) object);
}
}
Third My Activity that will display the data in the ViewPager, My problem here I don't know how to pass the data in the ViewPager, Her's what I did.
public class QuranSurahDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_surah);
final Intent intent = getIntent();
if (intent.hasExtra("imageDisplay")) {
ViewPager viewPager = findViewById(R.id.view_pager_quran_fateha);
int[] url = intent.getIntArrayExtra("imageDisplay");
//ViewPager
ViewPagerSurahAdapter adapter = new ViewPagerSurahAdapter(this,url);
viewPager.setAdapter(adapter);
}
}
}
If you have any questions u can write it in the comments and I will be explaining to you.
[Code below] Item in RecycleView doesn't click [it should open the DetailActivity], I try to find the mistake but I didn't understand where
What I try :
Change size items
Change RecycleView to VERTICAL
Write Log.v
I have the same RecycleViewAdapter but it vertical, and it is working well.
my all project : https://github.com/sanke46/E-Commerce
RecycleViewAdapter :
public class SalesRecyclerViewAdapter extends RecyclerView.Adapter<SalesRecyclerViewAdapter.ViewHolder> {
BasketActivity basketActivity = new BasketActivity();
private List<Item> itemList = basketActivity.getBasketItem();
private ArrayList arr;
private Context mContext;
public SalesRecyclerViewAdapter(Context context, ArrayList<Item> data) {
this.arr = data;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sale, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Item item = (Item) arr.get(position);
Picasso.with(mContext).load(item.getImageUrl()).into(holder.imageView);
holder.price.setText(item.getPrice() + " $");
holder.price.setPaintFlags(holder.price.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
holder.fixPrice.setText(item.getDiscontPrice() + " $");
holder.name.setText(item.getName());
holder.comment.setText(item.getComment());
holder.gramm.setText(item.converGramms(String.valueOf(item.getGramms())));
holder.kal.setText(item.getKalories() + " kal");
holder.addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemList.add((Item) arr.get(position));
basketActivity.setBasketItem(itemList);
}
});
holder.linerSaleClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra("item", item);
mContext.startActivity(intent);
Log.v("SALES", "SALES");
}
});
}
#Override
public int getItemCount() {
return arr.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout linerSaleClick;
private ImageView imageView;
private TextView price;
private TextView fixPrice;
private TextView name;
private TextView comment;
private TextView gramm;
private TextView kal;
private Button addToCart;
public ViewHolder(View itemView) {
super(itemView);
linerSaleClick = itemView.findViewById(R.id.linerSaleClick);
imageView = itemView.findViewById(R.id.imageSale);
price = itemView.findViewById(R.id.price);
kal = itemView.findViewById(R.id.kal);
gramm = itemView.findViewById(R.id.gramm);
name = itemView.findViewById(R.id.name);
comment = itemView.findViewById(R.id.comments);
fixPrice = itemView.findViewById(R.id.fixPrice);
addToCart = itemView.findViewById(R.id.buttonTwo);
}
}}
Basically code on your github is different than what you posted. So probably the reason of problem is:
In list_sale.xml
I noticed that in this view com.makeramen.roundedimageview.RoundedImageView you set parametr android:clickable="true" then if you want to rise click event on parent (RelativeLayout) it will not work. Solution: remove this line android:clickable="true".