My ListView works fine on start up. The problem is that whenever I click the search Button which triggers the search view, all items on my ListView disappears. Even after I clear the text field on my searchview, my ListView still is on a state where it is empty.
Loanist_Full.java (Main activity)
package com.memger.pautanganapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class Loanist_Full extends AppCompatActivity {
private ListView listView;
private ListView_Adapter adapter;
private ListView_Model model;
private ArrayList<ListView_Model> arrayList = new ArrayList<ListView_Model>();
private MenuItem searchItem;
private SearchView searchView;
private TextView totalText, totalCount;
private ImageButton sortBy;
private FloatingActionButton addDebtorButton;
public static final String currency = "₱";
public static final DecimalFormat formatter = new DecimalFormat("###,###,###.##");
String mContact[] = {"Craig", "Agatha", "Dave", "Brandon", "Russel", "Gleceper", "Percy", "Test"};
double mDebt[] = {2000, 525, 8000, 5000, 955, 4000, 50123, 51247};
double mDebtTotal = 0;
String mDesc[] = {"This is a description et. cetera", "Ito bata pa dapat di pa pinapautang", "Lalo na to kakatuto lang mag bike nangungutang na", "", "", "", "", ""};
String mDate[] = {"Apr. 21, 2016", "Mar. 4, 2017", "May 14, 2011", "Mar. 1, 2000", "Jul. 14, 1971", "", "", ""};
int mImg[] = {R.drawable.debtcontact_craig, R.drawable.debtcontact_agatha, R.drawable.debtcontact_dave, R.drawable.debtcontact_brandon, R.drawable.debtcontact_russel, R.drawable.debtcontact_gleceper, R.drawable.debtcontact_lola, R.drawable.ic_launcher_background};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loanist_full);
totalText = findViewById(R.id.TotalTextView);
totalCount = findViewById(R.id.CountTextView);
listView = findViewById(R.id.listView);
adapter = new ListView_Adapter(this, arrayList);
listView.setAdapter(adapter);
sortBy = findViewById(R.id.SortByButton);
addDebtorButton = findViewById(R.id.AddDebtorButton);
/* TO DO */
displayListViewContents();
setTextTotal();
/* OnClickListeners below */
/* Listview item */
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
makeDialog(ListView_Adapter.modellist.get(i).getModelContact(),
ListView_Adapter.modellist.get(i).getModelDebt(),
ListView_Adapter.modellist.get(i).getModelDesc(),
ListView_Adapter.modellist.get(i).getModelDate());
}
});
/* Sort by button*/
sortBy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sortArray();
sortArrayList();
}
});
/* Debtor Button*/
addDebtorButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Loanist_Full.this, Loanist_Add_Debtor.class));
}
});
} /* END onCreate*/
/* Display listview contents */
private void displayListViewContents(){
/* Display contents of listview*/
for(int i = 0; i < mDebt.length; i++){
model = new ListView_Model(mContact[i], mDebt[i], mDesc[i], mDate[i], mImg[i]);
arrayList.add(model);
}
totalCount.setText("Count: " + adapter.getCount());
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
totalCount.setText("Count: " + adapter.getCount());
}
});
}
/* Set "Total" view text */
private void setTextTotal(){
/* Set text of Total based on total amt of mDebt*/
for (double x: mDebt) { //Compute total mDebt
mDebtTotal += x;
}
if (mDebtTotal == 0){ //If mDebtTotal == 0
totalText.setText("Create a debt with an amount first.");
} else {
totalText.setText("Total: " + currency + " " + formatter.format(mDebtTotal));
}
}
/* Sort item list */
private void sortArray(){
Arrays.sort(mContact);
adapter.notifyDataSetChanged();
}
/* Sort array list */
private void sortArrayList(){
Collections.sort(arrayList, new Comparator<ListView_Model>() {
#Override
public int compare(ListView_Model listView_model, ListView_Model t1) {
return listView_model.getModelContact().compareTo(t1.getModelContact());
}
});
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
searchItem = menu.findItem(R.id.app_searchbutton);
searchItem.getActionView();
searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Enter a contact e.g 'Robert'");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)){
adapter.filter("");
listView.clearTextFilter();
}
else {
adapter.filter(newText);
}
//totalCount.setText("Count: " + adapter.getCount());
return true;
}
});
return true;
}
/* Creates a dialog whenever an item on listview is clicked*/
private void makeDialog(String contact, double debtAmt, String debtDesc, String debtDate){
AlertDialog alertDialog = new AlertDialog.Builder(Loanist_Full.this).create();
alertDialog.setTitle("Debt Information");
if (debtDesc.length() < 1)
debtDesc = "N/A";
if (debtDate.length() < 1)
debtDate = "N/A";
alertDialog.setMessage("\n" + contact + "'s debt is " + this.currency + " " + debtAmt + "\n\nDescription: " + debtDesc + "\nDebt created: " + debtDate);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
Loanist_full.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".Loanist_Full">
<LinearLayout
android:id="#+id/TotalBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#eaeaea"
android:orientation="horizontal"
>
<TextView
android:id="#+id/TotalTextView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:gravity="center_vertical"
android:text="Total"
android:textSize="16dp"
android:textStyle="bold"
android:layout_weight="1"
/>
<TextView
android:id="#+id/CountTextView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="15dp"
android:gravity="center_vertical"
android:text="Count"
android:textSize="14dp"
/>
<ImageButton
android:id="#+id/SortByButton"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_marginRight="15dp"
android:layout_gravity="center_vertical"
android:src="#drawable/ic_sort_black_24dp"
android:background="?android:selectableItemBackground"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="3.0dip"
android:background="#drawable/divider_total"
android:layout_below="#id/TotalBar"
/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#drawable/divider_listview"
android:dividerHeight="0.2dp"
android:layout_below="#id/TotalBar"
/>
<com.getbase.floatingactionbutton.AddFloatingActionButton
android:id="#+id/AddDebtorButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_margin="8dp"
app:fab_colorNormal="#color/lightYellow"
app:fab_colorPressed="#color/lightYellowPressed"
/>
</RelativeLayout>
ListView_Adapter.java
package com.memger.pautanganapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ListView_Adapter extends BaseAdapter {
Context mcontext;
LayoutInflater inflater;
public static List<ListView_Model> modellist;
ArrayList<ListView_Model> arrayList;
public ListView_Adapter(Context context, List<ListView_Model> modellist){
mcontext = context;
inflater = LayoutInflater.from(mcontext);
this.modellist = modellist;
this.arrayList = new ArrayList<ListView_Model>();
this.arrayList.addAll(modellist);
}
public class ViewHolder{
TextView myContact, myDebt, myDesc, myDate;
ImageView myImg;
}
#Override
public int getCount() {
return modellist.size();
}
#Override
public Object getItem(int i) {
return modellist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.listview_row, null);
holder.myContact = convertView.findViewById(R.id.Contact);
holder.myDebt = convertView.findViewById(R.id.Debt);
holder.myDesc = convertView.findViewById(R.id.Desc);
holder.myDate = convertView.findViewById(R.id.Date);
holder.myImg = convertView.findViewById(R.id.ContactImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.myContact.setText(modellist.get(position).getModelContact());
holder.myDebt.setText(Loanist_Full.currency + " " + Loanist_Full.formatter.format(modellist.get(position).getModelDebt()));
holder.myDate.setText(modellist.get(position).getModelDate());
holder.myDesc.setText(modellist.get(position).getModelDesc());
holder.myImg.setImageResource(modellist.get(position).getModelImg());
return convertView;
}
/* Filter */
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
modellist.clear();
if (charText.length()==0){
modellist.addAll(arrayList);
}
else {
for (ListView_Model model : arrayList){
if (model.getModelContact().toLowerCase(Locale.getDefault()).contains(charText)){
modellist.add(model); //Add to modellist those who contain the words in the search bar
}
}
}
notifyDataSetChanged();
}
}
Related
I am creating a ecommerce application. In which I am managing Cart screen.
The cart screen is included in HomeFragment's layout. From the adapter I am calling interface to transfer the data and update to the cart screen which appears when the cart value is greater than -> 0.
The problem is that when I click on "Add to cart" button of any item from recyclerview the "Add to cart" disappers and counter layout appears. as shown in the below images.
Clicking on single item ther other rows's "Add to cart" button disappears which must be not disapper. It is affecting multiple rows on single row change.
How to solve that issue any solution from your side?
HomeFragment.java
package com.example.rangeela_cart.Fragments;
import android.content.Intent;
import android.os.Bundle;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.rangeela_cart.Activity.CartActivity;
import com.example.rangeela_cart.Adapter.HomeFragImageSliderAdapter;
import com.example.rangeela_cart.Adapter.HomeFragLatestProAdapter;
import com.example.rangeela_cart.Adapter.HomeFragPopularProAdapter;
import com.example.rangeela_cart.R;
import com.example.rangeela_cart.databinding.ActivityCartBinding;
import com.example.rangeela_cart.databinding.FragmentHomeBinding;
import com.example.rangeela_cart.models.HomeFragImageSliderModel;
import com.example.rangeela_cart.models.HomeFragLatestProModel;
import com.example.rangeela_cart.models.HomePopularProModel;
import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType;
import com.smarteist.autoimageslider.SliderView;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
private View view;
public FragmentHomeBinding binding;
private List<HomeFragImageSliderModel> imageSliderModelList = new ArrayList<>();
private HomeFragImageSliderAdapter adapter;
private List<HomePopularProModel> homePopularProModelList = new ArrayList<>();
private HomeFragPopularProAdapter homeFragPopularProAdapter;
private List<HomeFragLatestProModel> homeFragLatestProModelList = new ArrayList<>();
private HomeFragLatestProAdapter latestProAdapter;
int val = 0;
int counter;
ActivityCartBinding activity_cart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
view = binding.getRoot();
intiView();
return view;
}
private void intiView() {
activity_cart = binding.layoutCart;
setCustomImage();
setPopularProducts();
setLatestPro();
binding.textLatest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), CartActivity.class).putExtra("value", "200"));
}
});
loadCart();
}
private void setCustomImage() {
HomeFragImageSliderModel model1 = new HomeFragImageSliderModel("https://5.imimg.com/data5/NJ/DW/YW/SELLER-8673553/namkeen-packaging-pouch-500x500.jpg", "1");
imageSliderModelList.add(model1);
HomeFragImageSliderModel model2 = new HomeFragImageSliderModel("https://5.imimg.com/data5/AV/FR/QL/SELLER-9988068/laminated-namkeen-packaging-packet-500x500.jpg", "2");
imageSliderModelList.add(model2);
HomeFragImageSliderModel model3 = new HomeFragImageSliderModel("https://thumbs.dreamstime.com/b/new-delhi-india-november-packets-chips-indian-brand-haldirams-packaged-food-182551372.jpg", "3");
imageSliderModelList.add(model3);
HomeFragImageSliderModel model4 = new HomeFragImageSliderModel("https://vinayakfoodsgroup.com/indian-ready-to-eat/wp-content/uploads/2019/07/delicious-healthy-breakfast2-4.jpg", "4");
imageSliderModelList.add(model4);
adapter = new HomeFragImageSliderAdapter(getActivity(), imageSliderModelList);
binding.autoImageSlider.startAutoCycle();
binding.autoImageSlider.setAutoCycle(true);
binding.autoImageSlider.setIndicatorAnimation(IndicatorAnimationType.WORM);
binding.autoImageSlider.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
binding.autoImageSlider.setScrollTimeInSec(3);
binding.autoImageSlider.setSliderAdapter(adapter);
}
private void setPopularProducts() {
HomePopularProModel model1 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "300", "RN Cart");
homePopularProModelList.add(model1);
HomePopularProModel model2 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "200", "RN Cart");
homePopularProModelList.add(model2);
HomePopularProModel model3 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "100", "RN Cart");
homePopularProModelList.add(model3);
HomePopularProModel model4 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "50", "RN Cart");
homePopularProModelList.add(model4);
homeFragPopularProAdapter = new HomeFragPopularProAdapter(getActivity(), homePopularProModelList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
SnapHelper startSnapHelper = new LinearSnapHelper();
startSnapHelper.attachToRecyclerView(binding.recyclerviewPopular);
binding.recyclerviewPopular.setLayoutManager(layoutManager);
binding.recyclerviewPopular.setItemAnimator(new DefaultItemAnimator());
binding.recyclerviewPopular.setAdapter(homeFragPopularProAdapter);
homeFragPopularProAdapter.setOnItemClickListner(new HomeFragPopularProAdapter.onItemClickListner() {
#Override
public void onClick(HomePopularProModel list) {
val = Integer.parseInt(list.getPro_price());
counter += val;
loadCart();
}
#Override
public void onCounterClick(HomePopularProModel listCounter, String from) {
if (from == "add"){
counter += Integer.parseInt(listCounter.getPro_price());
loadCart();
}else{
counter -= Integer.parseInt(listCounter.getPro_price());
loadCart();
}
}
});
}
private void setLatestPro() {
HomeFragLatestProModel model = new HomeFragLatestProModel(
"https://5.imimg.com/data5/NJ/DW/YW/SELLER-8673553/namkeen-packaging-pouch-500x500.jpg",
"Namkeen", "500gm", "Rs.350");
homeFragLatestProModelList.add(model);
HomeFragLatestProModel model2 = new HomeFragLatestProModel(
"https://5.imimg.com/data5/AV/FR/QL/SELLER-9988068/laminated-namkeen-packaging-packet-500x500.jpg",
"Sona Namkeen", "250gm", "Rs.100");
homeFragLatestProModelList.add(model2);
HomeFragLatestProModel model3 = new HomeFragLatestProModel(
"https://thumbs.dreamstime.com/b/new-delhi-india-november-packets-chips-indian-brand-haldirams-packaged-food-182551372.jpg",
"Chips", "500gm", "Rs.80");
homeFragLatestProModelList.add(model3);
HomeFragLatestProModel model4 = new HomeFragLatestProModel(
"https://thumbs.dreamstime.com/b/packets-popular-brands-snack-food-poznan-poland-jun-packets-popular-brands-snack-food-including-lays-crunchips-120285289.jpg",
"Lays", "100", "Rs.40");
homeFragLatestProModelList.add(model4);
HomeFragLatestProModel model5 = new HomeFragLatestProModel(
"https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F38%2F2015%2F06%2F12233316%2FMichael-Angelo-Meal-Starter-Chicken-Bruschetta.jpg",
"Chicken Masala", "500gm", "Rs.400");
homeFragLatestProModelList.add(model5);
HomeFragLatestProModel model6 = new HomeFragLatestProModel(
"https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F38%2F2015%2F06%2F12233316%2FMichael-Angelo-Meal-Starter-Chicken-Bruschetta.jpg",
"Dry Food", "500gm", "Rs.550");
homeFragLatestProModelList.add(model6);
setDataToLatestRecycler(homeFragLatestProModelList);
}
private void setDataToLatestRecycler(List<HomeFragLatestProModel> latestProModelList) {
latestProAdapter = new HomeFragLatestProAdapter(getActivity(), latestProModelList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
binding.recyclerviewLatest.setLayoutManager(layoutManager);
binding.recyclerviewLatest.setItemAnimator(new DefaultItemAnimator());
binding.recyclerviewLatest.setAdapter(latestProAdapter);
}
public void loadCart() {
activity_cart.cartValue.setText(String.valueOf(counter));
if (counter > 0) {
binding.layoutCart.getRoot().setVisibility(View.VISIBLE);
} else {
binding.layoutCart.getRoot().setVisibility(View.GONE);
}
}
}
Adapter class
package com.example.rangeela_cart.Adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.rangeela_cart.R;
import com.example.rangeela_cart.databinding.ItemHomePopularProBinding;
import com.example.rangeela_cart.models.HomePopularProModel;
import java.util.List;
public class HomeFragPopularProAdapter extends RecyclerView.Adapter<HomeFragPopularProAdapter.myViewHolder> {
private Context context;
private List<HomePopularProModel> list;
int productSelectedNumber = 0;
public HomeFragPopularProAdapter(Context context, List<HomePopularProModel> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
ItemHomePopularProBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_home_popular_pro, parent, false);
return new myViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
HomePopularProModel model = list.get(position);
Glide.with(context).load(model.getPro_image_url()).into(holder.binding.imagePopProduct);
holder.binding.textAvailability.setText(model.getPro_availability());
holder.binding.textCompanyName.setText(model.getPro_company_name());
holder.binding.textPopProductPrice.setText(model.getPro_price());
Log.e("initial counter " , String.valueOf(productSelectedNumber));
if (productSelectedNumber == 0) {
holder.binding.iconReduce.setEnabled(false);
holder.binding.layoutAddToCart.setVisibility(View.VISIBLE);
holder.binding.layoutCounter.setVisibility(View.GONE);
} else {
holder.binding.iconReduce.setEnabled(true);
holder.binding.layoutAddToCart.setVisibility(View.GONE);
holder.binding.layoutCounter.setVisibility(View.VISIBLE);
}
holder.binding.iconAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("added value ", String.valueOf(productSelectedNumber));
holder.binding.iconReduce.setEnabled(true);
productSelectedNumber += 1;
holder.binding.textCounterValue.setText(String.valueOf(productSelectedNumber));
onItemClickListner.onCounterClick(model, "add");
// notifyDataSetChanged();
}
});
holder.binding.iconReduce.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("reduce value = ", String.valueOf(productSelectedNumber));
if (productSelectedNumber != 0) {
productSelectedNumber = productSelectedNumber - 1;
holder.binding.textCounterValue.setText(String.valueOf(productSelectedNumber));
}else{
holder.binding.layoutAddToCart.setVisibility(View.VISIBLE);
holder.binding.layoutCounter.setVisibility(View.GONE);
}
onItemClickListner.onCounterClick(model, "reduce");
// notifyDataSetChanged();
}
});
holder.binding.layoutAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productSelectedNumber = 1;
holder.binding.textCounterValue.setText(String.valueOf(productSelectedNumber));
onItemClickListner.onClick(model);
holder.binding.layoutAddToCart.setVisibility(View.GONE);
holder.binding.layoutCounter.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
public class myViewHolder extends RecyclerView.ViewHolder {
ItemHomePopularProBinding binding;
public myViewHolder(ItemHomePopularProBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
onItemClickListner onItemClickListner;
public void setOnItemClickListner(HomeFragPopularProAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner{
void onClick(HomePopularProModel list);
void onCounterClick(HomePopularProModel list, String str);//pass your object types.
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:orientation="vertical"
tools:context=".Fragments.HomeFragment">
<com.smarteist.autoimageslider.SliderView
android:id="#+id/autoImageSlider"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#color/white"
app:sliderAnimationDuration="200"
app:sliderAutoCycleDirection="back_and_forth"
app:sliderIndicatorAnimationDuration="600"
app:sliderIndicatorEnabled="true"
app:sliderIndicatorOrientation="horizontal"
app:sliderIndicatorPadding="5dp"
app:sliderIndicatorRadius="3dp"
app:sliderScrollTimeInSec="3"
tools:ignore="MissingClass" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Popular"
android:textColor="#color/black"
android:textSize="15sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewPopular"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:itemCount="10" />
<TextView
android:id="#+id/textLatest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="Latest"
android:textColor="#color/black"
android:textSize="15sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewLatest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:paddingBottom="15dp" />
</LinearLayout>
</ScrollView>
<include
android:id="#+id/layoutCart"
layout="#layout/activity_cart"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Good evening everyone !
I am currently working on an ExpandableListView.
The parent contains 1 ImageView.
The child contains 1 TextView and 3 Buttons.
In terms of display, no problem: everything works as I want.
However, I want to add actions to my buttons and I realize that when I put a SetOnclickListener in the getChildView I am not able to launch a new INTENT.
The examples I find on the internet seem to show only clicks on dynamic elements. However, the buttons are not dynamic in my case.
I planned to use a variable to do a SWITCH and thus launch the right INTENT.
But since it doesn't work, I wonder if my direction is the right one.
MaintActivity.java
package com.evo.tab2escape;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
public class jeux2 extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<Integer> headerData;
HashMap<Integer,ArrayList<ChildDataModel>> childData;
ChildDataModel childDataModel;
Context mContext;
ArrayList<ChildDataModel> logo0,logo1,logo2,logo3,logo4,logo5,logo6,logo7,logo8,logo9,logo10,logo11;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.jeux2);
mContext = this;
headerData = new ArrayList<>();
childData = new HashMap<Integer, ArrayList<ChildDataModel>>();
logo0 = new ArrayList<>();
logo1 = new ArrayList<>();
logo2 = new ArrayList<>();
logo3 = new ArrayList<>();
logo4 = new ArrayList<>();
logo5 = new ArrayList<>();
logo6 = new ArrayList<>();
logo7 = new ArrayList<>();
logo8 = new ArrayList<>();
logo9 = new ArrayList<>();
logo10 = new ArrayList<>();
logo11 = new ArrayList<>();
// get the listview
expListView = (ExpandableListView) findViewById(R.id.ExpandableListView);
// populate data
// Adding header data
headerData.add(R.drawable.logo0);
headerData.add(R.drawable.logo1);
headerData.add(R.drawable.logo2);
headerData.add(R.drawable.logo3);
headerData.add(R.drawable.logo4);
headerData.add(R.drawable.logo5);
headerData.add(R.drawable.logo6);
headerData.add(R.drawable.logo7);
headerData.add(R.drawable.logo8);
headerData.add(R.drawable.logo9);
headerData.add(R.drawable.logo10);
headerData.add(R.drawable.logo11);
// Adding child data
childDataModel = new ChildDataModel(1,"Test0","logo0");
logo0.add(childDataModel);
childData.put(headerData.get(0),logo0);
childDataModel = new ChildDataModel(1,"Test1","logo1");
logo1.add(childDataModel);
childData.put(headerData.get(1),logo1);
childDataModel = new ChildDataModel(1,"Test2","logo2");
logo2.add(childDataModel);
childData.put(headerData.get(2),logo2);
childDataModel = new ChildDataModel(1,"Test3","logo3");
logo3.add(childDataModel);
childData.put(headerData.get(3),logo3);
childDataModel = new ChildDataModel(1,"Test4","logo4");
logo4.add(childDataModel);
childData.put(headerData.get(4),logo4);
childDataModel = new ChildDataModel(1,"Test5","logo5");
logo5.add(childDataModel);
childData.put(headerData.get(5),logo5);
childDataModel = new ChildDataModel(1,"Test6","logo6");
logo6.add(childDataModel);
childData.put(headerData.get(6),logo6);
childDataModel = new ChildDataModel(1,"Test7","logo7");
logo7.add(childDataModel);
childData.put(headerData.get(7),logo7);
childDataModel = new ChildDataModel(1,"Test8","logo8");
logo8.add(childDataModel);
childData.put(headerData.get(8),logo8);
childDataModel = new ChildDataModel(1,"test09","logo9");
logo9.add(childDataModel);
childData.put(headerData.get(9),logo9);
childDataModel = new ChildDataModel(1,"test10","logo10");
logo10.add(childDataModel);
childData.put(headerData.get(10),logo10);
childDataModel = new ChildDataModel(1,"test11","logo11");
logo11.add(childDataModel);
childData.put(headerData.get(11),logo11);
listAdapter = new ExpandableListAdapter(this, headerData, childData);
// setting list adapter
expListView.setAdapter(listAdapter);
//--------------------------child click listener--------------------------
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
Log.d("TEST", "onChildClick: " + groupPosition + " " + childPosition + " " + id + " " + parent);
//Toast.makeText(getApplicationContext(), "heeeeeeeeerrrrreeeee!", Toast.LENGTH_SHORT).show();
return true;
}
});
//group expanded
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int headPosition) {
if (lastExpandedPosition != -1
&& headPosition != lastExpandedPosition) {
expListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = headPosition;
}
});
//group collapsed
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int headPosition) {
}
});
//--------------------------RETOUR--------------------------
Button retour = (Button) findViewById(R.id.retour);
retour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent Intent_next = new Intent(jeux2.this, MainActivity.class);
startActivity(Intent_next);
}
});
//--------------------------HISTO--------------------------
TextView histo = (TextView) findViewById(R.id.histo);
histo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent Intent_next = new Intent(jeux2.this, historique.class);
startActivity(Intent_next);
}
});
}
}
class ChildDataModel
{
long id;
String txt;
String aventure;
public ChildDataModel(int id, String explications, String aventure) {
this.setId(id);
this.setTxt(explications);
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTxt() {
return txt;
}
public void setTxt(String explications) {
this.txt = explications;
}
public String getTxt_aventure() {
return aventure;
}
#Override
public String toString()
{
return super.toString();
}
}
ExpandableListAdapter.java
package com.evo.tab2escape;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<Integer> headerData; // Images
// child data in format of header , child
private HashMap<Integer, ArrayList<ChildDataModel>> childData;
public ExpandableListAdapter(Context context, List<Integer> listDataHeader,
HashMap<Integer, ArrayList<ChildDataModel>> childData) {
this._context = context;
this.headerData = listDataHeader;
this.childData = childData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this.childData.get(this.headerData.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ChildDataModel child = (ChildDataModel) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView explications = (TextView) convertView.findViewById(R.id.explications);
explications.setText(child.getTxt());
Button play = (Button) convertView.findViewById(R.id.play);
Button doc = (Button) convertView.findViewById(R.id.doc);
Button param = (Button) convertView.findViewById(R.id.param);
final String aventure = child.getTxt_aventure();
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d("TAG", "poulet: ");
}
});
doc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d("TAG", "poulet: ");
}
});
param.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d("TAG", "poulet: ");
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.childData.get(this.headerData.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.headerData.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.headerData.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
ImageView logo = (ImageView) convertView.findViewById(R.id.logo);
int imageId = this.headerData.get(groupPosition);
logo.setImageResource(imageId);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Space
android:layout_width="match_parent"
android:layout_height="20dp">
</Space>
<ImageView
android:id="#+id/logo"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="100dp"/>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:id="#+id/divers">
<TextView
android:id="#+id/explications"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical"
android:textStyle="bold"
android:layout_weight="1.5">
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal">
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jouer"
android:layout_gravity="center"
android:background="#drawable/bouton_main"
android:layout_weight="1">
</Button>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
</Space>
<Button
android:id="#+id/doc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Documents"
android:layout_gravity="center"
android:background="#drawable/bouton_main"
android:layout_weight="1">
</Button>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
</Space>
<Button
android:id="#+id/param"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paramètres"
android:layout_gravity="center"
android:background="#drawable/bouton_main"
android:layout_weight="1">
</Button>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
</Space>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Can somoene help me ?
I want to start a new intent on click on Button.
Edit : i add child Click Listener on MainActivity but its works only if i set clickable,focusable = false on the 3 Buttons in layout list_item.xml.
And than the click is on the complete child. I can't say if the click is on Button 1, 2 or 3.
Can we fix it ?
Problem solved.
I do this in ExpandableListAdapter in getChildView.
param.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next = new Intent(parent.getContext(), parametres.class);
parent.getContext().startActivity(next);
}
});
I have a button that says ADD ITEM.
Below there is a RECYCLERVIEW.
When you click on ADD ITEM it adds an EDITVIEW to the recycler view. You type text in it, and then click on ADD ITEM again and it adds another EDITVIEW to the recyler view.
Everything is in the right order.
When you click on ADD ITEM for the 4th time, instead of adding at the 4th position, it adds at the 1st position and moves the previous 3 items down 1.
What could be causing this?
Main Activity
package com.app.bowling.animalsrecycler;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import static java.sql.Types.NULL;
public class MainActivity extends Activity implements RemoveClickListner{
private RecyclerView mRecyclerView;
private RecyclerAdapter mRecyclerAdapter;
private RecyclerView.LayoutManager mLayoutManager;
Button btnAddItem;
ArrayList<RecyclerData> myList = new ArrayList<>();
EditText etTitle;
String title = "";
ImageView crossImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerAdapter = new RecyclerAdapter(myList,this);
mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
mRecyclerView.setAdapter(mRecyclerAdapter);
etTitle = (EditText) findViewById(R.id.etTitle);
if (mRecyclerAdapter.getItemCount() == 0 || mRecyclerAdapter.getItemCount() == NULL){
Toast.makeText(getApplicationContext(),"ZERO ITEMS LISTED",Toast.LENGTH_SHORT).show();
}
btnAddItem = (Button) findViewById(R.id.btnAddItem);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
title = etTitle.getText().toString();
// if (title.matches("")) {
// Toast.makeText(v.getContext(), "You did not enter a Title", Toast.LENGTH_SHORT).show();
// return;
// }
RecyclerData mLog = new RecyclerData();
// mLog.setTitle(title);
myList.add(mLog);
mRecyclerAdapter.notifyData(myList);
etTitle.setText("");
if (mRecyclerAdapter.getItemCount() > 0) {
Toast.makeText(v.getContext(), mRecyclerAdapter.getItemCount() + " Items Displayed", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
#Override
public void OnRemoveClick(int index) {
myList.remove(index);
mRecyclerAdapter.notifyData(myList);
}
}
RecyclerAdapter
package com.app.bowling.animalsrecycler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerItemViewHolder> {
private ArrayList<RecyclerData> myList;
int mLastPosition = 0;
private RemoveClickListner mListner;
public RecyclerAdapter(ArrayList<RecyclerData> myList,RemoveClickListner listner) {
this.myList = myList;
mListner=listner;
}
public RecyclerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
RecyclerItemViewHolder holder = new RecyclerItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerItemViewHolder holder, final int position) {
Log.d("onBindViewHolder ", myList.size() + "");
mLastPosition = position;
holder.crossImage.setImageResource(R.drawable.ic_add_circle_black_24dp);
holder.etTitleTextView.setHint("Enter Player " + (position + 1));
holder.etTitleTextView.requestFocus();
}
#Override
public int getItemCount() {
return(null != myList?myList.size():0);
}
public void notifyData(ArrayList<RecyclerData> myList) {
Log.d("notifyData ", myList.size() + "");
this.myList = myList;
notifyDataSetChanged();
}
public class RecyclerItemViewHolder extends RecyclerView.ViewHolder {
private final TextView etTitleTextView;
private ConstraintLayout mainLayout;
public ImageView crossImage;
public RecyclerItemViewHolder(final View parent) {
super(parent);
etTitleTextView = parent.findViewById(R.id.txtTitle);
etTitleTextView.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) {
myList.get(getAdapterPosition()).setTitle(etTitleTextView.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
crossImage = (ImageView) parent.findViewById(R.id.crossImage);
mainLayout = (ConstraintLayout) parent.findViewById(R.id.mainLayout);
mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Position:" + Integer.toString(getPosition()), Toast.LENGTH_SHORT).show();
}
});
crossImage.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
mListner.OnRemoveClick(getAdapterPosition()
);
}
});
}
}
RecyclerData
package com.app.bowling.animalsrecycler;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
public class RecyclerData {
String title;
RecyclerView data;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setCrossImage(ImageView crossImage){
setCrossImage(crossImage);
}
}
RemoveClickLstner
package com.app.bowling.animalsrecycler;
public interface RemoveClickListner {
void OnRemoveClick(int index);
}
Activity_Main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:padding="16dp"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:id="#+id/etTitle" />
<Button
android:id="#+id/btnAddItem"
android:text="Add Item"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dbfffe" />
</LinearLayout>
RecyclerView_Item
<LinearLayout 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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_margin="8dp"
android:id="#+id/cardview"
android:layout_height="112dp">
<android.support.constraint.ConstraintLayout
android:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/txtTitle"
android:maxLines="1"
android:inputType="text"
android:maxLength="15"
android:layout_width="273dp"
android:layout_height="56dp"
android:layout_marginEnd="122dp"
android:layout_marginBottom="56dp"
android:padding="12dp"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_conversion_absoluteHeight="0dp"
tools:layout_conversion_absoluteWidth="0dp"
tools:layout_conversion_wrapHeight="0"
tools:layout_conversion_wrapWidth="0" />
<ImageView
android:id="#+id/crossImage"
android:layout_width="136dp"
android:layout_height="112dp"
android:layout_marginStart="273dp"
android:background="#drawable/ic_add_circle_black_24dp"
android:paddingLeft="10dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_conversion_absoluteHeight="0dp"
tools:layout_conversion_absoluteWidth="0dp"
tools:layout_conversion_wrapHeight="0"
tools:layout_conversion_wrapWidth="0" />
</android.support.constraint.ConstraintLayout>
</LinearLayout>
Just try to replace your below snippet
myList.add(mLog);
mRecyclerAdapter.notifyData(myList);
etTitle.setText("");
Add this:
myList.add(mLog);
mRecyclerAdapter.addAll(myList);
mRecyclerAdapter.notifyDataSetChanged();
etTitle.setText("");
I would like to see your layout activity_main and recycler_view item because I have tried implementing your code with few twist and the code is working well please check the code below
https://github.com/muchbeer/StackOverflowRecyclerView
Please find the below Screen Shot
Kindy let me if this was your intended application
I have a problem binding a listview with ArrayList. When the first Vegetable Category is clicked it should bring different 3 elements in the listview but only the first one is displayed on the listview the others didn't show up.
here is my code (I am new to android stuff)!!!!!!
it should bring the list like this
enter image description here
problem_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/problem_imageView"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="13dp"
android:layout_marginTop="13dp" />
<!--app:srcCompat="#drawable/pest" />-->
<TextView
android:id="#+id/englishName_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/problem_imageView"
android:layout_marginStart="13dp"
android:layout_toEndOf="#+id/problem_imageView"
android:fontFamily="monospace"
android:text="Category English Name"
android:textAppearance="#style/TextAppearance.AppCompat.Medium" />
<TextView
android:id="#+id/amharicName_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/englishName_textView"
android:layout_below="#+id/englishName_textView"
android:layout_marginTop="4dp"
android:fontFamily="monospace"
android:text="Amharic Name"
android:textColor="#000080"
android:textSize="15sp" />
<TextView
android:id="#+id/count_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/amharicName_textView"
android:layout_below="#+id/amharicName_textView"
android:layout_marginTop="8dp"
android:fontFamily="monospace"
android:text="Count"
android:textColor="#000080"
android:textSize="14sp" />
</RelativeLayout>
ProblemAdapter.java
package com.packageName;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ProblemAdapter extends BaseAdapter {
private Context context;
private ArrayList<Integer> listID;
private ArrayList<String> English_Title;
private ArrayList<String> Amharic_Title;
private ArrayList<Integer> count;
public ProblemAdapter(Context context, ArrayList<Integer> listID,
ArrayList<String> name,ArrayList<String> Amharic_Title,ArrayList<Integer>
count) {
this.context = context;
this.listID = listID;
this.English_Title = name;
this.Amharic_Title= Amharic_Title;
this.count = count;
}
#Override
public int getCount() {
return English_Title.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(context, R.layout.problem_list, null);
} else {
ImageView img = convertView.findViewById(R.id.problem_imageView);
TextView txtView_Eng =
convertView.findViewById(R.id.englishName_textView);
//TextView txtView_Amc =
convertView.findViewById(R.id.amharicName_textView);
TextView txtView_Count =
convertView.findViewById(R.id.count_textView);
img.setImageResource(listID.get(position));
txtView_Eng.setText(English_Title.get(position));
txtView_Amc.setText(Amharic_Title.get(position));
txtView_Count.setText(count.get(position));
}
return convertView;
}
}
problem_category.java
package com.packageName;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class problem_category extends AppCompatActivity {
String VegetableCategoryType ;
ListView listView;
ArrayList<Integer> ImageID;
ArrayList<String> English_Title;
ArrayList<String> Amharic_Title;
ArrayList<Integer> count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_problem_category);
// Assigning caller plant to the VegetableCategoryType
Intent intent = getIntent();
VegetableCategoryType = intent.getStringExtra("Plant_Name");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Will be replaced with new action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listView = findViewById(R.id.category_List_view);
ImageID = new ArrayList<>();
English_Title = new ArrayList<>();
Amharic_Title = new ArrayList<>();
count = new ArrayList<>();
ImageID = getImageID();
English_Title = getEnglishName();
Amharic_Title = getAmharicName();
count = getCount();
ProblemAdapter pAdapter = new ProblemAdapter(problem_category.this,
ImageID,English_Title,Amharic_Title,count);
listView.setAdapter(pAdapter);
}
#Override
public void finish(){
super.finish();
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
public ArrayList<String> getEnglishName(){
English_Title= new ArrayList<>();
English_Title.add("Pest");
English_Title.add("Disease");
English_Title.add("Disorder");
return English_Title;
}
private ArrayList<String> getAmharicName() {
Amharic_Title= new ArrayList<>();
Amharic_Title.add("sub-title1");
Amharic_Title.add("sub-title2");
Amharic_Title.add("sub-title3");
return Amharic_Title;
}
public ArrayList<Integer> getImageID(){
ImageID = new ArrayList<>();
ImageID.add(R.drawable.pest);
ImageID.add(R.drawable.disease);
ImageID.add(R.drawable.disorder_edited);
return ImageID;
}
public ArrayList<Integer> getCount(){
count = new ArrayList<>();
if(VegetableCategoryType == "Cabbage"){
count.add(3);
count.add(8);
count.add(3);
}else if (VegetableCategoryType =="Pepper"){
count.add(7);
count.add(5);
count.add(2);
}else if(VegetableCategoryType == "Onion"){
count.add(2);
count.add(5);
count.add(3);
}else if(VegetableCategoryType == "Tomato"){
count.add(8);
count.add(16);
count.add(5);
}
return count;
}
}
MainActivity click_Listners()
public void click_Listeners(){
cabbageImageView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent pCategory = new
Intent(getApplicationContext(),problem_category.class);
pCategory.putExtra("Plant_Name","Cabbage");
startActivity(pCategory);
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
You are not setting the values for the new views created. Your getView body should look like this:
if (convertView == null) {
convertView = View.inflate(context, R.layout.problem_list, null);
} else {
ImageView img = convertView.findViewById(R.id.problem_imageView);
TextView txtView_Eng =
convertView.findViewById(R.id.englishName_textView);
//TextView txtView_Amc =
convertView.findViewById(R.id.amharicName_textView);
TextView txtView_Count =
convertView.findViewById(R.id.count_textView);
img.setImageResource(listID.get(position));
txtView_Eng.setText(English_Title.get(position));
txtView_Amc.setText(Amharic_Title.get(position));
txtView_Count.setText(count.get(position));
}
return convertView;
I have dynamic CheckBoxes and now I want to check which CheckBox clicked or not
AdditionalInformation.Java File Here Simple Adapter is defined :
package com.example.ahmad.cvbuilder21;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AdditionalInformation extends ActionBarActivity {
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_infromation);
cb=(CheckBox)findViewById(R.id.additionalchk);
ABC s = ABC.getSingletonObject();
String[][] str = s.getString();
ListView lv=((ListView)findViewById(R.id.additionallist));
String[] additionalOptions={"Add your Picture","Add Experince / Project","Add Reference","Add Skills / Languages"};
String[] txtViewNames={"options"};
List<HashMap<String,String>>list=new ArrayList<HashMap<String, String>>();
for (int i = 0; i < additionalOptions.length; i++) {
HashMap<String, String> map= new HashMap<String, String>();
map.put("options", additionalOptions[i]);
list.add(map);
}
SimpleAdapter simpleAdpt = new SimpleAdapter(this, list, R.layout.mylayout2,txtViewNames , new int[] {R.id.additionaltxt1});
lv.setAdapter(simpleAdpt);
}
public void additionalData(View view1)
{
if(cb.isChecked())
{
cb.findViewById(R.id.additionalchk).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast toast = Toast.makeText(getApplicationContext(), "Checked",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.show();
}
}
);
}
else{}
}
}
AdditionalInformation.xml file: where additionalData function is called to
check which CheckBox clicked.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Additional Options:"
android:id="#+id/additionalBtn"
/>
<ListView
android:layout_below="#id/additionalBtn"
android:layout_centerHorizontal="true"
android:id="#+id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
<Button
android:layout_below="#id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to CV"
android:onClick="additionalData"
/>
</RelativeLayout>
mylayout2.xml file where I define the controls for simple adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/additionaltxt1"
/>
<CheckBox
android:layout_alignParentRight="true"
android:layout_alignRight="#id/additionaltxt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:id="#+id/additionalchk"
/>
</RelativeLayout>
What you actually need to do is create a custom adapter. In that custom you could listen for checkbox event at the right position.
Here is an example:
public class ListEmployeesAdapter extends BaseAdapter {
public List<Employees> items;
Context c;
public ListEmployeesAdapter(Context c, List<Employees> items) {
this.c = c;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
c.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.employee_item, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(items.get(position).name);
name.setOnCLickListener(new OnClickListener(){
#Override
public void onClick(){
//listen to the click
}
});
return convertView;
}
}
Just replace the the layout with you layout and call checkbox instead of TextView and you are good to go.