Skip to main content

Getting the Selected View from ListView



I am using a CursorAdapter to handle my ListActivity:







public class Mclass extends ListActivity{

...

TheAdapter mAdapter;

public static HashMap<Long, Boolean> shown = new HashMap<Long, Boolean>();

...



@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

super.onListItemClick(l, v, position, id);

Boolean tmp = shown.get(id);

if (tmp == null) { // if null we don't have this key in the hashmap so we added with the value true

shown.put(id, true);

} else {

shown.put(id, !tmp.booleanValue()); // if the value exists in the map then inverse it's value

}

mAdapter.notifyDataSetChanged();

}



}







And my adapter class extends CursorAdapter and overrides bindView







@Override

public void bindView(View view, Context context, Cursor cursor) {

String listText= cursor

.getString(cursor

.getColumnIndexOrThrow(DataHandler.MY_TEXT));



long id = cursor.getLong(cursor.getColumnIndexOrThrow(DataHandler.ROW_ID));

if (Mclass.shown.get(id) != null) {

TextView m_text = (TextView) view

.findViewById(R.id.my_text);

if (m_text != null) {

m_text.setVisibility(Mclass.shown.get(id)? View.VISIBLE:

View.GONE);



if (m_text.isShown())

m_text.setText("STRING");

}

}







My list item layout is defined in an xml file list_item.xml







<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:background="#DDDDDD"

android:orientation="horizontal" >



<LinearLayout

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:orientation="vertical" >



<ImageView

android:id="@+id/my_image"

android:layout_width="wrap_content"

android:layout_height="0dip"

android:layout_weight="1"

android:paddingRight="1dip"

android:paddingTop="1dip"

</LinearLayout>



/*

*I want to toggle this text view's visibility

*/

<TextView

android:id="@+id/my_text"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:visibility="gone"//VISIBILITY defined here

android:paddingBottom="2dip"

android:paddingLeft="4dip"

android:paddingRight="4dip"

android:paddingTop="5dip" />

</LinearLayout>







So my question is: How can I toggle the visibility the TextView in my layout within onListItemClick ? I've tried:







TextView mTextView = (TextView) v.findViewById(R.id.my_text);

mTextView.setVisibility(mTextView.isShown()? View.GONE: View.VISIBLE);

mAdapter.notifyDataSetChanged();







but it seems to choosing which list items to toggle at random, regardless of the one I click.


Comments

  1. You'll have to store the id's of the rows you'll hide. You could make a field in your activity to store those ids:

    HashMap<Long, Boolean> positionHide = new HashMap<Long, Boolean>();


    where the key is the long id of the row and the boolean object represents the status of the TextView(false- it is visible, true it is gone). In the onListItemClick() add the ids of the clicked rows to that field:

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    Boolean tmp = status.get(id);
    if (tmp == null) { // if null we don't have this key in the hashmap so we added with the value true
    status.put(id, true);
    } else {
    status.put(id, !tmp.booleanValue()); // if the value exists in the map then inverse it's value
    }
    }


    also modify the bindView() method:

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
    String listText = cursor.getString(cursor
    .getColumnIndexOrThrow(DataHandler.MY_TEXT));
    long pos = cursor.getLong(cursor.getColumnIndex(DataHandler.ID)); // DataHandler.ID will point to the column _id
    TextView m_text = (TextView) view.findViewById(R.id.my_text);

    if(status.get(pos) == null) {
    //id is not yet in the hashmap so the value is
    //by default false, the TextView is invisible
    m_text.setVisibility(View.GONE);

    } else {
    // we have the value in the
    // Hashmap so see what it is and set the
    // textview visibility from this value

    if (tmp.booleanValue()) {
    m_text.setVisibility(View.VISIBLE);
    } else {
    m_text.setVisibility(View.GONE);
    }
    }
    if (m_text != null)
    m_text.setText(listText);

    }


    For this to work you'll need to have in your database the column _id INTEGER PRIMARY KEY AUTOINCREMENT(and also added to the query).

    ReplyDelete
  2. You're problem is that views are reused in list view. This meens that even if you have a list consisting of 100 items, there will be only 10 or so view instances (depending on how much can be fitted on the screen). If you have written a custom adapter, you probably have seen the method getView. This takes a view to reuse as parameter.

    What you have done, is taken a view that displays for example the 23rd item in the list, and hide the text box. When the 23rd item is scrolled out of the screen, it's view gets reused, but only the values are replaced with the 33rd item's data, the visiblity you set remains invisible.

    What you should do is add a status boolean to all list items, and in the adapter's getView toggle the text boxes visibility according to the currently wanted state of the item.

    ------------------- EDITED CODE FROM THE ANSWER ABOW -----------------------
    HashMap positionHide = new HashMap();

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    Boolean tmp = positionHide.get(id);
    if (tmp == null) { // if null we don't have this key in the hashmap so we added with the value true
    positionHide.put(id, true);
    tmp = true;
    } else {
    tmp = !tmp.booleanValue();
    positionHide.put(id, !tmp.booleanValue()); // if the value exists in the map then inverse it's value
    }
    // You should also hide the text view, because bindView will not be called until the list item is scrolled out and in again
    TextView m_text = (TextView) view.findViewById(R.id.my_text);
    if (m_text != null) {
    if(tmp) {
    // We should hide the text view
    m_text.setVisibility(View.GONE);
    } else {
    // We should display the text view
    m_text.setVisibility(View.VISIBLE);
    }
    }
    }


    @Override
    public void bindView(View view, Context context, Cursor cursor) {
    String listText = cursor.getString(cursor
    .getColumnIndexOrThrow(DataHandler.MY_TEXT));
    TextView m_text = (TextView) view.findViewById(R.id.my_text);
    if (m_text != null) {
    m_text.setText(listText);
    long pos = cursor.getLong(cursor.getColumnIndex(DataHandler.ID)); // DataHandler.ID will point to the column _id
    if((positionHide.get(pos) != null)&&(positionHide.get(pos))) {
    // We should hide the text view
    m_text.setVisibility(View.GONE);
    } else {
    // We should display the text view
    m_text.setVisibility(View.VISIBLE);
    }
    }
    }


    For this to work you'll need to have in your database the column _id INTEGER PRIMARY KEY AUTOINCREMENT(and also added to the query).

    ReplyDelete
  3. First of use "invisible" instead of "gone" like below

    android:visibility="invisible"


    Try to use accordingly

    TextView mTextView = (TextView) v.findViewById(R.id.my_text);
    mTextView.setVisibility(mTextView.isShown()? View.INVISIBLE: View.VISIBLE);
    mAdapter.notifyDataSetChanged();

    ReplyDelete
  4. Well you shouldn't use ListView for any active View, try using TableLayout or LinearLayout instead.
    Look at this blog post for more details on this, however it's for CheckBoxes,but holds true for any active View.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.