2015-01-23 3 views
0

Я создаю пользовательский ListView через базовый адаптер в качестве кода ниже. На самом деле мне нужно получить длину CustomListView. Спасибо за вашу любезную помощь в AdvanceКак сохранить все элементы CustomListView в массиве

public class ListViewWithBaseAdapter extends Activity { 

    public class codeLeanChapter { 
     String chapterName; 
     String chapterDescription; 
    } 
    CodeLearnAdapter chapterListAdapter; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_list_view_with_simple_adapter); 


     chapterListAdapter = new CodeLearnAdapter(); 

     ListView codeLearnLessons = (ListView)findViewById(R.id.listView1); 
     codeLearnLessons.setAdapter(chapterListAdapter); 

     codeLearnLessons.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
        long arg3) { 

       codeLeanChapter chapter = chapterListAdapter.getCodeLearnChapter(arg2); 

       Toast.makeText(ListViewWithBaseAdapter.this, chapter.chapterName,Toast.LENGTH_LONG).show(); 

      } 
     }); 
    } 

// ---------------------------------------------Adapter class Start from Here-------------------------------------------------------------- 
    public class CodeLearnAdapter extends BaseAdapter { 

     List<codeLeanChapter> codeLeanChapterList = getDataForListView(); 
     @Override 
     public int getCount() { 
      // TODO Auto-generated method stub 
      return codeLeanChapterList.size(); 
     } 

     @Override 
     public codeLeanChapter getItem(int arg0) { 
      // TODO Auto-generated method stub 
      return codeLeanChapterList.get(arg0); 
     } 

     @Override 
     public long getItemId(int arg0) { 
      // TODO Auto-generated method stub 
      return arg0; 
     } 

     @Override 
     public View getView(int arg0, View arg1, ViewGroup arg2) { 

      if(arg1==null) 
      { 
       LayoutInflater inflater = (LayoutInflater) ListViewWithBaseAdapter.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       arg1 = inflater.inflate(R.layout.listitem, arg2,false); 
      } 

      TextView chapterName = (TextView)arg1.findViewById(R.id.textView1); 
      TextView chapterDesc = (TextView)arg1.findViewById(R.id.textView2); 

      codeLeanChapter chapter = codeLeanChapterList.get(arg0); 

      chapterName.setText(chapter.chapterName); 
      chapterDesc.setText(chapter.chapterDescription); 

      return arg1; 
     } 

     public codeLeanChapter getCodeLearnChapter(int position) 
     { 
      return codeLeanChapterList.get(position); 
     } 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.list_view_with_simple_adapter, menu); 
     return true; 
    } 

    public List<codeLeanChapter> getDataForListView() 
    { 
     List<codeLeanChapter> codeLeanChaptersList = new ArrayList<codeLeanChapter>(); 

     for(int i=0;i<10;i++) 
     { 

      codeLeanChapter chapter = new codeLeanChapter(); 
      chapter.chapterName = "Chapter "+i; 
      chapter.chapterDescription = "This is description for chapter "+i; 
      codeLeanChaptersList.add(chapter); 
     } 

     return codeLeanChaptersList; 

    } 
} 
+0

Длина зрения пользовательского списка? –

+0

Это вернет вашу длину списка, если я правильно понимаю ваш вопрос. codeLeanChapterList.size(). – droidd

+0

На самом деле я сделал CustomListView, как указано выше. Мне нужно знать, сколько элементов доступно в моем ListView. Поэтому вопрос: «Как получить количество элементов в ListView и показать в Toast». Thats it –

ответ

1

Для BaseAdapter моего предложения заключается в использовании ViewHolder шаблона для создания элемента строки.

Если вы хотите получить общую длину списка, чем после установки данных или на основе размера списка, вы можете получить.

int totalListViewsize = adapter.getCount();

В ниже размещен код я упомянул комментарии в классе GetView и где его требуется

public class ListViewWithBaseAdapter extends Activity { 

     ListView listView; 
     public class codeLeanChapter { 
      String chapterName; 
      String chapterDescription; 
     } 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_list_view_with_simple_adapter); 
      listView = (ListView) findViewById(R.id.listView1); 
      ListViewCustomAdapter adapter = new ListViewCustomAdapter(this, 
        getDataForListView()); 
      listView.setAdapter(adapter); 
      listView.setOnItemClickListener(new OnItemClickListener() { 

       @Override 
       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
         long arg3) { 

        codeLeanChapter chapter = adapter.getItem(arg2); 

        Toast.makeText(ListViewWithBaseAdapter.this, chapter.chapterName,Toast.LENGTH_LONG).show(); 

       } 
      }); 
     int totalListViewsize = adapter.getCount(); 
} 

     public List<codeLeanChapter> getDataForListView() { 
      List<codeLeanChapter> codeLeanChaptersList = new ArrayList<codeLeanChapter>(); 

      for (int i = 0; i < 10; i++) { 

       codeLeanChapter chapter = new codeLeanChapter(); 
       chapter.chapterName = "Chapter " + i; 
       chapter.chapterDescription = "This is description for chapter " + i; 
       codeLeanChaptersList.add(chapter); 
      } 

      return codeLeanChaptersList; 

     } 

     private class ListViewCustomAdapter extends BaseAdapter { 
      Context context; 
      int totalDisplayDatasize = 0; 
      List<codeLeanChapter> codeLeanChapterList; 

      public ListViewCustomAdapter(Context context, 
        List<codeLeanChapter> codeLeanChapterList) { 
       this.context = context; 
       this.codeLeanChapterList = codeLeanChapterList; 
       if (this.codeLeanChapterList != null) 
        totalDisplayDatasize = this.codeLeanChapterList.size(); 
       System.out.println("Inside ListViewCustomAdapter "); 
      } 

      @Override 
      public int getCount() { 
       // this could be one of the reason for not showing listview.set 
       // total data length for count 
       return totalDisplayDatasize; 
      } 

      @Override 
      public codeLeanChapter getItem(int i) { 
       return this.codeLeanChapterList.get(i); 
      } 

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

      private class Holder { 
       TextView textView1, textView2; 
      } 

      @Override 
      public View getView(int position, View convertView, ViewGroup parent) { 
       Holder holder = null; 
       View view = convertView; 
       /* 
       * First time for row if view is not created than inflate the view 
       * and create instance of the row view Cast the control by using 
       * findview by id and store it in view tag using holder class 
       */ 
       if (view == null) { 
        holder = new Holder(); 
        ///No need to create LayoutInflater instance in 
        // constructor 

        convertView = LayoutInflater.from(this.context).inflate(
          R.layout.listitem, null); 

        holder.textView1 = (TextView) convertView 
          .findViewById(R.id.textView1); 
        holder.textView2 = (TextView) convertView 
          .findViewById(R.id.textView2); 

        convertView.setTag(holder); 
       } else { 
        /* 
        * Here view next time it wont b null as its created and 
        * inflated once and in above if statement its created. And 
        * stored it in view tag. Get the holder class from view tag 
        */ 
        holder = (Holder) convertView.getTag(); 

       } 
       holder.textView1.setText("chapterDescription : " 
         + codeLeanChapterList.get(position).chapterDescription); 
       holder.textView2.setText("chapterName : " 
         + codeLeanChapterList.get(position).chapterName); 
       return convertView; 
      } 
     } 
    } 
+0

@ Спасибо за работу –

+0

Я не могу ответить, потому что у меня нет достаточной репутации :( –