Update Listview in android - android

I am trying to create an activity where the user can create some recipe and input the ingredients. every time the user enters an ingredient, it should be added to a listview. The issue I am having here is that the first input is the only one that is added to the listview not the others.
Here is the layout script:
<?xml version="1.0" encoding="utf-8"?><ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.AddActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="226dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:orientation="vertical">
<EditText
android:id="#+id/Name_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/recipe_name" />
<EditText
android:id="#+id/ServingsNbr_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/number_of_servings" />
<EditText
android:id="#+id/PrepTime_Et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/preparation_time" />
<EditText
android:id="#+id/Calories_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/calories" />
</LinearLayout>
<LinearLayout
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="36dp"
android:text="#string/ingredients"
android:textSize="26sp"
android:textAlignment="center"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/new_ing"
android:layout_width="0dp"
android:layout_weight="9"
android:layout_height="36dp" />
<ImageView
android:id="#+id/add_ingredient_btn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="36dp"
android:src="#drawable/round_add_circle_outline_black_36dp"/>
</LinearLayout>
<ListView
android:id="#+id/ingredient_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
</LinearLayout>
And the logic behind it :
public class AddActivity extends AppCompatActivity {
private ListView added_ing;
private IngredientAdapter adapter;
private ArrayList<String> ingredients = new ArrayList<String>();
private EditText new_ing;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
adapter = new IngredientAdapter(AddActivity.this,ingredients);
added_ing = findViewById(R.id.ingredient_list);
added_ing.setAdapter(adapter);
new_ing = findViewById(R.id.new_ing);
ImageView add_ingredien = findViewById(R.id.add_ingredient_btn);
add_ingredien.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ingredients.add(new_ing.getText().toString());
Toast.makeText(AddActivity.this, new_ing.getText().toString(), Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
});
}
public class IngredientAdapter extends ArrayAdapter<String> {
ArrayList<String> mNewIngredients;
public IngredientAdapter(Context context, ArrayList<String> objects) {
super(context, 0, objects);
mNewIngredients = objects;
}
public String getItem(int position) {
return mNewIngredients.get(position).toString();
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
if(convertView==null)
convertView = LayoutInflater.from(getContext()).inflate(R.layout.ingredient,parent,false);
TextView recipeName= convertView.findViewById(R.id.new_added_ingredient);
recipeName.setText(item);
return convertView;
}
}
}

Try to scroll down your list view, maybe in your item's layout, you set the layout_height = match_parent so you do not see the other inputs.

You need to add android:fillViewport="true" to your ScrollView
Also change all child LinearLayout height to wrap_content instead of match_parent
Try this
<?xml version="1.0" encoding="utf-8"?><ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:fillViewport="true"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="226dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="vertical">
<EditText
android:id="#+id/Name_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/app_name" />
<EditText
android:id="#+id/ServingsNbr_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/app_name" />
<EditText
android:id="#+id/PrepTime_Et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/app_name" />
<EditText
android:id="#+id/Calories_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="36dp"
android:text="#string/app_name"
android:textSize="26sp"
android:textAlignment="center"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/new_ing"
android:layout_width="0dp"
android:layout_weight="9"
android:layout_height="36dp" />
<ImageView
android:id="#+id/add_ingredient_btn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="36dp"
android:src="#drawable/ic_launcher_background"/>
</LinearLayout>
<ListView
android:id="#+id/ingredient_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
</LinearLayout>
</ScrollView>

In your implementation of IngredientAdapter, you are using your own ArrayList mNewIngredients for the data instead of the collection in the ArrayAdapter. When you add new data into ingredients, it is not added to the adapter.
To make use of the collection implemented in ArrayAdapter for simplicity. The following is an example, with a view holder so that views can be reused.
public class IngredientAdapter extends ArrayAdapter<String> {
public IngredientAdapter(Context context, ArrayList<String> objects) {
super(context, 0, objects);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView==null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.ingredient, parent, false);
holder = new ViewHolder();
holder.recipeName = convertView.findViewById(R.id.new_added_ingredient);
convertView.Tag = holder;
} else {
holder = (ViewHolder)convertView.Tag;
}
String item = getItem(position);
holder.recipeName.setText(item);
return convertView;
}
}
public class ViewHolder {
public TextView recipeName;
}
The data in the adapter is now backed by the internal collection. And in the activity, you should add the new data into adapter directly.
public class AddActivity extends AppCompatActivity {
private ListView added_ing;
private IngredientAdapter adapter;
// keep this if you need it for something else
// private ArrayList<String> ingredients = new ArrayList<String>();
private EditText new_ing;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
adapter = new IngredientAdapter(AddActivity.this,ingredients);
added_ing = findViewById(R.id.ingredient_list);
added_ing.setAdapter(adapter);
new_ing = findViewById(R.id.new_ing);
ImageView add_ingredien = findViewById(R.id.add_ingredient_btn);
add_ingredien.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// keep this if you need it for something else
// ingredients.add(new_ing.getText().toString());
// to add adata into the adapter
adapter.Add(new_ing.getText().toString());
Toast.makeText(AddActivity.this, new_ing.getText().toString(), Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
});
}
}

Related

Cannot click on item's view inside RecyclerView

I want to show a popup menu for each item of a RecyclerView when a button is clicked.
My Adapter:
public class SearchResultRecyclerViewAdapter extends RecyclerView.Adapter<SearchResultRecyclerViewAdapter.ViewHolder> {
public SearchResultRecyclerViewAdapter(ArrayList<BookModel> bookModels, Context context) {
this.bookModels = bookModels;
this.context = context;
}
ArrayList<BookModel> bookModels;
Context context;
#NonNull
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("aa", bookModels.get(position).getThumbnailLink());
Glide.with(context)
.asBitmap()
.load(bookModels.get(position).getThumbnailLink())
.into(holder.coverImage);
holder.name.setText(bookModels.get(position).getName());
holder.author.setText(bookModels.get(position).getAuthor());
holder.category.setText(bookModels.get(position).getCategories().toString());
holder.maturity.setText(bookModels.get(position).getMaturityRating());
holder.desc.setText(bookModels.get(position).getDesc());
holder.option.setOnClickListener(new View.OnClickListener() { ///////////// here
#Override
public void onClick(View v) {
//show popup
Log.d("ItemOption","Clicked");
}
});
if (position+1 == bookModels.size()){
holder.divider.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return bookModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
RoundedImageView coverImage;
TextView name;
TextView author;
TextView desc;
TextView category;
TextView maturity;
ImageView divider;
Button option;
RelativeLayout root;
public ViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
coverImage = itemView.findViewById(R.id.cover_book_item_imageview);
name = itemView.findViewById(R.id.name_book_item_textview);
author = itemView.findViewById(R.id.author_book_item_textview);
desc = itemView.findViewById(R.id.desc_book_item_textview);
category = itemView.findViewById(R.id.category_book_item_textview);
maturity = itemView.findViewById(R.id.maturity_book_item_textview);
divider = itemView.findViewById(R.id.divider_book_item_imageview);
option = itemView.findViewById(R.id.option_book_item_button);
root = itemView.findViewById(R.id.root);
}
}
}
My item Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/cover_book_item_cardview"
android:layout_width="#dimen/_81sdp"
android:layout_height="#dimen/_124sdp"
android:layout_margin="#dimen/_15sdp"
app:cardCornerRadius="#dimen/_8sdp"
android:elevation="#dimen/_5sdp">
<com.makeramen.roundedimageview.RoundedImageView
android:id="#+id/cover_book_item_imageview"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:src="#drawable/testcover"
android:scaleType="fitXY"
app:riv_corner_radius="#dimen/_5sdp"/>
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/name_book_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:layout_marginTop="#dimen/_20sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:textSize="#dimen/_18sdp"
android:textColor="#color/light_black"
/>
<TextView
android:id="#+id/author_book_item_textview"
android:textSize="#dimen/_13sdp"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:layout_marginTop="#dimen/_1sdp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name_book_item_textview"
android:text="author"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp"/>
<TextView
android:id="#+id/desc_book_item_textview"
android:layout_width="#dimen/_190sdp"
android:layout_height="#dimen/_40sdp"
android:layout_below="#id/name_book_item_textview"
android:width="#dimen/_60sdp"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp"
android:layout_marginTop="#dimen/_30sdp"
android:textColor="#color/light_black"
android:text="desc"
android:fontFamily="#font/yanonekaffeesatz_medium"/>
<LinearLayout
android:id="#+id/holder_book_item_linearlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/name_book_item_textview"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp">
<TextView
android:id="#+id/category_book_item_textview"
android:textColor="#color/white"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:background="#drawable/rounded_rectangle_90"
android:backgroundTint="#color/yellow"
android:padding="#dimen/_3sdp"
android:layout_marginTop="#dimen/_72sdp"
android:text="category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/maturity_book_item_textview"
android:textColor="#color/white"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:background="#drawable/rounded_rectangle_90"
android:backgroundTint="#color/light_black"
android:padding="#dimen/_3sdp"
android:layout_marginTop="#dimen/_72sdp"
android:text="maturity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_5sdp"/>
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/option_book_item_button"
android:layout_width="#dimen/_20sdp"
android:layout_height="#dimen/_20sdp"
android:background="#drawable/ic_more"
android:backgroundTint="#color/light_black"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_260sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_260sdp"
android:layout_marginTop="#dimen/_23sdp"/>
<ImageView
android:id="#+id/divider_book_item_imageview"
android:layout_width="#dimen/_200sdp"
android:layout_height="1dp"
android:background="#DFDFDF"
android:layout_below="#id/holder_book_item_linearlayout"
android:layout_marginTop="#dimen/_15sdp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Initializing RecyclerView:
recyclerView = findViewById(R.id.search_result_recyclerview);
recyclerView.scheduleLayoutAnimation();
recyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("CheckRecyclerView","clicked");
}
});
searchResultRecyclerViewAdapter = new SearchResultRecyclerViewAdapter(bookModels,SearchActivity.this);
recyclerView.setAdapter(searchResultRecyclerViewAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
}
XML Layout of Activity:
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawerlayout"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:layout_width="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:gravity="center"
android:animateLayoutChanges="true"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--
Views
-->
<androidx.recyclerview.widget.RecyclerView
android:layout_centerHorizontal="true"
android:layout_below="#id/appbar_cardview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/search_result_recyclerview"
android:layoutAnimation="#anim/search_result_recyclerview_anim"
android:visibility="gone"/> <!-- will become visible later-->
<!--
Views
-->
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
app:itemTextColor="#color/white"
app:itemIconTint="#color/white"
android:background="#color/black"
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu_main" />
</androidx.drawerlayout.widget.DrawerLayout>
when the item's view is clicked nothing happens. I've done the same exact thing before with no problem I don't know what I'm missing here.
EDIT:
as #anemomylos mentioned this might be a click issue. in this layout there is a lot of Views that will be Gone in order to RecyclerView shows up. RecyclerViews don't register any clicks themselves so I'm not sure if it's being blocked by another view or not, is there any way to know what is blocking the click? I don't have any android:clickable="true" and I made sure that all Views before RecyclerView are Gone and not Invisible

Why Custom ArrayAdapter not showing TextView in a ListView

I have made a custom ArrayAdapter and tried to add the another TextView "Breed" of the animals, but when i execute the program , its not showing the Breed. Where am i doing wrong ? I am scratching my head since long. please help where is the mistake ?
MainActivity.Java
public class MainActivity extends AppCompatActivity {
ListView simpleList;
ArrayList<Item> animalList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.simpleListView);
animalList.add(new Item("Lion",R.drawable.lion,"Khatarnak"));
animalList.add(new Item("Tiger",R.drawable.tiger,"Fudu"));
animalList.add(new Item("Monkey",R.drawable.monkey,"Lallu"));
animalList.add(new Item("Elephant",R.drawable.elephant,"Jabardast"));
animalList.add(new Item("Dog",R.drawable.dog,"ItemDog"));
animalList.add(new Item("Cat",R.drawable.cat,"MeeMee"));
MyAdapter myAdapter=new MyAdapter(this,R.layout.list_view_items,animalList);
simpleList.setAdapter(myAdapter);
}
}
MyAdapter.Java
public class MyAdapter extends ArrayAdapter<Item> {
ArrayList<Item> animalList = new ArrayList<>();
public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
super(context, textViewResourceId, objects);
animalList = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_view_items, null);
TextView textView = (TextView) v.findViewById(R.id.textView);
ImageView imageView = (ImageView) v.findViewById(R.id.imageView);
TextView breedView = (TextView)v.findViewById(R.id.breed);
textView.setText(animalList.get(position).getAnimalName());
imageView.setImageResource(animalList.get(position).getAnimalImage());
breedView.setText(animalList.get(position).getBreed());
return v;
}
}
Item.Java
public class Item {
String animalName;
int animalImage;
String breedName;
public String getBreed() {
return breedName;
}
public void setBreed(String breed) {
this.breedName = breedName;
}
public Item(String animalName,int animalImage,String breedName)
{
this.animalImage=animalImage;
this.animalName=animalName;
this.breedName = breedName;
}
public String getAnimalName()
{
return animalName;
}
public int getAnimalImage()
{
return animalImage;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="2dp"/>
</RelativeLayout>
list_view_items.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="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp" />
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Demo"
android:textColor="#000" />
<TextView
android:id="#+id/breed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Breed"
android:textColor="#000" />
</LinearLayout>
This is most likely a problem with the linear layout for each item. The orientation is horizontal, which lays each view one after the other horizontally. The problem is that the text view for the animal type has a width of fill_parent leaving no space for the breed view. If you change it to wrap_content it'll probably work for some of the cases, but might not work with everything.
In any case I think this is a problem with the views' positions and sizes. Try and move them around. Perhaps even a simple change would be placing them vertically:
<?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="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Demo"
android:textColor="#000" />
<TextView
android:id="#+id/breed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Breed"
android:textColor="#000" />
</LinearLayout>
</LinearLayout>
There's perhaps a more efficient way of doing this, but this is just an example. The inner linear layout places one text view on to of the other.
PS: your getCount method is not really doing anything. You can remove it.
replace your layout with my code your issue will resolve.
<?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="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp" />
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:text="Demo"
android:textColor="#000" />
<TextView
android:id="#+id/breed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Breed"
android:textColor="#000" />
</LinearLayout>

How to handle "ReadMore" Button click present in my List

BusinessForSaleActivity
public class BusinessForSaleActivity extends AppCompatActivity {
DatabaseReference databaseLinks;
ListView listViewBusinessForSale;
Button readMore;
ArrayList<BusinessForSale> list;
//CardView cardView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_for_sale);
listViewBusinessForSale = (ListView)findViewById(R.id.ListViewBusinessForSale);
list = new ArrayList<>();
databaseLinks = FirebaseDatabase.getInstance().getReference("BusinessList");
databaseLinks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
try{
for(DataSnapshot businessSnapshot : dataSnapshot.getChildren()){
BusinessForSale b = businessSnapshot.getValue(BusinessForSale.class);
list.add(b);
}
}
catch (Exception ex){
Log.e("Error Descr:",ex.getMessage());
}
BusinessForSaleList adapter=new BusinessForSaleList(BusinessForSaleActivity.this,list);
listViewBusinessForSale.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(BusinessForSaleActivity.this,"Something is wrong",Toast.LENGTH_SHORT).show();
}
});
}
}
BusinessForSaleList================(Adapter class)============
public class BusinessForSaleList extends ArrayAdapter<BusinessForSale> {
private Activity context;
private List<BusinessForSale> businessForSaleList;
public BusinessForSaleList(Activity context,List<BusinessForSale> businessForSaleList){
//super(context,R.layout.list_layout,businessForSaleList);
super(context,R.layout.list,businessForSaleList);
this.context=context;
this.businessForSaleList=businessForSaleList;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View listViewItem=inflater.inflate(R.layout.list,null,true);
ImageView imgBuiness=(ImageView)listViewItem.findViewById(R.id.imgViewBusiness);
TextView txtTitle = (TextView)listViewItem.findViewById(R.id.txtViewTitle);
TextView txtType = (TextView)listViewItem.findViewById(R.id.txtViewType);
TextView txtDescr = (TextView)listViewItem.findViewById(R.id.txtViewDescr);
Button btnReadMore = (Button)convertView.findViewById(R.id.buttonReadMore);
BusinessForSale businessForSale = businessForSaleList.get(position);
Picasso.get().load(businessForSale.getImage().toString()).into(imgBuiness);
txtTitle.setText(businessForSale.getBusiness_Title());
txtType.setText(businessForSale.getBusiness_Type());
txtDescr.setText(businessForSale.getDescription());
return listViewItem;
}
}
BusinessForSaleActivity.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="match_parent"
tools:context=".BusinessForSaleActivity">
<ListView
android:id="#+id/ListViewBusinessForSale"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
/>
</RelativeLayout>
List.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="match_parent"
android:background="#e0e0e0">
<android.support.v7.widget.CardView
android:id="#+id/cardBusinessForSale"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="4dp">
<LinearLayout
android:id="#+id/L1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imgViewBusiness"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_margin="4dp"
android:scaleType="centerCrop"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/txtViewTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginBottom="8dp"
android:textColor="#000"
android:textSize="18sp"/>
<TextView
android:id="#+id/txtViewType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#555" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/txtViewDescr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:maxLines="3"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<Button
android:id="#+id/buttonReadMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="#style/PrimaryFlatButton"
android:text="Read More" />
<Button
android:id="#+id/buttonAddToFvrt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="#style/PrimaryFlatButton"
android:text="Add to Favorites" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>][1]
I want to redirect to new Activity on "ReadMore" button click. I am fetching firebase data into a listview using list.xml layout.
When you're using a list and need to handle click on an item or an element contained by it, the common way is to set a listener in the getView() method or onBind() method, depending on the adepter you're using.
In this case, in your "getView()" method, after referenced your button you need to set a listener on it that retrieve the position of the item that contains it and open the relative activity (or the unique activity setting up the correct value). You can do it by retrieving the parent position of its parent, but it's sounds so complicated.
The best and common way is to assign to the button a tag that is the position assigned to its parent by the getView() method in this way:
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View listViewItem=inflater.inflate(R.layout.list,null,true);
...
Button btnReadMore = (Button)convertView.findViewById(R.id.buttonReadMore);
btnReadMore.setTag(position + "");
}
After that, every button contains the position of the item in the list. Now, assign the listener to the button and retrieve the correct position:
btnReadMore.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view,....){
Button btnReadMore = (Button) view; //This cast is unless, it's here only for more understanding
String positionString = btnReadMore.getTag();
int position = Integer.parseInt(positionString);
BusinessForSale correctItem = BusinessForSaleList.get(position);
//here start activity you need.
}});
Hope this help! :D

ListView OnItemClickListener is not listening

I checked all the previous questions regarding this issue , but none of them are helpfull to me .
My listview is not responding , i tried changing this
list.setOnItemClickListener(new ContactsListItemClickListener(this));
to
list.setOnItemClickListener(this);
by making my PrioritiseContacts activity just imeplement OnItemClickListener , but then too its not working .
The activity is successfully running , but i am unable to listen for listclick events.
How to correct this?
Here is my class :
public class PrioritiseContacts extends Activity implements OnClickListener {
private ListView list;
// list of contacts with name
private List<Contacts> contactsList;
private Controller controll;
private ContactListAdapters adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_contacts);
controll = new Controller();
contactsList = controll.fetchContacts(this);
// call the adapter to set the list view layout
adapter = new ContactListAdapters(contactsList, this);
list = (ListView) findViewById(R.id.lv_contacts);
// set the adapter to list
list.setAdapter(adapter);
list.setOnItemClickListener(new ContactsListItemClickListener(this));
// inflate the list of contact
}
#Override
public void onClick(View arg0) {
Toast.makeText(this, "clicked", 1000).show();
}
class ContactsListItemClickListener implements OnItemClickListener {
private Context c;
public ContactsListItemClickListener(
PrioritiseContacts prioritiseContacts) {
this.c = prioritiseContacts;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(c, "Clicked", 1500).show();
System.out.print("clicked");
}
}
}
My select_contacts 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:background="#000000"
android:orientation="vertical">
<TextView
android:id="#+id/tv_select_contacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Choose Contacts"
android:textColor="#fdfdfd"
android:textSize="30dip"
android:gravity="center" >
</TextView>
<ListView
android:id="#+id/lv_contacts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:cacheColorHint="#00000000"
android:clickable="true"
android:focusable="true"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:scrollbars="none" >
</ListView>
</LinearLayout>
And this is my adapter's getview() :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// layout infklater to inflate the post list view
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = inflater.inflate(R.layout.contacts_list_view, null);
}
Contacts c = contactList.get(position);
// set text views in contact lists
// Typeface custom_font =
// Typeface.createFromAsset(context.getAssets(),"fonts/calibril.ttf");
TextView name = (TextView) view.findViewById(R.id.tv_contact_name);
// date.setTypeface(custom_font);
name.setText(c.getName());
TextView number = (TextView) view.findViewById(R.id.tv_number);
// title.setTypeface(custom_font);
number.setText(c.getPhone());
ImageView contact_image = (ImageView) view.findViewById(R.id.iv_single_contact);
// hut.setTypeface(custom_font);
if(c.getContactImage() != null)
contact_image.setImageBitmap(c.getContactImage());
else
contact_image.setImageDrawable(view.getResources().getDrawable(R.drawable.ic_contact_picture_2));
return view;
}
My contacts_list_view xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl_post_list"
android:layout_width="match_parent"
android:layout_height="50dip"
android:background="#000000"
android:gravity="left"
android:orientation="horizontal"
android:paddingBottom="2dp"
android:paddingTop="2dp" >
<ImageView
android:id="#+id/iv_single_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.87"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:gravity="left"
android:paddingLeft="2dp"
android:text="Contact Name"
android:textColor="#fdfbfb"
android:textStyle="bold" />
<View style="#style/Divider" />
<TextView
android:id="#+id/tv_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-thin"
android:gravity="left"
android:text="this is number"
android:textColor="#fdfbfb"
android:textSize="10dp"
android:textStyle="bold" />
</LinearLayout>
<CheckBox
android:id="#+id/cb_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
</LinearLayout>
If any row item of list contains focusable or clickable view then OnItemClickListener won't work such as for checkbox or button etc in the row item.There are two solution:
1. row item must be having param like android:descendantFocusability="blocksDescendants"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>
2. Set given two attributes to false
like
android:focusable="false"
android:focusableInTouchMode="false"
For example if there is any checkbox or button or image in the row item then
<CheckBox
android:id="#+id/fav_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />

ListView Item not clickable when I display ad's with PublisherAdView inside the Item [duplicate]

I checked all the previous questions regarding this issue , but none of them are helpfull to me .
My listview is not responding , i tried changing this
list.setOnItemClickListener(new ContactsListItemClickListener(this));
to
list.setOnItemClickListener(this);
by making my PrioritiseContacts activity just imeplement OnItemClickListener , but then too its not working .
The activity is successfully running , but i am unable to listen for listclick events.
How to correct this?
Here is my class :
public class PrioritiseContacts extends Activity implements OnClickListener {
private ListView list;
// list of contacts with name
private List<Contacts> contactsList;
private Controller controll;
private ContactListAdapters adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_contacts);
controll = new Controller();
contactsList = controll.fetchContacts(this);
// call the adapter to set the list view layout
adapter = new ContactListAdapters(contactsList, this);
list = (ListView) findViewById(R.id.lv_contacts);
// set the adapter to list
list.setAdapter(adapter);
list.setOnItemClickListener(new ContactsListItemClickListener(this));
// inflate the list of contact
}
#Override
public void onClick(View arg0) {
Toast.makeText(this, "clicked", 1000).show();
}
class ContactsListItemClickListener implements OnItemClickListener {
private Context c;
public ContactsListItemClickListener(
PrioritiseContacts prioritiseContacts) {
this.c = prioritiseContacts;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(c, "Clicked", 1500).show();
System.out.print("clicked");
}
}
}
My select_contacts 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:background="#000000"
android:orientation="vertical">
<TextView
android:id="#+id/tv_select_contacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Choose Contacts"
android:textColor="#fdfdfd"
android:textSize="30dip"
android:gravity="center" >
</TextView>
<ListView
android:id="#+id/lv_contacts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:cacheColorHint="#00000000"
android:clickable="true"
android:focusable="true"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:scrollbars="none" >
</ListView>
</LinearLayout>
And this is my adapter's getview() :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// layout infklater to inflate the post list view
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = inflater.inflate(R.layout.contacts_list_view, null);
}
Contacts c = contactList.get(position);
// set text views in contact lists
// Typeface custom_font =
// Typeface.createFromAsset(context.getAssets(),"fonts/calibril.ttf");
TextView name = (TextView) view.findViewById(R.id.tv_contact_name);
// date.setTypeface(custom_font);
name.setText(c.getName());
TextView number = (TextView) view.findViewById(R.id.tv_number);
// title.setTypeface(custom_font);
number.setText(c.getPhone());
ImageView contact_image = (ImageView) view.findViewById(R.id.iv_single_contact);
// hut.setTypeface(custom_font);
if(c.getContactImage() != null)
contact_image.setImageBitmap(c.getContactImage());
else
contact_image.setImageDrawable(view.getResources().getDrawable(R.drawable.ic_contact_picture_2));
return view;
}
My contacts_list_view xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl_post_list"
android:layout_width="match_parent"
android:layout_height="50dip"
android:background="#000000"
android:gravity="left"
android:orientation="horizontal"
android:paddingBottom="2dp"
android:paddingTop="2dp" >
<ImageView
android:id="#+id/iv_single_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.87"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:gravity="left"
android:paddingLeft="2dp"
android:text="Contact Name"
android:textColor="#fdfbfb"
android:textStyle="bold" />
<View style="#style/Divider" />
<TextView
android:id="#+id/tv_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-thin"
android:gravity="left"
android:text="this is number"
android:textColor="#fdfbfb"
android:textSize="10dp"
android:textStyle="bold" />
</LinearLayout>
<CheckBox
android:id="#+id/cb_contact"
android:layout_width="70dp"
android:layout_height="fill_parent"
android:layout_weight="0.05"
android:padding="2dp" />
</LinearLayout>
If any row item of list contains focusable or clickable view then OnItemClickListener won't work such as for checkbox or button etc in the row item.There are two solution:
1. row item must be having param like android:descendantFocusability="blocksDescendants"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>
2. Set given two attributes to false
like
android:focusable="false"
android:focusableInTouchMode="false"
For example if there is any checkbox or button or image in the row item then
<CheckBox
android:id="#+id/fav_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />

Categories

Resources