Android: handle onItemClick() in listView-based app - android

I'm new to Android. I'm working on a listView-based app: you have a main menu, when you click an item, a new activity starts with another menu; when you click again, a new activity starts with the content you selected. Since I've quite a lot of menu items, I've to create a listener which handles all possible cases, so I've something similar:
#Override public void onItemClick(AdapterView<?> listAdapter, View v, int position, long id) {
String text = ((TextView)v).getText().toString();
//main menu
if (text.equals(K.getStringById(K.ID_MAIN_THEORY))) {
...
} else if (text.equals(K.getStringById(K.ID_MAIN_EXERCISE))) {
...
}
else if (text.equals(K.getStringById(K.ID_MAIN_TABLES))) {
...
}
//here other menus' items: lots of items
...
//back item
else if (text.equals(K.getStringById(K.ID_BACK))) {
activity.finish();
}
Intent i = new Intent(...);
startActivity(i);
}
* K is a class that holds ids' references
There's a way I can avoid hard-coding listener behavior?
** PS: the lists' TextViews don't render properly: text appears light grey, not black! O.o

It's more useful to use the position rather than the view to switch the action of the click event. Your ListView should be populated from some sort of List, therefore when the onClick fires, giving you the position, you can reference that position in the List to know what was clicked.

If you want to click on item and in result it goes to another activity, for example if you have three item and when you click on item A it will redirect you to activity A and if B then to B and so on,
lstview.setOnItemClickListener(new OnItemClickListener()
{
private String input;
public void onItemClick(AdapterView<?> v, View arg1, int index,long arg3)
{
if(index==1)
{
Intent intnt=new Intent(v.getContext(),A.class);
startActivity(intnt);
}
else if (index==2)
{
Intent intnt=new Intent(v.getContext(),B.class);
startActivity(intnt);
}
else
{
Intent intnt=new Intent(v.getContext(),C.class);
startActivity(intnt);
}
}
}
Here in this case you are going to different activities on selection the items in a list view, put your comments for further query.

I solved this way: I think it's pretty good.
//This in K class, where MAPPED_HIERARCHY is a static field
static void activity(android.app.Activity a) {
MAPPED_HIERARCHY = new HashMap<String, ArrayList<String>>();
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.app_name), K.array2list(a.getResources().getStringArray(R.array.menu_main)));
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.main_theory), K.array2list(a.getResources().getStringArray(R.array.menu_theory)));
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.main_exercise), K.array2list(a.getResources().getStringArray(R.array.menu_exercise)));
....
}
static ArrayList<String> getArrayListByString(String string) {
ArrayList<String> copy = new ArrayList<String>(MAPPED_HIERARCHY.get(string).size());
for (String s : MAPPED_HIERARCHY.get(string))
copy.add(s);
return copy; //defensive copy
}
//This in my listener class
#Override public void onItemClick(AdapterView<?> listAdapter, View v, int position, long id) {
String text = ((TextView)v).getText().toString();
ArrayList<String> params = K.getArrayListByString(text);
Intent i = new Intent(...);
i.putExtra("params", params);
activity.startActivity(i);
}
I have a map which links an arraylist containing the menu items with the string wihich causes the menu to be displayed; on the click event, I simply retrieve the arraylist according with the selected item's text.

Related

in Android detect if a ListView item is clicked

I have a ListView in a Fragment where I need to be able to detect when an item in the ListView is selected. I need the list item to throw a flag or something along those lines so that a method in the Main Activity which houses the Fragments can detect whether or not the ListView was acted upon. I need a method in the Main Activity basically like this:
public void doSomething(){
if(Fragment ListView onItemClick is detected){
//--- do something
} else {
//--- don't do anything
}
}
The OnItemClickListener in the Fragment ListView that needs to indicate that it's been acted upon looks like this:
list_LV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor getPathCursor = (Cursor) list_LV.getItemAtPosition(position);
String cursorSDFStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("sdfdate"));
String cursorCalDateStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("caldate"));
String cursorURLStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("path"));
String cursorTitleStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("title"));
String cursorbodyStr = getPathCursor.getString(getPathCursor.getColumnIndexOrThrow("body"));
Intent slpI = new Intent("com.myapp.LISTVIDEO");
slpI.putExtra("SDFKey", cursorSDFStr);
slpI.putExtra("CalDateKey", cursorCalDateStr);
slpI.putExtra("PathKey", cursorURLStr);
slpI.putExtra("TitleKey", cursorTitleStr);
slpI.putExtra("bodyKey", cursorbodyStr);
startActivity(slpI);
}
});
You should follow the steps google outlined here http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
You can alternately use broadcasts or something like Otto http://square.github.io/otto/

Setting images in gridview to transparent

So I have images in gridview. These images are shown in an activity. When one of the images is clicked, new activity is started with this image. In this activity, If user inputs correct answer, new activity is started that indicates the answer is correct. After user inputs correct answer, I want to set this image more transparent with a check mark in gridwiew. If the user clicks again to this correct view, I want to show same activity which indicates it was solved correct. How can I do that?
Here is my activity which contains grid view:
public class LogoSelectionActivity extends Activity {
.
.
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent(LogoSelectionActivity.this, LogoActivity.class);
intent.putExtra ("clicked_position", position);
startActivity(intent);
}
Here is my activity where user enter inputs:
public class LogoActivity extends Activity{
EditText text;
Button check;
Boolean a;
int id;
Names name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logo);
check = (Button) findViewById(R.id.Check_button);
text = (EditText) findViewById(R.id.editText1);
ImageView view = (ImageView)findViewById(R.id.imageView1);
final ImageView incorrect = (ImageView)findViewById(R.id.incorrect);
switch (getIntent().getIntExtra ("clicked_position", -1))
{
case 0:
view.setImageResource(R.drawable.adese);
id = R.drawable.adese;
break;
case 1:
view.setImageResource(R.drawable.birvar);
id = R.drawable.birvar;
break;
case 2:
view.setImageResource(R.drawable.agaoglu);
break;
case 3:
view.setImageResource(R.drawable.akinsoft);
break;
default:
view.setImageResource(R.drawable.afra);
id = R.drawable.afra;
}
name = Names.forDrawable(id);
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
a=name.isCorrect(text.getText().toString());
if(a==true){
Intent intent = new Intent(LogoActivity.this, CorrectActivity.class);
startActivity(intent);
}
else{
incorrect.setVisibility(0);
incorrect.setVisibility(4);
}
}
});
}
}
I hope I could explain my intention clearly.
There are number of ways to do this. Because this is not problem this is functionality that you want in your project.
According to my logic I am giving you one solution.
Steps:
Create one static array with the length of your items in grid view with default value is 0.
static int[] items = {0,0,0,...};
Now check in getView methode of grid view with the value according to position in array that if it is 0 then it will looks like normal otherwise it will look with different (Here you want transparent with check box this will you get by adding one more image on it.)
If(items[position] == 0){
}else{
}
Now when user taps any image and navigate to other screen (Suppose Activity B) that time pass value of that position from that array and check in Activity B's OnCreate().
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent(LogoSelectionActivity.this, LogoActivity.class);
intent.putExtra ("clicked_position", position);
intent.putExtra ("answered_or_not", items[position]);
startActivity(intent);
}
And if answered means if its value is 1 then show accordingly other wise as it is.
And when it user give answer unanswered question make its value 1 in that array.
I hope it will help you can ask if any question.

How to get data from object in Android

In the following code, on click of list item I want to fetch variable present inside the object, How I can achive this
Below is code snippet
private void onListViewItemClick() {
// TODO Auto-generated method stub
// item click switch to next activity
listCustomListViewId.setOnItemClickListener(new OnItemClickListener() {
/* on click gets list view item id */
public void onItemClick(AdapterView<?> myAdapter, View myView,
int myItemInt, long mylng) {
// fetching clicked item id
Object o = listCustomListViewId.getItemAtPosition(myItemInt);
Log.i("Victory Item Id:.....", String.valueOf(o);
long strid = (long) (listCustomListViewId
.getItemIdAtPosition((int) mylng));
Log.i("Item Id...#######", String.valueOf(strid));
/* switch on next 'ListItemDeleteUpdateActivity' activity */
Intent intent = new Intent(FeedsActivity.this,
VictoryDetailActivity.class);
intent.putExtra("customElements", o.toString());
startActivity(intent);
}
});
}
I have tried to get data into Object but unable to fetch.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the data associated with selected item
Object item = l.getItemAtPosition(position);
String myitem = item.toString();
edittxt.setText("Selected item is :"+ myitem); // You can Set EditText from Here.
/* switch on next 'VictoryDetailActivity' activity */
Intent intent = new Intent(FeedsActivity.this,VictoryDetailActivity.class);
intent.putExtra("customElements",myitem);
startActivity(intent);
}
Hope this helps you.
On DataSource you have probably an collection of something. myItemInt represent the corresponding item in your collection to the item clicked. Use that.
If you have some views inside the clicked view you need to get, use findViewbyId on myView, like this:
myView.findViewbyId(R.id.myEditTextControl) //demo, use yours
If this answer is not enough for you, post some code from your adapter and tell us more details about what you need to do.
To handle events when the items of ListView is selected. You must override onListItemClick() method. The medthod have 4 parameters:
#Override
protected void onListItemClickonListItemClick(ListView l, View v, int position, long id)
To get information about ItemSelected, you just call getItemAtPosition(position) method to return a object which contains data.
It should be onListItemClick()

returning listview clicked position to another activity

I'm having a very simple problem, which can be solved fairly simple but for some reason I cannot figure it out why is it not working.
I have a view composed of 6 Listviews and when the user clicks on a detail position I'm returning the position.
This position will be used to get the items from an entire row in a database.
When passing the position to another activity, The detail activity, the position I get is the one which I initialized, which is 0.
Here is my code.
1st Activity
The item click listener:
detailsLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
/*
* Intent openDetails = new Intent(
* "com.DCWebMakers.Vairon.APPOINTMENTDETAILS");
* startActivity(openDetails);
*/
positionView = detailsLi.getSelectedItemPosition();
Dialog showPosition = new Dialog(MyAppointment.this);
showPosition.setTitle("Position is:" + positionView);
}
});
the return position method:
public Integer getPosition() {
return positionView;
}
2nd activity
Setting the row:
AppointmentInfo details = new AppointmentInfo(this);
details.open();
String name = details.getName(new MyAppointment().getPosition());
details.close();
So, is the return position method not being used correctly?
Thanks.
new MyAppointment().getPosition()
A new instance will return your default value. You should be passing the position:
In your list item click:
Intent intent = new Intent("com.example.newactivity");
intent.putExtra("list_position", arg2);
startActivity(intent);
arg2 will give you the item position in the list..
to get the item use aV.getItemAtPosition(arg2).toString()

How to get the selected item from ListView?

in my Android app I have created a ListView component called myList, and filled it with objects of my own custom type:
class MyClass{
private String displayName;
private String theValue;
... //here constructor, getters, setters and toString() are implemented
}
I used the ArrayAdapter to bound the ArrayList theObjects with myList:
ArrayAdapter<MyClass> adapter=
new ArrayAdapter<MyClass>(this, R.layout.lay_item, theObjects);
myList.setAdapter(adapter);
This works fine, the list is populated and etc., but when I'm trying to access the selected item, i receive a Null object. I've done this using
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass selItem = (MyClass) myList.getSelectedItem(); //
String value= selItem.getTheValue(); //getter method
}
What seems to be the problem? Thank you
By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
myList.getSelectedItem();
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
myList.getItemAtPosition(position);
You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.
What you should change, in your above example, is to
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass item = (MyClass) adapter.getItem(position);
}
Since the onItemClickLitener() will itself provide you the index of the selected item, you can simply do a getItemAtPosition(i).toString(). The code snippet is given below :-
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String s = listView.getItemAtPosition(i).toString();
Toast.makeText(activity.getApplicationContext(), s, Toast.LENGTH_LONG).show();
adapter.dismiss(); // If you want to close the adapter
}
});
On the method above, the i parameter actually gives you the position of the selected item.
On onItemClick :
String text = parent.getItemAtPosition(position).toString();
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass selItem = (MyClass) adapter.getItem(position);
}
}
Using setOnItemClickListener is the correct answer, but if you have a keyboard you can change selection even with arrows (no click is performed), so, you need to implement also setOnItemSelectedListener :
myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
MyObject tmp=(MyObject) adapterView.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// your stuff
}
});
In touch mode, there is no focus and no selection. Your UI should use a different type of widget, such as radio buttons, for selection.
The documentation on ListView about this is terrible, just one obscure mention on setSelection.
Though I am using kotlin, the following code answered your question. This return selected item:
val item = myListView.adapter.getItem(i).toString()
The following is the whole selecteditem Listener
myListView.setOnItemClickListener(object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
id: Long) {
val item = myListView.adapter.getItem(i).toString()
}
})
The code returns the item clicked by its index i as shown in the code
MyClass selItem = (MyClass)
myList.getSelectedItem(); //
You never instantiated your class.

Categories

Resources