【问题标题】:customised listview using arrayadapter class in android在android中使用arrayadapter类自定义listview
【发布时间】:2013-05-17 03:02:54
【问题描述】:

如何在 android 中使用 iphone 之类的刻度线选择行项目?iam 在 list_row.xml 中使用 imageview。当我单击列表行项目时,我会在行 imageview 中显示图像。

if(getItem(position)!=null){
img.setvisibilty(View.Visible);}        
else{System.out.println("imagenull");}

我正在使用这个,但图像仅显示在最后一行。请帮助我如何使用标记图像选择项目。

public class DistanceArrayAdapter extends ArrayAdapter<Constant>{
public static String category,state,miles;
public ImageView img;
private Context context;
private int current = -1;
ArrayList<Constant> dataObject;

public DistanceArrayAdapter(Context context, int textViewResourceId,
ArrayList<Constant> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

rowView = inflater.inflate(R.layout.category_row, parent, false);

}
    //TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
    //textView.setText(""+getItem(position).id);
textView1.setText(""+getItem(position).caption);
img=(ImageView)rowView.findViewById(R.id.img);
img.setVisibility(View.GONE);
if(position%2==1)
{
rowView.setBackgroundResource(R.color.even_list);
}
else
    {
        rowView.setBackgroundResource(R.color.odd_list);
    }

rowView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if(img.getVisibility()==View.GONE)
            {
                img.setVisibility(View.VISIBLE);
                System.out.println("1");
            }
if(img.getVisibility()==View.VISIBLE){
img.setVisibility(View.GONE);
System.out.println("12");
}

miles=getItem(position).caption;
System.out.println("miles"+miles);
}
});
return rowView;
}
}

【问题讨论】:

  • 您想显示带有刻度线图像的行...?表示所有行??
  • 是的。当单击行时,仅在行中显示刻度线图像,而不是所有行仅选中行
  • Divya 解决了你的问题吗??
  • 不,我尝试了您的逻辑,但勾选标记图像仅显示在列表视图中行的最后一项中。我想在选择行项中显示图像。
  • @DivyaBalraj 检查下面的答案。它是 Romain Guy 谷歌开发者提供的解决方案。检查答案中的链接

标签: java android checkbox android-listview


【解决方案1】:

取自https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
    String[] GENRES = new String[] {"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"};
    private CheckBoxAdapter mCheckBoxAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView listView = (ListView) findViewById(R.id.lv);

        listView.setItemsCanFocus(false);
        listView.setTextFilterEnabled(true);
        listView.setOnItemClickListener(this);
        mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
        listView.setAdapter(mCheckBoxAdapter);
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                StringBuilder result = new StringBuilder();
                for (int i = 0; i < GENRES.length; i++) {
                    if (mCheckBoxAdapter.mCheckStates.get(i) == true) {
                        result.append(GENRES[i]);
                        result.append("\n");
                    }

                }
                Toast.makeText(MainActivity.this, result, 1000).show();
            }

        });
    }

    public void onItemClick(AdapterView parent, View view, int position, long id) {
        mCheckBoxAdapter.toggle(position);
    }

    class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener {
        LayoutInflater mInflater;
        TextView tv1, tv;
        CheckBox cb;
        String[] gen;
        private SparseBooleanArray mCheckStates;
        private SparseBooleanArray mCheckStates;

        CheckBoxAdapter(MainActivity context, String[] genres) {
            super(context, 0, genres);
            mCheckStates = new SparseBooleanArray(genres.length);
            mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            gen = genres;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return gen.length;
        }
    }
}

activity_main.xml

 <RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent">

 <ListView
 android:id="@+id/lv"
 android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_above="@+id/button1"/>
  <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_centerHorizontal="true"
      android:text="Button" />

</RelativeLayout>

以及复选框的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="15dp"
    android:layout_marginTop="34dp"
    android:text="TextView" />

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView1"
    android:layout_marginRight="22dp"
    android:layout_marginTop="23dp" />

 </RelativeLayout>

当您单击按钮时,会显示一条带有所选项目列表的 toast 消息。您可以根据自己的需要修改以上内容。

【讨论】:

    【解决方案2】:

    在 ListView 上设置选择模式

        //if using ListActivity or ListFragment
     getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    
        //or
    
         myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    
        //myListView is reference to your ListView
    

    【讨论】:

    • 单选和多选对TS案例有什么影响?
    【解决方案3】:

    我使用数组适配器为具有复选框的列表创建了一个示例。

    ListView with CheckBox using ArrayAdatpter in Android

    您也可以找到示例代码。

    这将被输出

    这是我的代码片段

    我有一个具有列表视图的 Activity

    public class MainActivity extends Activity {
    
     private ListView mainListView = null;
     private Planet[] planets = null;
     private ArrayAdapter<Planet> listAdapter = null;
    
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      mainListView = (ListView) findViewById(R.id.mainListView);
    
      // When item is tapped, toggle checked properties of CheckBox and
      // Planet.
      mainListView
      .setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View item,
        int position, long id) {
       Planet planet = listAdapter.getItem(position);
       planet.toggleChecked();
       PlanetViewHolder viewHolder = (PlanetViewHolder) item
        .getTag();
       viewHolder.getCheckBox().setChecked(planet.isChecked());
       }
      });
    
      // Create and populate planets.
      planets = (Planet[]) getLastNonConfigurationInstance();
      if (planets == null) {
       planets = new Planet[] { new Planet("Mercury"),
         new Planet("Venus"), new Planet("Earth"),
         new Planet("Mars"), new Planet("Jupiter"),
         new Planet("Saturn"), new Planet("Uranus"),
         new Planet("Neptune"), new Planet("Ceres"),
         new Planet("Pluto"), new Planet("Haumea"),
         new Planet("Makemake"), new Planet("Eris") };
      }
      ArrayList<Planet> planetList = new ArrayList<Planet>();
      planetList.addAll(Arrays.asList(planets));
    
      // Set our custom array adapter as the ListView's adapter.
      listAdapter = new PlanetArrayAdapter(this, planetList);
      mainListView.setAdapter(listAdapter);
     }
    
     public Object onRetainNonConfigurationInstance() {
      return planets;
     }
    }
    

    这是我处理复选框内容的自定义数组适配器

    public class PlanetArrayAdapter extends ArrayAdapter<Planet> {
    
     private LayoutInflater inflater;
    
     public PlanetArrayAdapter(Context context, List<Planet> planetList) {
     super(context, R.layout.simplerow, R.id.rowTextView, planetList);
     //Cache the LayoutInflate to avoid asking for a new one each time.
      inflater = LayoutInflater.from(context);
     }
    
     @Override
     public View getView(int position, View convertView, ViewGroup parent){
      Planet planet = (Planet) this.getItem(position);
      CheckBox checkBox;
      TextView textView;
    
      // Create a new row view
      if (convertView == null) {
      convertView = inflater.inflate(R.layout.simplerow, null);
    
      textView = (TextView) convertView.findViewById(R.id.rowTextView);
      checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
    
      convertView.setTag(new PlanetViewHolder(textView, checkBox));
    
      // If CheckBox is toggled, update the planet it is tagged with.
      checkBox.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
        CheckBox cb = (CheckBox) v;
        Planet planet = (Planet) cb.getTag();
        planet.setChecked(cb.isChecked());
       }
      });
      }
      // Re-use existing row view
      else {
    
      PlanetViewHolder viewHolder = (PlanetViewHolder) convertView
         .getTag();
       checkBox = viewHolder.getCheckBox();
       textView = viewHolder.getTextView();
      }
    
      checkBox.setTag(planet);
    
      // Display planet data
      checkBox.setChecked(planet.isChecked());
      textView.setText(planet.getName());
    
      return convertView;
     }
    
    }
    

    请!如果您在这方面有任何问题,请告诉我。

    【讨论】:

      【解决方案4】:

      1.使gone对你的标记图像可见

      2.在arrayadapter中实现view.setOnClickListener

      3. 在那检查image.getVisibility()==View.GONE 然后使image.setVisibity(View.Visible)

      4.如果image.getVisiblity()==View.VISIBLE 然后让你的image.setVisibity(View.GONE)

      试试这个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-18
        • 2014-07-20
        相关资源
        最近更新 更多