Ngo Van
Ngo Van

Reputation: 887

Android: getItemAtPosition() in Custom listview: Image and TextView

I have a custom ListView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:orientation="horizontal">

<ImageView
    android:id="@+id/image"
    android:layout_width="70dip"
    android:layout_height="50dip"
    android:contentDescription="@string/menu_settings"
    android:scaleType="centerCrop"
    android:src="@drawable/ico_slide" />

<TextView
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="left|center_vertical"
    android:layout_marginLeft="10dip"
    android:text="@string/app_name"
    android:layout_weight="1"
    android:textSize="20sp" />

I want to get text of TextView

public void onItemClick(final AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            Object[] item = (Object[]) arg0.getItemAtPosition(arg2);
            final String name = item[1].toString();

By using this, it have CastClassException and line:

Object[] item = (Object[]) arg0.getItemAtPosition(arg2);

Does anyone know how to get text of the TextView?

Upvotes: 1

Views: 2267

Answers (2)

Mike
Mike

Reputation: 1000

If you're using the ViewHolder pattern in your Adapter you should use getTag() to get your TextView for performance reasons:

public void onItemClick(final AdapterView<?> arg0, View arg1, int arg2, long arg3) {
       ViewHolder holder = (ViewHolder) arg1.getTag();
       String text = holder.text.getText();
}

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

Use the below. The second param arg1 is a view. Use that to initialize text view and get the string.

public void onItemClick(final AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

           TextView tv = (TextView)arg1.findViewById(R.id.text);
           String textvalue= tv.getText().toString()  
}

Upvotes: 4

Related Questions