I am using listviews instead of button in my application. I want to set OnClickListener() on listview instead of setOnItemClickListener(). here is my code:
listview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), BillingActivity1.class));
}
});
can someone suggest a method to do OnClickListener()?
thank you
Ok, I understood your problem.
Lets analyze cases:
If your ListView
has some items, the good approach is to set anyway an onItemClickListener
and, based on which item has been clicked, do something. You can also do the same thing for each item without considering which item has been pressed, but this is still the best approach.
the list view will be hidden when there is no data to display.
ListView
(usually) has the height
set to wrap_content
, so even setting the onClickListener
on an empty list won't work since the list will result having height of 0, being not able to be clicked (you can't click a view with no height
since it is not visible).
If, as it looks like, you need to do some stuffs on your ListView
even if it's empty, just add a Button or a FloatingActionButton
to your Activity
and then use those: you can both keep the button in any case (like an "Add item" Button) or you can make it visible only if the ListView
is empty. something like:
<Button
android:id="@+id/buttonEmptyListStuffs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List is empty, click me!"
android:visibility="gone"/>
//init the button and do other stuffs
...
buttonEmptyListStuffs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//go to activity 2
}
});
...
List<MyListViewItem> myListViewItems = //init your list of items for the listView
buttonEmptyListStuffs.setVisibility(myListViewItems.size() > 0 ? View.GONE : View.VISIBLE);
...
Note: I wrote this code by hand without compiler so it might not be perfect, just take the concept behind it
I forgot to mention that ListView has setEmptyView(View)
which allows you to set a custom layout for the Listview if it is empty. Refer to his link for a good tutorial