about ListView code - android

I am new to android and right now I am learning about ListView.
I was reading tutorials from bogotobogo.com when I saw this code:
ListView lv = getListView();
lv.setTextFilterEnabled(true);
*** lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) v).getText(),
Toast.LENGTH_SHORT).show();
}
}); ***
i was not able to understand code from lv.setOnItemClickListener(new OnItemClickListener(); is it an argument?
Can some one help me to understand it?

What that code is doing is implementing a new OnItemClickListener inline. The OnItemClickListener interface is basically a contract that says that an object will provide an implementation of the function onItemClick(....). Later on, when an item in your list gets clicked, the onItemClick function will be called and the AdapterView (thing that's instantiating and managing the list rows, the view - (the render code for a particular row), the position (the position in the list) and an id property which I never use so you can look up what that's for are being passed in.
Inline code like this always looks strange to me. There are a couple other ways to write this that I think make more intuitive sense. Just keep in mind that what you're doing is writing some code to get executed when a row in your list gets clicked.
1 - You can have your Activity implement OnItemClickListener
public class SomeActivity extends Activity implements OnItemClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourview);
ListView lv = (ListView)findViewById(R.id.listView);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
//Your toast code goes in here
}
}
In this code you're having your main class implement the OnItemClickListener interface so setOnItemClickListener sees the main class (this) as an instance of OnItemClickListener. When a row in your list gets clicked the onItemClick function will get called.
You can also 2 - have your click listener come from an internal class.
public class SomeActivity extends Activity implements OnItemClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourview);
ListView lv = (ListView)findViewById(R.id.listView);
lv.setOnItemClickListener(new YourInternalClass());
}
class YourInternalClass implements View.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
//Your toast code goes in here
}
}
}
And really all three methods are doing the same thing: Providing the setOnItemClickListener with an instance of a View.OnItemClickListener class that will have it's onItemClick function called when a row in the list gets clicked.

Related

android studio. i ask about the use of on item click listener function. how it work?

ListView listView;
ArrayAdapter<String> adapter;
String[] hotel = {"one room", "double room", "suit", "vip"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hotel);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),adapterView.getItemIdAtPosition(i)+"is Checked",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),adapter.getItem(i),Toast.LENGTH_LONG).show();
}
});
}
Could anyone explain to me how on item clickListener work? what View view , int i , long I mean on (onclick item listener?. A new Adapter view class or object?
OnItemClickListener is a Listener which keep listening for the events. When you click any item in the ListView then this interface will fired and it'll call the onItemClick callback(abstract method). So just override this method and put your code which needs to run when the item is clicked. In your case, you're just showing the item id with Toast.
onItemClick : It is a Callback method in Android. This can be invoked when an item in this ListView has been clicked.
This method accepts four parameters adapterView, view, i, l
AdapterView(adapterView): The AdapterView where the click happened. This might be a ListView, GridView etc. These classes are derived from the AdapterView class.
View(view): The view within the AdapterView that was clicked (this will be a view provided by the adapter). The View parameter passed in the onItemClick() method when you click the item in the ListView.
int(i): The position of the view in the adapter. By this way, you can get the item. Position starts from 0 to n.
long(l): The row id of the item that was clicked.
Please see this documentation. Hope this helps you...

Android Problems

I have a problem that i am trying to solve using android to develop and app for a trivia quiz so i need to start a quiz based on the category chosen. The problem is as follows:
Question 1
I cant seem to figure out how to pass the item selected from a ListView i can pass what is selected using spinner but not a list selection.
private String getCategory(){
final String category[] =new String[1];
final ListView list = (ListView) findViewById(R.id.soloList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View View, int position, long id) {
category[0] =(String) (list.getItemAtPosition(position));
}
});
return category[0];
}
That is the part of the code is use and cant seem to get it to work and my question is how do i make it work? I call the method within main but nothing ever gets passed.
Thanks.
About Q1 :
You have function that return String it's ok but what's wrong that not made code work is ItemClickListener
First let me tell you about Interfaces in Java :
As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off. - link
The problem in this code is that you set kind of interface on each item click, but you function not wait for item click callback to return result !
the way you can handle is :
1: Create Interface for Callback when user select new item on listview
public interface category {
public void getCategory(String itemTitle);
}
2: set callback to you Activity Fragment or ...
public class ProjectList extends Fragment implements category
3: Override callback function
#Override
public void getCategory(String itemTitle) {
// do something with new item !
}
4: Call callback function when item selected
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View View, int position, long id) {
ProjectList.this.getCategory("newitem-String")
}
});

How to dynamically create new threads

I have a for loop which creates views dynamically.
for (int i=0;i<5;i++){
a=new ImageView();
tv=new TextView();
img=new ImageView();
spn=new Spinner();
img.setOnClickListener(this);//this is working for every view
spn.post(new Runnable){
#Override
public void run() {
Log.d("post","inside post");// here only last view is working
}
} //for loop ends
But how to create spinner.post dynamically or make it work.
Please help. Stuck on it for last three days.Thanks in advance.
Make your activity implementes OnItemSelectedListener, which is the callbak registered for every item selected in the spinner, and then inside this callback implements what you need on every view.
Your class definition:
public class SpinnerActivity extends Activity implements OnItemSelectedListener
Implements onItemSelected callback in your activity:
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
If you need documentation look at this http://developer.android.com/guide/topics/ui/controls/spinner.html ;)

OnItemClick doesn't work with custom adapter

I have a ListView with Custom Adapter. I have seen this thread where people asked if the items in the custom view had a clickable item. And Yes, I have a clickable ImageView in the listrow. So clicking anywhere else(other than that ImageView) should perform some other action. I gave an onItemClickListener to the ListView. However, it doesn't work on first click and works on two-three clicks.
Update:
In my adapter's getView method, I set onClick of ImageView like this:
holder.chatImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Stuff here
}
});
It works fine, and in my activity, I gave onItemClickListener to listView likw this:
onlineListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
//Stuff here
}
});
PS: I didn't explicitly give any focus to anything.
Some time ago I've faced the same problem but with a CheckBox, I've resolve it by creating a onClickListener as member of the Custom Adapter. For example
public MyAdapter extends BaseAdapter{
// ... ..
// ... ...
private OnClickListener imageClickListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
/// your data .getTag()
// process onClickListener for image
}
};
}
And then, in your getView:
if (convertView == null){
//Create your views and register onClickListener
holder.chatImageView.setOnClickListener(imageClickListener);
}
Add android:focusable="false" to your image in xml.
Hope it helps, Here you have the entire example:

onItemClick not being invoked on ListActivity

I have a class that extends from ListActivity and implements OnItemClickListener
It's a very simple test class, the idea is that I select an item on the list, and it shows the selected item on a Toast.
I can see the list normally on the emulator, and I can also see the effects of clicking in the item, but then nothing happens.
I don't think the event is being fired, because I see nothing on LogCat, here's the code:
public class CarsListActivity extends ListActivity implements
OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listCars()));
}
private List<String> listCars() {
return Arrays.asList("Ferrari", "Lamborghini", "Porsche");
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textView = (TextView) view;
String message = "Selected car: " + textView.getText();
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
The Activitiy is defined like this on the AndroidManifest.xml file:
<activity android:name=".CarsListActivity" />
Is there anything I'm missing?
I researched this error and I found many solutions saying that this concerns clickability and focusability attributes on the layout. But I'm using Android's own android.R.layout.simple_list_item_1 so I don't really know how I could fix it.
Am I missing some configuration?
You need to register the OnItemClickListener (the activity) like this :
getListView().setOnItemClickListener(this)
Simply implementing the OnItemClickListener interface is not sufficient
add this in onCreate() below setListAdapter()
getListView().setOnItemClickListener(this);
use this on oncreate()
getListView().setOnItemClickListener(this);

Categories

Resources