I've seen few parts like this in the project I'm working on:
public class ViewHolder extends RecyclerView.ViewHolder {
public PlanJourneyItemLayoutBinding binding;
public ViewHolder(View view) {
super(view);
binding = PlanJourneyItemLayoutBinding.bind(view);
}
}
I'm on MacOS, and if binding is highlighted and Shift+Cmd+B is pressed, Android Studio will show you the content of plan_journey_item_layout.xml, which is the one inflated in onCreateViewHolder(). No problem so far.
Now what if I want to use another XML layout for the viewholder, say plan_other_item_layout.xml? I tried cleaning and rebuilding the project, and couldn't import PlanOtherItemLayoutBinding, for example.
Step 1: Rename the file to something else. Like "plan_other_item.xml"
Step 2: Invalidate Cache & Restart on android studio from "File" -> "Invalidate Caches" -> " Invalidate Cache & Restart. "
Step 3: Rebuild the project. and try to import.
import <YOUR_PACKAGE_NAME>.databinding.PlanOtherItemBinding
dataBinding {
enabled = true
}
To enable the new data binding compiler, add the following option to your gradle.properties file:
android.databinding.enableV2=true
Update:
To enable databinding please use,
android {
...
buildFeatures {
dataBinding true
}
}
Please follow this link: https://developer.android.com/jetpack/androidx/releases/databinding
Sample:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> implements CustomClickListener {
private List<DataModel> dataModelList;
private Context context;
public MyRecyclerViewAdapter(List<DataModel> dataModelList, Context ctx) {
this.dataModelList = dataModelList;
context = ctx;
}
#Override
public MyRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
ItemRowBinding binding = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()),
R.layout.item_row, parent, false);
return new ViewHolder(binding);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
DataModel dataModel = dataModelList.get(position);
holder.bind(dataModel);
holder.itemRowBinding.setItemClickListener(this);
}
#Override
public int getItemCount() {
return dataModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ItemRowBinding itemRowBinding;
public ViewHolder(ItemRowBinding itemRowBinding) {
super(itemRowBinding.getRoot());
this.itemRowBinding = itemRowBinding;
}
public void bind(Object obj) {
itemRowBinding.setVariable(BR.model, obj);
itemRowBinding.executePendingBindings();
}
}
public void cardClicked(DataModel f) {
Toast.makeText(context, "You clicked " + f.androidName,
Toast.LENGTH_LONG).show();
}
}
Update :-
Don't forget to add below code in xml layout which you want to use
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
..
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Related
While implementing MVVM architecture with Data Binding and Live Data run into problem with getting error "cannot find symbol method setUser_list_user_view(User_List_UserViewModel)" I have done many time rebuild, cleanup and other stuff but this error not going..I am doing this first time so not sure have implemented the right method. Below is my code. Thnx in advance for the help
User_List_UserViewModel.java
public class User_List_UserViewModel extends AndroidViewModel {
private User_List_UserRepository mRepository;
private LiveData<List<User>> mAllUser;
public User_List_UserViewModel(Application application) {
super(application);
mRepository = new User_List_UserRepository(application);
mAllUser = mRepository.getmUserlist();
}
LiveData<List<User>> getAllWords() {
return mAllUser;
}
public void insert(User user) {
mRepository.insert(user);
}
}
User_List_UserAdapter.java
public class User_List_UserAdapter extends RecyclerView.Adapter<User_List_UserAdapter.User_List_ViewHolder> {
private LayoutInflater mInflater;
private List<User_List_UserViewModel> user_list_userViewModels;
class User_List_ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private PeopleListItemBinding mBinding;
private TextView mFirst_NameTextView;
public User_List_ViewHolder(PeopleListItemBinding itemBinding) {
super(itemBinding.getRoot());
mBinding = itemBinding;
}
public void bind(User_List_UserViewModel user_list_userViewModel) {
this.mBinding.setUser_list_user_view(user_list_userViewModel);
mBinding.executePendingBindings();
}
public PeopleListItemBinding getPeopleListItemBInding() {
return mBinding;
}
#Override
public void onClick(View v) {
}
}
public User_List_UserAdapter(List<User_List_UserViewModel> newsList) {
this.user_list_userViewModels = newsList;
}
#NonNull
#Override
public User_List_ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (mInflater == null) {
mInflater = LayoutInflater.from(parent.getContext());
}
PeopleListItemBinding peopleListItemBinding = DataBindingUtil.inflate(mInflater, R.layout.people_list_item, parent, false);
return new User_List_ViewHolder(peopleListItemBinding);
}
#Override
public void onBindViewHolder(#NonNull User_List_ViewHolder holder, int position) {
User_List_UserViewModel userViewModel = user_list_userViewModels.get(position);
holder.bind(userViewModel);
}
#Override
public int getItemCount() {
if (user_list_userViewModels != null)
return user_list_userViewModels.size();
else return 0;
}
}
People_List_Fragment.java
public class People_List_Fragment extends Fragment {
List<User_List_UserViewModel> user_list = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
final RecyclerView rv = (RecyclerView) inflater.inflate(
R.layout.people_list, container, false);
rv.setLayoutManager(new LinearLayoutManager(rv.getContext()));
rv.setAdapter(new User_List_UserAdapter(user_list));
return rv;
}
}
welcome to data binding.
You have not shown your layout so I can not see what is variable name, you have taken in your layout. But here is an example, which will explain you trick.
1> Create <variable item of type User_List_UserViewModel in layout.
<layout xmlns:android="http://schemas.android.com/apk/res/android"
>
<data>
<variable
name="item"
type="com.sample.User_List_UserViewModel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--other views-->
</LinearLayout>
</layout>
2> Now you can use setItem(User_List_UserViewModel)
public void bind(User_List_UserViewModel model) {
this.mBinding.setItem(model);
}
Dont use long or confusing variable name
<variable
name="User_List_UserViewModel"
type="com.sample.User_List_UserViewModel"/>
Use short names, easy to use
<variable
name="item"
type="com.sample.User_List_UserViewModel"/>
Suggestions
See java naming convensions https://www.geeksforgeeks.org/java-naming-conventions/
You could make model name just UserModel, why so long name?
You can make UserAdapter, again why a confusing name.
Update
Please see this answer if you classes or variables are not generated. https://stackoverflow.com/a/51579759/6891563
Could able to resolve by removing snacks from setUser_list_user. So it become setUserlistuser. This worked. As a result changed Class name from User_List_User to UserListUser. This will solve the problem. Thanx Khemraj for all the help you extended to me. Will definitely go through naming convention as well. Perhaps you can put my findings as a note in the link that you have provided me to go through. This will help beginers..
I have referred few links regarding this topic but I still couldn't understand how to pass data from a RecyclerView to a Fragment[opening a Fragment on Cardview click]. Following is my RecyclerView class:
public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotosHolder>
{
static class PhotosHolder extends RecyclerView.ViewHolder
{
CardView cv;
ImageView photo_img;
PhotosHolder(final View itemView)
{
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv_photo);
photo_img = (ImageView) itemView.findViewById(R.id.thum_photo);
}
}
private List<PhotoInitialise> photo;
private Activity mContext;
public PhotoAdapter(List<PhotoInitialise> photos, Context mContext)
{
this.photo=photos;
this.mContext= (Activity) mContext;
}
#Override
public PhotosHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.phototab_layout,parent,false);
return new PhotosHolder(layoutView);
}
#Override
public void onBindViewHolder(PhotosHolder holder, final int position)
{
holder.photo_count.setText(photo.get(position).gettotalImages());
holder.cv.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// want to pass the value to a Fragment here and invoke the Fragment
}
});
}
#Override
public int getItemCount()
{
return photo.size();
}
}
This is the XML Layout of the Fragment that should be displayed:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/photo_detail_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/photodetail_description"
android:textSize="20sp"
android:paddingLeft="5dp"
android:layout_marginTop="5dp"
android:paddingRight="5dp">
</RelativeLayout>
I already have an idea of how to pass the value to fragment but I never could able to invoke the layout. Now what should I write in my onClick() to initiate the Fragment Layout ?
Implement interface to handle the click in the specified Fragment.
Sample code structure will be like below. You can customize and use it according to your need:
public InterfaceListItemClickListener{
void listItemClickAction(<parameters to pass>);
}
In your fragment class implement this interface:
public class SampleFragment extends BaseFrgment implements InterfaceListItemClickListener{
#Override
public void listItemClickAction(<parameters to pass>) {
//override the interface function
//handle your click action here
}
//pass the instance of your interface to your adapter like below line
YourAdapter yourAdapter = new YourAdapter(otherParameters, this);
}
In constructor of your Adapter access the interface:
public YourAdapter(otherParameters, InterfaceListItemClickListener clickListenerInferface ){
//other assignations
this.clickListenerInferface = clickListenerInferface;
}
and then onClick callback you can call your onclick function:
clickListenerInferface.listItemClickAction(<parameter to pass>);
I'm working on a simple restaurant POS system, and I had a problem suddenly come up. This problem has only occurred when I run it on a Genymotion tablet device. I do not have this problem on smaller genymotion devices or the 2 physical devices I've tried.
One of my activities uses 5 RecyclerViews to display the menu and sales summary. Every few item clicks, the RecyclerViews decide to just not update and do not properly display my items unless I scroll a bit on ANY of the RecyclerViews or click something. Even though they are not displayed properly, all item clicks register what should be shown (not what is actually shown).
For example, I click beef -> seafood -> chicken. The RecyclerView responsible for showing the menu items still shows seafood. If I click on anything, the correct chicken item gets selected and everything refreshes to what should show up. If I scroll on any RecyclerView (even an unrelated one), everything refreshes properly.
Activity onCreate():
...
cAdapter = new CategoryAdapter();
cAdapter.setOnItemClickListener(new OnItemClickAdapter<Category>() {
#Override
public void onItemClick(Category item, int position) {
miAdapter.setItems(item.getMenuItems());
va1.setDisplayedChild(0);
}
});
miAdapter = new MenuItemAdapter();
miAdapter.setOnItemClickListener(new OnItemClickAdapter<MenuItem>() {
#Override
public void onItemClick(MenuItem item, int position) {
salesOrder.addMenuItem(item);
oeAdapter.notifyDataSetChanged();
updateTotals();
}
});
...
Adapters:
public abstract class ItemRecyclerViewAdapter<T, TVH extends ItemViewHolder<T>> extends RecyclerView.Adapter<TVH> {
private ItemViewHolder.OnItemClickListener<T> listener;
protected List<T> items;
public ItemRecyclerViewAdapter() {
this(new ArrayList<T>());
}
public ItemRecyclerViewAdapter(List<T> items) {
this.items = items;
}
public final void setOnItemClickListener(ItemViewHolder.OnItemClickListener<T> listener) {
this.listener = listener;
}
public void setItems(List<T> items) {
this.items = items;
this.notifyDataSetChanged();
}
public void clear() {
this.items.clear();
this.notifyDataSetChanged();
}
protected abstract TVH createItemViewHolder(ViewGroup parent, int viewType);
#Override
public TVH onCreateViewHolder(ViewGroup parent, int viewType) {
TVH holder = createItemViewHolder(parent, viewType);
holder.setOnItemClickListener(listener);
return holder;
}
#Override
public void onBindViewHolder(TVH holder, int position) {
holder.setItem(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
}
ViewHolders:
public abstract class ItemViewHolder<T> extends RecyclerView.ViewHolder {
public ItemViewHolder(View itemView) {
super(itemView);
}
public interface OnItemClickListener<T> {
void onItemClick(T item, int position);
boolean onItemLongClick(T item, int position);
}
public final void setOnItemClickListener(final OnItemClickListener<T> listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(getItem(), getAdapterPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener(){
#Override
public boolean onLongClick(View v) {
return listener != null && listener.onItemLongClick(getItem(), getAdapterPosition());
}
});
}
public abstract T getItem();
public abstract void setItem(T item);
}
It SEEMS like it's a swapbuffer issue or some race condition I'm not seeing, but I thought I'd see if maybe I'm misunderstanding something first. Any ideas would be much appreciated!
I have that bug too.
After editing my activity_main.xml, I could fix it.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ulimbridge.recylerview.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/recycler"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</android.support.constraint.ConstraintLayout>
Making RecyclerViews' height and width '0dp' was a solution.
I'm trying to figure out how to achieve the same effect of
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
in a RecyclerView implementation. Please help.
There is no built-in support for a "choice mode" structure with RecyclerView. Your options are to either roll it yourself or use a third-party library that offers it.
The DynamicRecyclerView library offers choice modes, but I have not tried it.
This sample app demonstrates implementing it yourself, in this case using the activated state to indicate which is the current choice. The overall pattern is:
Have your RecyclerView.ViewHolder detect a UI operation that indicates a choice (click on a row? click on a RadioButton in the row? etc.).
Keep track of the selection at the level of your RecyclerView.Adapter. In my case, a ChoiceCapableAdapter handles that, in conjunction with a SingleChoiceMode class that implements a ChoiceMode strategy.
When a choice is made, update the newly-chosen row to reflect the choice and update the previously-chosen row to reflect that it is no longer chosen. findViewHolderForPosition() on RecyclerView can help here -- if you track the position of the last choice, findViewHolderForPosition() can give you the ViewHolder for that choice, so you can "un-choose" it.
Keep track of the choice across configuration changes, by putting it in the saved instance state of the activity or fragment that is managing the RecyclerView.
I've created a library for this kind of choice mode applied to the RecyclerView, maybe it can help:
Description
This library has been created to help the integration of a multi-choice selection to the RecyclerView
Implementation
The integration with Gradle is very easy, you just need the jcenter repository and the library:
repositories {
jcenter()
}
...
dependencies {
compile 'com.davidecirillo.multichoicerecyclerview:multichoicerecyclerview:1.0.1'
}
Main steps for usage
Add the MultiChoiceRecyclerView to your xml file
<com.davidecirillo.multichoicesample.MultiChoiceRecyclerView
android:id="#+id/multiChoiceRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Instanciate you object and connect the view
MultiChoiceRecyclerView mMultiChoiceRecyclerView = (MultiChoiceRecyclerView) findViewById(R.id.multiChoiceRecyclerView);
Extend you adapter to the MultiChoiceAdapter and add it to the RecyclerView as per normal usage
public class MyAdapter extends MultiChoiceAdapter<MyViewHolder> {
public MyAdapter(ArrayList<String> stringList, Context context) {
this.mList = stringList;
this.mContext = context;
}
...
}
MyAdapter myAdapter = new MyAdapter(mList, getApplicationContext());
mMultiChoiceRecyclerView.setAdapter(myAdapter);
For more information and customisations:
https://github.com/dvdciri/MultiChoiceRecyclerView
You can follow this:
– Data (String name, boolean selected)
– Adapter with itemClickListener
– Activity or fragment
– activity_main (recyclerView)
– list_item (TextView, CheckBox)
Data
public class MultipleData {
private String mTitle;
private boolean mBoolean;
public MultipleData(String title, boolean mBoolean) {
this.mTitle = title;
this.mBoolean = mBoolean;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public boolean isBoolean() {
return mBoolean;
}
public void setBoolean(boolean mBoolean) {
this.mBoolean = mBoolean;
}
}
Your views activity_main.xml (recyclerView)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.thedeveloperworldisyours.fullrecycleview.multiple.MultipleFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/multiple_fragment_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
and list_item.xml (TextView, CheckBox)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/multiple_list_item_text"
android:layout_width="match_parent"
android:layout_height="90dp"
android:text="#string/app_name"
android:typeface="monospace"
android:layout_toLeftOf="#+id/multiple_list_item_check_button"
android:gravity="center"
android:textSize="#dimen/multiple_list_item_size_rock_stars"/>
<RadioButton
android:id="#+id/multiple_list_item_check_button"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:layout_alignParentRight="true"
android:checked="false"
android:clickable="false"
android:focusable="false" />
</RelativeLayout>
Adapter with ClickListener
public class MultipleRecyclerViewAdapter extends RecyclerView
.Adapter<MultipleRecyclerViewAdapter
.DataObjectHolder> {
private List<MultipleData> mList;
private static MultipleClickListener sClickListener;
MultipleRecyclerViewAdapter(List<MultipleData> mList) {
this.mList = mList;
}
static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView mTextView;
RadioButton mRadioButton;
DataObjectHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.multiple_list_item_text);
mRadioButton = (RadioButton) itemView.findViewById(R.id.multiple_list_item_check_button);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
sClickListener.onItemClick(getAdapterPosition(), v);
}
}
void changedData(int position) {
if (mList.get(position).isBoolean()) {
mList.get(position).setBoolean(false);
} else {
mList.get(position).setBoolean(true);
}
notifyDataSetChanged();
}
void setOnItemClickListener(MultipleClickListener myClickListener) {
this.sClickListener = myClickListener;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.multiple_list_item, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.mTextView.setText(mList.get(position).getTitle());
holder.mRadioButton.setChecked(mList.get(position).isBoolean());
}
#Override
public int getItemCount() {
return mList.size();
}
interface MultipleClickListener {
void onItemClick(int position, View v);
}
}
Activity or fragment
public class MultipleFragment extends Fragment implements MultipleRecyclerViewAdapter.MultipleClickListener{
MultipleRecyclerViewAdapter mAdapter;
public MultipleFragment() {
// Required empty public constructor
}
public static MultipleFragment newInstance() {
return new MultipleFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.multiple_fragment, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.multiple_fragment_recycler_view);
MultipleData hendrix = new MultipleData("Jimi Hendrix", false);
MultipleData bowie = new MultipleData("David Bowie", false);
MultipleData morrison = new MultipleData("Jim Morrison", false);
MultipleData presley = new MultipleData("Elvis Presley", false);
MultipleData jagger = new MultipleData("Mick Jagger", false);
MultipleData cobain = new MultipleData("Kurt Cobain", false);
MultipleData dylan = new MultipleData("Bob Dylan", false);
MultipleData lennon = new MultipleData("John Lennon", false);
MultipleData mercury = new MultipleData("Freddie Mercury", false);
MultipleData elton = new MultipleData("Elton John", false);
MultipleData clapton = new MultipleData("Eric Clapton", false);
List<MultipleData> list = new ArrayList<>();
list.add(0, hendrix);
list.add(1, bowie);
list.add(2, morrison);
list.add(3, presley);
list.add(4, jagger);
list.add(5, cobain);
list.add(6, dylan);
list.add(7, lennon);
list.add(8, mercury);
list.add(9, elton);
list.add(10, clapton);
mAdapter = new MultipleRecyclerViewAdapter(list);
recyclerView.setAdapter(mAdapter);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
mAdapter.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(int position, View v) {
mAdapter.changedData(position);
}
}
You can see this example in GitHub and this post for multiple choice, and this post for single choice Happy code!!!
I have this in the onCreate method as follows:
ListView lv = (ListView)findViewById(android.R.id.list);
adapter = new ModuleAdapter(this);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
Then later in the code:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Log.v(TAG, "clicked");
}
OnItemClickListener is being implemented.
I'm trying to fire a new activity from onItemClick but it does not appear to be working.
New to Android and don't know a lot of java. Can anyone help? Thanks.
Do you set FocusableInTouchMode to be true in your layout? If so then onItemClick will not be called.
Try this changes in the xxx_row.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:enabled="false">
</TextView>
At least for me it worked when i changed the width and enabled attributes.
ListView lv = (ListView)findViewById(android.R.id.list);
It's if you trying to get android System resources, but you want listview which you describe on xml layout.
Let's say it's look like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
so you need change your code to
ListView lv = (ListView)findViewById(R.id.listView1);
Some explain:
android.R - it's default resources of Android OS - llike
buttons,images, listview items layouts and etc.
R - it' your project resoures full path likes [your package path].R
for example: com.example.R
I am not sure if what you are trying to do is intentional. You are setting click listener on the whole list view container. I believe you wanted to set a click listener for the items inside. I will give you an example below, but also please note that I am extending RecyclerView here instead of using ListView which is rather obsolete.
Java version:
public class ModuleAdapter2 extends RecyclerView.Adapter<ModuleAdapter2.ItemViewHolder> {
private final List<Item> items;
private final ModuleAdapterListener listener;
public ModuleAdapter2(List<Item> items, ModuleAdapterListener listener) {
this.items = items;
this.listener = listener;
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
public ItemModuleBinding binding;
public ItemViewHolder(ItemModuleBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
ItemModuleBinding binding = ItemModuleBinding.inflate(inflater, parent, false);
return new ItemViewHolder(binding);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
Item item = items.get(position);
holder.binding.getRoot().setOnClickListener(v -> listener.onItemClicked(item));
}
#Override
public int getItemCount() {
return items.size();
}
interface ModuleAdapterListener {
void onItemClicked(Item item);
}}
Kotlin version:
class ModuleAdapter(var items: MutableList<Item>, private val listener: ModuleAdapterListener) : RecyclerView.Adapter<ModuleAdapter.ItemViewHolder>() {
inner class ItemViewHolder(val binding: ItemModuleBinding) : RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemModuleBinding.inflate(inflater, parent, false)
return ItemViewHolder(binding)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
holder.binding.root.setOnClickListener {
listener.onItemClicked(items[position])
}
}
override fun getItemCount(): Int {
return items.size
}
interface ModuleAdapterListener {
fun onItemClicked(item: Item)
}}
If by any chance you wanted to use the click listener for the container, the reason why it is not working for you, is that the container is consuming the click within the onTouch method (and that is why you are not getting your onClick events). If you would like to overcome this, find some good solutions in both Java and Kotlin here: setOnClickListener for recyclerView not working