Skip to main content

Getview Method Wierd in Listview

Its common issue in android and most of newbee faced.

To understand why its happening, you have to read about behavior of Getview method of listivew, its your home work, let continue with tutorial.

Below tutorial will explain that how to maintain the position of button  which is in row file using settag and gettag.

main.xml ( its contain listview which will hold row data)

<?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="fill_parent"
    android:descendantFocusability="blocksDescendants">

 <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>

row.xml ( Its contain one togglebutton of which we will maintain the state of check/uncheck and textview)

<?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="fill_parent"
    android:descendantFocusability="blocksDescendants">

    <ToggleButton
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="tag"
        android:paddingLeft="10dip"/>

</LinearLayout>



GetviewMethodWiredListviewActivity.java

package com.openxcell.GetviewMethodWiredListview;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class GetviewMethodWiredListviewActivity extends Activity  {
    /** Called when the activity is first created. */
    ArrayList<String> listarray = new ArrayList<String>();
    ListView list;
    ListviewAdapter adapter;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        listarray.add("android1.0");
        listarray.add("CupCake");
        listarray.add("Donut");
        listarray.add("Elcair");
        listarray.add("Froyo");
        listarray.add("GingerBread");
        listarray.add("HoneyComb");
        listarray.add("IcreamSandswich");
        listarray.add("android1.0");
        listarray.add("CupCake");
        listarray.add("Donut");
        listarray.add("Elcair");
        listarray.add("Froyo");
        listarray.add("GingerBread");
        listarray.add("HoneyComb");
        listarray.add("IcreamSandswich");
        listarray.add("android1.0");
        listarray.add("CupCake");
        listarray.add("Donut");
        listarray.add("Elcair");
        listarray.add("Froyo");
        listarray.add("GingerBread");
        listarray.add("HoneyComb");
        listarray.add("IcreamSandswich");
        listarray.add("ziyaNziya");
       
        list=(ListView)findViewById(R.id.listView);
     
        adapter= new ListviewAdapter(this,listarray);
        list.setAdapter(adapter);
       
        list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                 Toast.makeText(GetviewMethodWiredListviewActivity.this, "clicked", Toast.LENGTH_SHORT).show();   
               
            }
        });
    }
  
    }


ListviewAdapter.java


package com.openxcell.GetviewMethodWiredListview;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class ListviewAdapter extends BaseAdapter {
    ArrayList<String> getData = new ArrayList<String>();
    Context c;
    private LayoutInflater mInflater;
    int pos;
    int boxState[];

    public ListviewAdapter(Context cont, ArrayList<String> data) {
       c = cont;
        getData = data;
        mInflater = LayoutInflater.from(cont);

        boxState = new int[getData.size()];

        for (int i = 0; i < getData.size(); i++) {
            boxState[i] = 0;
        }
    }

    public int getCount() {
        return getData.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
       return position;
    }

    public class ViewHolder {
        private TextView name = null;
        private ToggleButton mBox = null;

    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
       return getData.size();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
       final ViewHolder holder;
        View vi = convertView;
        pos = getItemViewType(position);

        if (convertView == null) {

            vi = mInflater.inflate(R.layout.row, null);

            holder = new ViewHolder();

            holder.name = (TextView) vi.findViewById(R.id.textView);
            holder.mBox = (ToggleButton) vi.findViewById(R.id.checkBox);

            vi.setTag(holder);
        }

        else {
            holder = (ViewHolder) vi.getTag();
        }

        holder.name.setText(getData.get(pos));

        holder.mBox.setTag(pos);

        holder.mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                pos = (Integer) buttonView.getTag();
                // boxState[pos] = 1;
                // pos = (Integer) v.getTag();

                if (!buttonView.isChecked()) {
                    boxState[pos] = 0;
                } else {
                    boxState[pos] = 1;
                }
                notifyDataSetChanged();
            }
        });
        if (boxState[position] == 0) {
            holder.mBox.setChecked(false); // set unchecked"
        } else {
            holder.mBox.setChecked(true); // set checked"
        }

        return vi;
    }

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.openxcell.GetviewMethodWiredListview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".GetviewMethodWiredListviewActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output:


This way you can maintain the state of button which is inside your row, within getview method of listview, below is the link of my stackoverflow answers which is related to this issue.



Good luck!

Comments

  1. http://alexgorbatchev.com/SyntaxHighlighter/ Use thi syntax highlighter for code blocks. :) Good luck.

    ReplyDelete

Post a Comment

Popular posts from this blog

EasyPermissions

public class EasyPermissions { private static final String TAG = "EasyPermissions" ; private static PermissionDialog finalPermissionDialog = null ; public interface PermissionCallbacks { void onPermissionsGranted( int requestCode, List<String> perms); void onPermissionsDenied( int requestCode, List<String> perms); void onPermissionsPermanentlyDeclined( int requestCode, List<String> perms); } /** * Check if the calling mContext has a set of permissions. * * @param context the calling mContext. * @param perms one ore more permissions, such as { @code android.Manifest.permission.CAMERA}. * @return true if all permissions are already granted, false if at least one permission * is not yet granted. */ public static boolean hasPermissions(Context context, String... perms) { // Always return true for SDK < M, let the system deal with the permissions if (Bu

Amazon S3 Configuration

Gradles //amazon s3 compile 'com.amazonaws:aws-android-sdk-core:2.2.+' compile 'com.amazonaws:aws-android-sdk-s3:2.2.+' Declare in manefiest file <!--AMAZON S3--> < service android :name= "com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android :enabled= "true" /> AmazonUtils.java import android.content.Context; import android.net.Uri; import com.amazonaws.auth.CognitoCachingCredentialsProvider; import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver; import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3Client; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.UUID; /* * Handles basic helper functions used throughout the app. */ public class AmazonUtil { // We only n

Volley Network Call

  Volley.java public class Volley { private static Volley mInstance ; private RequestQueue mRequestQueue ; private ImageLoader mImageLoader ; private static Context mCtx ; public static final String TAG = Volley. class .getSimpleName(); private Volley(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); mImageLoader = new ImageLoader( mRequestQueue , new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>( 20 ); @Override public Bitmap getBitmap(String url) { return cache .get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache .put(url, bitmap); }