列表视图的onClick中复制的项目

时间:2014-10-08 18:20:46

标签: android

我在SD卡的app文件夹中存储了一些图像(.jpg)和pdf(.pdf)。列表视图已填充,但当我点击列表视图中的pdf项目时,jpg和pdf的项目都会多次显示在列表视图中。我需要帮助才能搞清楚。谢谢

public class Data_Adapter extends ArrayAdapter<Data_Class>{


    Context context;
    int ResourceLayoutId;
    ArrayList<Data_Class> data=null;

    public Data_Adapter(Context c,int r,ArrayList<Data_Class> dc)
    {
        super(c,r,dc);
        this.ResourceLayoutId=r;
        this.context=c;
        this.data=dc;

    }


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

        View row=convertView;
        DataHolder holder=null;

        if(row==null)
          {
              LayoutInflater inflater= ((Activity)context).getLayoutInflater();
              row=inflater.inflate(ResourceLayoutId, parent, false);
              holder=new DataHolder();
             holder.image=(ImageView)row.findViewById(R.id.image1);
             holder.txt=(TextView)row.findViewById(R.id.textlist);
              row.setTag(holder);
          }
          else
          {

              holder=(DataHolder)row.getTag();

          }

          Data_Class dc=data.get(position);
          holder.txt.setText(dc.data);

          Bitmap bm = decodeSampledBitmapFromUri(data.get(position).get_path(), 100, 100);
          holder.image.setImageBitmap(bm);


          return row;    


    }

    public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

          Bitmap bm = null;
          // First decode with inJustDecodeBounds=true to check dimensions
          final BitmapFactory.Options options = new BitmapFactory.Options();
          options.inJustDecodeBounds = true;
          BitmapFactory.decodeFile(path, options);

          // Calculate inSampleSize
          options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

          // Decode bitmap with inSampleSize set
          options.inJustDecodeBounds = false;
          bm = BitmapFactory.decodeFile(path, options);

          return bm;  
         }


    public int calculateInSampleSize(

            BitmapFactory.Options options, int reqWidth, int reqHeight) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;

            if (height > reqHeight || width > reqWidth) {
             if (width > height) {
              inSampleSize = Math.round((float)height / (float)reqHeight);   
             } else {
              inSampleSize = Math.round((float)width / (float)reqWidth);   
             }  
            }

            return inSampleSize;   
           }






    public class DataHolder
    {

        ImageView image;
        TextView txt;
    }

}

//在主要活动中

 private ListView listview1;
    private int check_view;
    private File targetDirectory;
    private File[] files;
    protected static  ArrayList<Data_Class> dataclass=new ArrayList<Data_Class>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    check_view = 0;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview_layout);
    listview1=(ListView)findViewById(R.id.List1);

    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    String targetPath = path + "/AppName/";

    targetDirectory = new File(targetPath);
    files = targetDirectory.listFiles();

      for(int i=0;i<files.length;i++)
      {
          dataclass.add(new Data_Class(files[i].getName(),files[i].getAbsolutePath()));
      }

      Data_Adapter adapter=new Data_Adapter(this,R.layout.img,dataclass);
      listview1.setAdapter(adapter);

      listview1.setClickable(true);
      listview1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // TODO Auto-generated method stub



        Data_Class mData_Class = (Data_Class)parent.getItemAtPosition(position);

        String path = mData_Class.get_path();



           if(path.contains(".jpg")){

               String path3 = path.substring(path.lastIndexOf("/") + 1);

               Intent intent = new Intent();
               intent.setAction(Intent.ACTION_VIEW);
               intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath()
                       + "/AppName/" + path3), "image/*");
               startActivity(intent);

               //Toast.makeText(ListviewActivity.this, path, Toast.LENGTH_LONG).show();

           }
                  if(path.contains(".pdf")){

               String path2 = path.substring(path.lastIndexOf("/") + 1);


               File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/AppName/" +  path2);
               Intent intent = new Intent(Intent.ACTION_VIEW);
               intent.setDataAndType(Uri.fromFile(file), "application/pdf");
               intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
               Intent intent2 = Intent.createChooser(intent, "Open File");
               try {
                   startActivity(intent2);

               } catch (ActivityNotFoundException e) {

                   Toast.makeText(ListviewActivity.this, "No pdf viewer found. Install one. ", Toast.LENGTH_LONG).show();
               }   


           }

        }

                  });


             }

  }

// Data_Class

public class Data_Class {

public String data;
public String pic;
public Data_Class()
{
    super();
}
public Data_Class(String d, String p)
{
    super();
    this.data=d;
    this.pic=p;
}

public String Get_Name()
{
    return data;
}

public String get_path()
{
    return pic;
}

void Set_Name(String s)
{
    data=s;

}

3 个答案:

答案 0 :(得分:0)

这样做是因为无论何时单击ListView项,都会调用getView()方法,因此无需再次添加。

yout getView()应该是这样的:

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

        View row=convertView;
        DataHolder holder=null;

        if(row==null)
        {
            LayoutInflater inflater= ((Activity)context).getLayoutInflater();
            row=inflater.inflate(ResourceLayoutId, parent, false);
            holder=new DataHolder();
            holder.image=(ImageView)row.findViewById(R.id.image1);
            holder.txt=(TextView)row.findViewById(R.id.textlist);
            row.setTag(holder);

            Data_Class dc=data.get(position);
            holder.txt.setText(dc.data);

            Bitmap bm = decodeSampledBitmapFromUri(data.get(position).get_path(), 100, 100);
            holder.image.setImageBitmap(bm);


          }
          else
          {

              holder=(DataHolder)row.getTag();

          }
          return row;    

    }

答案 1 :(得分:0)

我在上面发布的代码中找不到任何问题。

protected static  ArrayList<Data_Class> dataclass=new ArrayList<Data_Class>();

正如您已将“dataclass”声明为静态,请确保您不在代码的其他部分修改它。

答案 2 :(得分:0)

问题是列表视图中的先前数据在下次加载listview之前没有被清除。因此,每次活动加载时,我都会清除listview,如下所示。希望将来帮助某人。

 adapter.clear();
adapter.notifyDataSetChanged();