просмотр списка с флажком - PullRequest
1 голос
/ 21 марта 2011

Я хочу показать список с флажком, например

          checkbox listitem1
          checkbox listitem2
          checkbox listitem3
                  .
                  .
                  .
                  .

Если щелкнуть любой элемент списка в списке, соответствующий флажок будет установлен на true.Я попробовал ниже код

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:text=""
    android:id="@+id/list_checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    ></CheckBox>
 <TextView
 android:id="@+id/songname"
 android:layout_height="wrap_content"
 android:layout_width="wrap_content"
 android:layout_marginTop="10px"
 android:layout_marginLeft="60px"/>
 <TextView
 android:id="@+id/artist"
 android:layout_height="wrap_content"
 android:layout_width="wrap_content"
 android:layout_marginTop="30px"
 android:layout_marginLeft="60px"/>
</RelativeLayout> 

Файл класса

 list.setOnItemClickListener(this);
 list.setAdapter(new EfficientAdapter(this));

private static class EfficientAdapter extends BaseAdapter 
    {
       private LayoutInflater mInflater;

       public EfficientAdapter(Context context) 
       {
       mInflater = LayoutInflater.from(context);
       }

       public int getCount() 
       {
       return title.length;
       }

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

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

       public View getView(int position, View convertView, ViewGroup parent) 
       {
       ViewHolder holder;
       if (convertView == null) 
       {
       convertView = mInflater.inflate(R.layout.selectsongs, null);
       holder = new ViewHolder();

       holder.title = (TextView) convertView.findViewById(R.id.songname);
       holder.artist = (TextView) convertView.findViewById(R.id.artist);
       holder.check = (CheckBox) convertView.findViewById(R.id.list_checkbox);    
       convertView.setTag(holder);
       } 
       else 
       {
       holder = (ViewHolder) convertView.getTag();
       }

       holder.title.setText(title[position]);  
       holder.artist.setText(artist[position]);

       return convertView;
       }

       static class ViewHolder 
       {
       TextView title,artist;

       CheckBox check;

       }
       }
    @Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
    // TODO Auto-generated method stub
    Log.e("name",title[position]);

}

, но в этом OnClickItemClickListener на просмотр списка не работает.Флажок, отмечаемый флажком, имеет значение true, когда я нажимаю на флажок, а не на элемент списка в просмотре списка.Поэтому, пожалуйста, скажите мне, как отобразить просмотр списка с помощью флажка, а также флажок listitem, который можно установить, когда я нажимаю на элемент списка.

С наилучшими пожеланиями.

Заранее спасибо

Ответы [ 3 ]

3 голосов
/ 21 марта 2011

Лучше выполнить список, используя ChechBoxPreference .

Основное преимущество использования предпочтений состоит в том, что вам не нужно писать код для сохранения значения, и вы можете легко получитьценность в любой деятельности.Значение сохраняется в настройках Android в качестве значения пары ключей.Вы можете ссылаться на значение, используя «KeyName».

Следующая ссылка поможет вам получить представление об этом:

http://geekswithblogs.net/bosuch/archive/2010/12/03/android---creating-a-custom-preferences-activity-screen.aspx

0 голосов
/ 01 ноября 2011

После двух часов работы у меня есть решение.

/**
*This is Adapter class 
*/
  public class CustomListAdapter extends BaseAdapter {

        private String[] stringArray;
        private Context mContext;
        private LayoutInflater inflator;
        int checkbox;
        /**
         * 
         * @param context
         * @param stringArray
         */
        public CustomListAdapter(Context  context, String[] stringArray) 
        {
            this.mContext=context;
            this.stringArray=stringArray;
            this.inflator= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public int getCount()
        {
            return stringArray.length;
        }

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {

            final MainListHolder mHolder;
            View v = convertView;
            if (convertView == null)
            {
                mHolder = new MainListHolder();
                v = inflator.inflate(android.R.layout.simple_list_item_multiple_choice, null);
                mHolder.txt=(CheckedTextView) v.findViewById(android.R.id.text1);
                v.setTag(mHolder);
            } 
            else
            {
                mHolder = (MainListHolder) v.getTag();
            }
            mHolder.txt.setText(stringArray[position]);
            mHolder.txt.setTextSize(12);
            mHolder.txt.setTextColor(Color.YELLOW);

        /**
         * When checkbox image is set By setImageFromResourceCheckBox(int id) method...Otherwise it takes default
         */
            if(checkbox!=0)
                mHolder.txt.setCheckMarkDrawable(R.drawable.android_button);

            mHolder.txt.setPadding(5, 5, 5, 5);
            return v;
        }
        class MainListHolder 
        {
            private CheckedTextView txt;

        }
        /***
         * Setting Image for Checkbox
         * @param id
         * 
         */
        public void setImageFromResourceCheckBox(int id)
        {
            this.checkbox=id;
        }


    }

И класс Activity должен быть таким.

public class MyActivity extends ListActivity implements OnItemClickListener  {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        CustomListAdapter c=new CustomListAdapter(this,GENRES);
      //  c.setImageForCheckBox(R.drawable.android_button);//Image for checkbox
        setListAdapter(c);

        final ListView listView = getListView();
        listView.setItemsCanFocus(false);
      //  listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);// For single mOde

        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setItemChecked(2, true);

        listView.setOnItemClickListener(this);
    }


    private static  String[] GENRES = new String[] {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
    };
    @Override
    public void onItemClick(AdapterView<?> adapter, View arg1, int arg2, long arg3)
    {

    SparseBooleanArray sp=getListView().getCheckedItemPositions();

    String str="";
    for(int i=0;i<sp.size();i++)
    {
        str+=GENRES[sp.keyAt(i)]+",";
    }
    Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();

    }


}
0 голосов
/ 21 марта 2011

У меня такая же проблема. я только что исправил это за 2 дня до:

В: общедоступном представлении getView

 cb =(CheckBox)row.findViewById(R.id.CheckBox01);
          cb.setChecked(etat[position]);

          final int xt=position;

          cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                if(arg0.isChecked())
                {           
                    etat[xt]=true;
                    //Update the state of Checkbox to the: "tabEtat"
                    Etat.getInstance().setAddIdEtat(String.valueOf(xt));
                        }                         
                }
                else
                {
                    //Update the state of Checkbox to the : "tabEtat"
                    Etat.getInstance().setDeleteIdEtat(String.valueOf(xt));
                        }                          
                }
            }
        });       
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...