Graphite January 2017

Android - List View - setOnItemClickListener

I have such a problem. I'm trying to get Id of row in List View. To do so I'm using setOnClickListener.

wyswietlenieZadan=(ListView)findViewById(R.id.ListView);
mAdapter=new ArrayAdapter<>(this, R.layout.zadania, R.id.opisZadania,
                        listaZadan);
wyswietlenieZadan.setAdapter(mAdapter);
wyswietlenieZadan.setOnItemClickListener(new 
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Twoje id: " +id, Toast.LENGTH_SHORT).show();

}}
);

Here is my zadania.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical">
<TextView
android:id="@+id/opisZadania"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"
android:textSize="20sp"
android:layout_marginStart="32dp"
android:layout_alignParentStart="true"
android:layout_marginTop="12dp"
android:clickable="true"
android:contextClickable="true"
/>

<ImageButton
android:layout_width="wrap_content"
app:srcCompat="@android:drawable/ic_menu_close_clear_cancel"
android:id="@+id/task"
android:layout_marginEnd="19dp"
android:layout_height="wrap_content"
style="@android:style/Widget.ImageButton"
android:background="@android:drawable/ic_delete"
android:onClick="usunZadanie"
android:layout_alignTop="@+id/opisZadania"
android:layout_alignParentEnd="true"
android:focusable="false"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@android:drawable/ic_menu_edit"
android:id="@+id/imageView"
android:layout_toStartOf="@+id/task"
android:layout_alignTop="@+id/task"
android:onClick="edytujZadanie"
android:        

Answers


Shashank Singh January 2017

change

Toast.makeText(getApplicationContext(), "Twoje id: " +id, Toast.LENGTH_SHORT).show();

to

Toast.makeText(getApplicationContext(), "Twoje id: " +position, Toast.LENGTH_SHORT).show();

as position variable gives you the position of the item you just clicked like if you click first item it will show Twoje id:0,if you click second item it will show Twoje id:1 and so on...

Post Status

Asked in January 2017
Viewed 1,007 times
Voted 4
Answered 0 times

Search




Leave an answer