목록 보기 항목의 보기는 화면에서 보기를 스크롤한 후 원래 상태로 돌아갑니다. (listview item's view returns to original state after scroll the view off the screen)


문제 설명

목록 보기 항목의 보기는 화면에서 보기를 스크롤한 후 원래 상태로 돌아갑니다. (listview item's view returns to original state after scroll the view off the screen)

I have button in listview item and when it's clicked horizontal progressbar start loading and when it is done loading two button should appear in that item in listview. While progressbar downloading if I scroll that item off the screen and then scroll it back, the progressbar disappeared and two buttons appeared. Downloading process works fine. But I wanna show the progressbar while its downloading all the time?  Here my adapter. Please any help. Thanks in advance  

@Override
public View getView(final int position, View convertView, ViewGroup parent) {   
    final ArrayList<String> array=JournalArray.get(position);
    LayoutInflater inflator = ((Activity) activity).getLayoutInflater();
    final Hashtable<Integer, Integer> hash = new Hashtable<Integer, Integer>();
    final Button imgAR;
    final Button imgPDF;
    final Button imgDown;
    final Button btnDel;
    final TextProgressBar progress;
    //ConnectionDetector cd=new ConnectionDetector(activity);
    final Database db=new Database(activity);
    //final ImageView imgViewFlag;
    //final TextView txtViewTitle,txtProgress;

    if(convertView==null)
    {
        convertView = inflator.inflate(R.layout.familylist_item, null);
    }       
        progress=(TextProgressBar)convertView.findViewById(R.id.downprogress);
        progress.setTextColor(Color.BLACK);
        //progress.setTag(tag)
        //progress.setVisibility(View.GONE);
        TextView txtViewTitle = (TextView) convertView.findViewById(R.id.text);
        //view.txtProgress=(TextView)convertView.findViewById(R.id.textProgress);
        ImageView imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);
         imgAR=(Button)convertView.findViewById(R.id.imageAR);
        //view.imgAR.setTag(view);
         imgDown=(Button)convertView.findViewById(R.id.imageDown);
        //view.imgDown.setTag(view);
         imgPDF=(Button)convertView.findViewById(R.id.imagePDF);
        //view.imgPDF.setTag(view);
        //view.progress=(ProgressBar)convertView.findViewById(R.id.downprogress);
        btnDel=(Button)convertView.findViewById(R.id.btnDel);
        //view.btnDel.setTag(view);
        //convertView.setTag(view);

    if(DeleteBin){
        if(XMLParser.CheckFileInSD(array.get(5))){
        btnDel.setVisibility(View.VISIBLE);
        imgAR.setVisibility(View.GONE);
        imgDown.setVisibility(View.GONE);
        imgPDF.setVisibility(View.GONE);
        progress.setVisibility(View.GONE);
        }
        else{
            imgDown.setVisibility(View.GONE);
            imgAR.setVisibility(View.GONE);
            btnDel.setVisibility(View.GONE);
            imgPDF.setVisibility(View.GONE);
            progress.setVisibility(View.GONE);
        }
    }
    else{
        btnDel.setVisibility(View.GONE);
        if(!XMLParser.CheckFileInSD(array.get(5))){
            imgAR.setVisibility(View.GONE);
            imgPDF.setVisibility(View.GONE);
            imgDown.setVisibility(View.VISIBLE);
            progress.setVisibility(View.GONE);
        }
        else{
            imgAR.setVisibility(View.VISIBLE);
            imgPDF.setVisibility(View.VISIBLE);
            imgDown.setVisibility(View.GONE);
            progress.setVisibility(View.GONE);
            }
        }

    txtViewTitle.setText(array.get(1));
    channelid=array.get(4);
    RelativeLayout.LayoutParams paramrel = new RelativeLayout.LayoutParams(width/5, height/5);
    paramrel.leftMargin = width/10;
    imgViewFlag.setLayoutParams(paramrel);
    imgViewFlag.setImageDrawable(Drawable.createFromPath(new File(array.get(3)).getAbsolutePath()));
    btnDel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            pos=position;
            Deletefiles(pos);
            Toast.makeText(activity, "Сэтгүүл амжилттай усгтгагдлаа", Toast.LENGTH_SHORT).show();
            btnDel.setVisibility(View.GONE);
        }
    });
    imgAR.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            channelid=array.get(4);
            Intent intent=new Intent(activity,ARELViewActivity.class);
            intent.putExtra("channelid", db.getConfigByChannelID(channelid));
            activity.startActivity(intent);
        }
    });
    imgPDF.setOnClickListener(new View.OnClickListener() {

        @SuppressLint("SdCardPath")
        @Override
        public void onClick(View v) {
            path=array.get(5);
            String PATH=Environment.getExternalStorageDirectory().getAbsolutePath()+ "/sdcard/.FamilyMagazine/";    
            openBook(PATH+XMLParser.getFileName(path));
        }
    });
    imgDown.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Database db=new Database(activity);
            final ConnectionDetector cd=new ConnectionDetector(activity);
            if(downloading<3){
            downloading++;

            path=array.get(5);
            channelid=array.get(4);
            pos=position;
            progress.setMax(100);
            progress.setProgress(0);
            progress.setVisibility(View.VISIBLE);
            imgDown.setVisibility(View.GONE);
            progress.setText("Татаж байна...");
            new AsyncTask<View, String, String>() {
                private View v;

                @Override
                protected String doInBackground(View... params) {
                    v = params[0];
                    int count;
                    isLoading=true;
                    //mprogress=progress;
                    String result="0";
                    if(cd.isConnectingToInternet()){
                        getChannel(channelid);
                        try {
                            URL url = new URL(path);
                            URLConnection conection = url.openConnection();
                            conection.connect();
                            // getting file length
                            lenghtOfFile = conection.getContentLength();

                            // input stream to read file ‑ with 8k buffer
                            InputStream input = new BufferedInputStream(url.openStream(), 8192);

                            String PATH="/mnt/sdcard/sdcard/.FamilyMagazine";
                            File dir=new File(PATH);
                            boolean test=dir.mkdirs();
                            OutputStream output = new FileOutputStream("/mnt/sdcard/sdcard/.FamilyMagazine/"+XMLParser.getFileName(path));
                            byte data[] = new byte[1024];

                            long total = 0;

                            while ((count = input.read(data)) != ‑1) {
                                total += count;
                                // publishing the progress....
                                // After this onProgressUpdate will be called
                                publishProgress(""+(int)((total*100)/lenghtOfFile));

                                // writing data to file
                                output.write(data, 0, count);
                                hash.put(pos, (int)((total*100)/lenghtOfFile));
                            }

                            // flushing output
                            output.flush();

                            // closing streams
                            output.close();
                            input.close();


                        } catch (Exception e) {
                            result=e.toString();
                        }
                        }
                    else
                        result="Интернетэд холбогдоогүй байна!";

                    return result;
                }
                protected void onProgressUpdate(String... progresses) {
                    // setting progress percentage
                progress.setProgress(Integer.parseInt(progresses[0]));
                int x=lenghtOfFile/100 * Integer.parseInt(progresses[0])/1048576;
                progress.setText(x+"MB / "+lenghtOfFile/1048576+"MB");
                }
                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    //view.txtProgress.setVisibility(View.GONE);
                    downloading‑‑;

                    isLoading=false;
                    if(result.equals("0")){
                        imgDown.setVisibility(View.GONE);
                        progress.setVisibility(View.GONE);
                        btnDel.setVisibility(View.GONE);
                        imgAR.setVisibility(View.VISIBLE);
                        imgPDF.setVisibility(View.VISIBLE);

                    }
                    else
                    {
                        Toast.makeText(activity, result, Toast.LENGTH_LONG).show();

                        imgDown.setVisibility(View.VISIBLE);
                        btnDel.setVisibility(View.GONE);
                        imgAR.setVisibility(View.GONE);
                        imgPDF.setVisibility(View.GONE);


                    }

         }
            }.execute(v);
            }
            else
                Toast.makeText(activity, "Өөр сэтгүүл татаж байна\n Түр хүлээнэ үү", Toast.LENGTH_LONG).show();
        }
    });

    return convertView;

}

참조 솔루션

방법 1:

I had experienced this problem. This is happening because Listview reuses the views(rows), it does not create views for all the rows, it only creates some rows which are visible on the screen and rest of the rows just reuse the created views.

The solution to your problem is to maintain the state of each row in some custom object(you can have an arraylist of these objects) and then in getView() method, restore the state of all the views from that object.  For example you can save the state of progressBar in this object as a boolean value. As soon as somebody press button, the object(corresponding to a particular row) should get updated with a 'true' boolean value. And every time in get view, state of progressbar should be set from this object.

This should solve your problem.

(by casperVipul J)

참조 문서

  1. listview item's view returns to original state after scroll the view off the screen (CC BY‑SA 3.0/4.0)

#android-progressbar #listviewitem #listview #android-asynctask #Android






관련 질문

목록 보기 항목의 보기는 화면에서 보기를 스크롤한 후 원래 상태로 돌아갑니다. (listview item's view returns to original state after scroll the view off the screen)

Android의 비동기 클래스에서 FTP 다운로드에 진행률 표시줄을 표시하는 방법은 무엇입니까? (How to show the progress bar in FTP download in async class in Android?)

Android에서 진행률 표시줄의 ListView (ListView of Progress Bars in android)

안드로이드에서 24시간 SeekBar 또는 ProgressBar를 만드는 방법 (How to create 24hour SeekBar or ProgressBar in android)

Android: ProgressBar가 활동에서 이상하게 보입니다. (Android: ProgressBar looks strange in activity)

Android에서 기본 ProgressDialog 원 색상을 변경하는 방법 (How to change default ProgressDialog circle color in android)

Android: 사이에 공백이 있는 맞춤 원 ProgressBar (Android: Custom circle ProgressBar with spaces in between)

정적 수평 진행률 표시줄 Android (Static horizontal progress bar android)

Android progressBar setVisibility()가 작동하지 않음 (Android progressBar setVisibility() not working)

비동기 작업의 게시 진행률 (Publishing progress in async task)

BaseActvity/BaseFragment의 ProgressBar 관리 (ProgressBar management in BaseActvity/BaseFragment)

진행 중인 경고 대화 상자가 닫히거나 취소되지 않음 (Alertdialog running ongoing dosen't dismiss or cancel)







코멘트