2013-05-25 4 views
0

custom list view을 사용하고 있습니다. 각 행에는 두 개의 이미지보기와 텍스트보기가 있습니다. 나는 getView() 방법에서 view holdercustom adapter의 방법으로 사용하고 있습니다. getview() 방법의 이미지 뷰 중 하나에 Onclicklistener()을 설정 한 경우 onSelectItemListener()listview에만 있습니다. 이제 imageview을 클릭하면 특정 행에 영향을 미치지 만 아래로 스크롤하면 해당 클릭에 의해 임의의 행이 표시됩니다. 켜기를 클릭하면 일어납니다. viewholder을 사용하지 않을 때 이런 일이 발생하지 않습니다. 나는 이것이 왜 일어나는지를 알지 못한다. 도와주세요. 여기 ViewHolder를 사용하면 비정상적인 결과가 발생합니다.

getView() 방법의 내 코드입니다 :

public View getView(int position, View convertView, ViewGroup parent) { 
    final int myposition = position; 
    // TODO Auto-generated method stub 

    if (convertView == null) { 
     LayoutInflater inflater = LayoutInflater.from(context); 
     convertView = inflater.inflate(R.layout.fileviewrowfrnview_layout, null); 
     ViewHolder holder = new ViewHolder(); 
     holder.icon = (ImageView) convertView.findViewById(R.id.icon2); 
     holder.text = (TextView) convertView.findViewById(R.id.file_name2); 
     holder.download = (ImageView) convertView.findViewById(R.id.play_buttonOropen2); 
     convertView.setTag(holder); 
    } 
    final ViewHolder holder = (ViewHolder) convertView.getTag(); 


    holder.download.setOnClickListener(new View.OnClickListener() { 

     @ 
     Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if (frnshare_list.get(myposition).getFileType().trim() 
       .equalsIgnoreCase("file")) { 
       // it is file 
       if (frnshare_list.get(myposition).getDownloadStatus().trim() 
        .equalsIgnoreCase("0")) { 
        // is is not a downloaded file do download it 
        holder.icon.setVisibility(View.GONE); 
        holder.download.setVisibility(View.GONE); 
        holder.text.setTextSize(14); 

        Log.e("file to be download", "" + frnshare_list.get(myposition).getFileName()); 
        if (frnshare_list.get(myposition).getFileName().length() > 15) 
         holder.text.setText(frnshare_list.get(myposition).getFileName().subSequence(0, 15) + " will be downloaded soon."); 
        else 
         holder.text.setText(frnshare_list.get(myposition).getFileName() + " will be downloaded soon."); 
        UserService us = new UserService(context); 
        Frnshared fdto = frnshare_list.get(myposition); 
        fdto.setDownloadStatus("2"); // in queue 
        fdto.setMessageId("0"); 
        us.updateDowloadStatusById(fdto); 
        us.updatemsgIdbyId(fdto); 
        if (CommonUtility.isNetworkAvailable(context)) { 
         AsyncTask < Void, Void, Void > httpconnection = new AsyncTask < Void, Void, Void >() {@ 
          Override 
          protected Void doInBackground(Void...params) { 
           // TODO Auto-generated method stub 
           NetworkCommunication nc = new NetworkCommunication(
            context); 
           try { 
            UserService us = new UserService(
             context); 
            Frnshared fdto = frnshare_list 
             .get(myposition); 
            Log.i("file to be download", "" + fdto.getFileName()); 
            fdto.setDownloadStatus("2"); // in queue 
            fdto.setMessageId("0"); 
            us.updateDowloadStatusById(fdto); 
            us.updatemsgIdbyId(fdto); 
            String response = nc 
             .MyHttpPostDownload(frnshare_list 
             .get(myposition)); 
            ParsersAndDataInsertion.DownloadRequestResponseParser(
             response, context, 
             frnshare_list.get(myposition)); 

           } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
           } 
           // http call for download 
           return null; 
          } 
         }.execute(null, null, null); 
        } 
        Apitable(adto); 
       } 

      } else if (frnshare_list.get(myposition) 
       .getDownloadStatus().equalsIgnoreCase("1")) { 

       Intent intent = new Intent(); 
       intent.setAction(android.content.Intent.ACTION_VIEW); 
       File file = new File(frnshare_list.get(myposition) 
        .getFileLocation()); 
       intent.setDataAndType(Uri.fromFile(file), "audio/*"); 

       context.startActivity(intent); 

      } else if (frnshare_list.get(myposition) 
       .getDownloadStatus().equalsIgnoreCase("2")) { 
       Toast.makeText(context, "already request snet", 2000) 
        .show(); 
      } 
     } else if (frnshare_list.get(myposition).getFileType() 
      .equalsIgnoreCase("folder")) {} 

    } 
    }); 

// view purpose 


String file_name = frnshare_list.get(position).getFileName(); 
if (file_name.length() > 15) 
    holder.text.setText(file_name.substring(0, 15) + ""); 
else 
    holder.text.setText(file_name); // frn name 

try { 
    if (frnshare_list.get(myposition).getFileType() 
     .equalsIgnoreCase("file")) { // it is file 
     holder.icon.setImageResource(R.drawable.mp3_icon); 
     if (frnshare_list.get(myposition).getDownloadStatus() 
      .equalsIgnoreCase("0")) { 
      Log.i("file is ", "" + frnshare_list.get(myposition).getFileName()); 
      holder.download.setImageResource(R.drawable.download_png); 
     } else if (frnshare_list.get(myposition).getDownloadStatus() 
      .equalsIgnoreCase("1")) { 

     } else if (frnshare_list.get(myposition).getDownloadStatus() 
      .equalsIgnoreCase("2")) { 
      Log.i("file is in queue", "" + frnshare_list.get(myposition).getFileName()); 
      holder.icon.setVisibility(View.GONE); 
      holder.download.setVisibility(View.GONE); 
      holder.text.setTextSize(14); 
      if (frnshare_list.get(myposition).getFileName().length() > 15) 
       holder.text.setText(frnshare_list.get(myposition).getFileName().substring(0, 1); 
      else 
       holder.text.setText(frnshare_list.get(myposition).getFileName()); 
     } 
    } else if (frnshare_list.get(myposition).getFileType() 
     .equalsIgnoreCase("folder")) { 
     holder.icon.setImageResource(R.drawable.folder); 

    } 
} catch (Exception e) { 
    // TODO: handle exception 
    Intent i = new Intent(context, TabViewActivity.class); 
    i.putExtra("show", "frntab"); 
    context.startActivity(i); 

    BugSenseHandler.sendException(e); 
    e.printStackTrace(); 
} 


return convertView; 
} 
+0

홀더에 대한 논리에 오류가있을 수 있습니다. 그래도 문제를 해결하려면 코드를 게시해야합니다. –

+0

http://stackoverflow.com/questions/16726535/find-clicked-row-in-listview-and-get-data/16726623#16726623 –

+0

@GabeSechan 선생님. 내 코드 –

답변

2

내가 코드를 보았다, 그리고 여러 번 같은 날 자신의 코드는, 여기

if(position==1){ 

//here change color or hide view 

holder.someView.setVisibility(View.Invisible); 

holder.someView.setColor ==== green; //forgive me abt syntx 

}else{ 

//Here in else part it is important that you must reverse above things 
//so that when you scroll list, GREEN color do not show up in random rows 

holder.someView.setVisibility(View.Visible); 

holder.someView.setColor ==== red; //forgive me abt syntx 

} 

//same is for on click listener etc 
+1

을 절대적으로 추가했습니다. Upvoted 많은 사람들이 이것을 잊지 coz. –

+0

@Syed Zahid 알리 : 나는 그것을했다. 내 코드에서 세 가지 상태 0,1,2를 확인하고 이에 따라보기가 바뀌지 만 영향을 미치지 않는다. ( –

+0

@Sneha 예,하지만 위치 0 당신은 holder.icon.setVisibility (View.GONE)을 가지고 있고 다른 부분에서는 아이콘 상태를 visible로 변경하지 않았습니다. 따라서 일반적으로 코드를 검토해야합니다. – Androider

0

당신은 비동기를하고있는 내 제안이다 ListView의 작업을 종료합니다. 그것은 문제를 요구하고 있습니다. ListView는 행을 재활용합니다. 따라서 작업이 끝날 때까지는 작업이 시작될 때와 완전히 다른 위치를 실제로 가리킬 수 있습니다. 매우 조심해야하며 비동기 작업이 UI에 아무런 영향을 미치지 않도록하십시오. 목록 전체를 변경하지 않고 전체 목록을 강제로 다시 작성하거나 클릭 한 행을 절대 가정하지 않아야합니다. 버튼이 클릭되었을 때 행에 어떤 위치가 있었는지를 알고 있고 지금 어떤 행을 업데이트해야하는지 파악합니다.

기본적으로 가능한 경우 AsyncTasks를 사용하지 마십시오. 할 수 없다면, AsyncTask가 UI (notifyDataSetChanged 호출을 제외하고)를 건드리지 않아야하고, 작업 과정에서 필요한 모든 데이터 (예를 들어 파일 이름이 저장되는 것처럼)가 로컬로 복사되는지 확인해야합니다 생성 된 시간에 AsyncTask의 멤버 변수이며 행 뷰에서 읽지 않습니다.

+0

비동기 작업에 내가 데이터베이스에서 상태를 업데이 트하고있어 어떤보기도 바뀌지 않고 –

0

나는 당신의 코드를 구현하는 일반적인 방법이라고 생각한다. 당신이 할 수있는 일

당신이 방법을 직접 받고 위치의 1. - 당신이 얻을 일단, 당신의 홀더에 이미 설정 내용을 재사용하는 대신 다시 그리기 2의 순서로 shoould 보유자가 전환보기에서 다른 데이터 소스의 콘텐츠를 List<<>>과 같이 설정하면보기를 다시 만들 때 시간을 절약 할 수 있고 콘텐츠는 다른 데이터 소유자에 저장됩니다.

+0

@ rock_win 선생님은 내가 안드로이드에서 더 신선해서 나를 위해 복잡해지고있다. 당신이 할 수 있다면 도움이 될 것이다. 예를 들어주세요.: –

+0

TextView 및 ImageView에 설정하는 비트 맵 및 문자열 참조 다른 데이터 형식이므로 모든 행 항목에 대해이 데이터에 대한 엔티티 모델을 따로 가질 수 있으며이를 'List'유형 홀더가 제공하는 모든 도움은 레이아웃을 다시 팽창시킬 필요가 없다는 것입니다. 그래서 일단 홀더를 얻으면 목록을 사용하고 인자로 가져온'position'을 사용하십시오 데이터 및 홀더에서'Views' 설정하십시오. 그 이후로 당신이 방법에서 돌아 오는 궁극적 인 것. 자세한 내용은 또한 참조 할 수 있습니다 ... –

+0

Google IO 이야기 ListViews에 - 나는 그것이 있었다고 생각한다. 2010. –

관련 문제