How do you implement action listener on listView?
-
12-11-2019 - |
문제
I have been struggling for days trying to find the proper way to implement an action listener to a ListView. What I really want to accomplish is to create a ListView and whenever the user clicks any item, the previous Activity will be switched. I am really new at this so please help me, I would really appreciate it a lot. If you can tell me the what I'm doing wrong on my code that would be awesome!
I am using Fedor's code from [here][1].
///Here I tried to Implement an action listener but It doesn't work.
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id)
{
if(list.getItemAtPosition(position).equals(mStrings[1]))
{
Intent i = new Intent(MainActivity.this, Activity2.class);
startActivity(i);
}
}
});
}
해결책
You need to override onListItemClick in such a case. Refer to Click Listener on ListView for more help, the solution is a fairly good implementation.
Here is a possible implementation that should go in your Main activity. Please keep in mind that this will only work as long as you keep MainActivity extending Activity.
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Intent launcher here
}
If you wish to extend ListActivity instead of Activity later on and you need to call to onListItemClick, do it following this scheme
public class YourClass extends ListActivity implements OnItemClickListener{
@Override
public void onCreate(Bundle icicle){
super.onCreate(icicle);
setContentView(R.layout.your_layout);
getListView().setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// your stuff here
}
}