2014-12-14 3 views
1

Здравствуйте, я работаю над проектом, где мне нужно вставить каждый объект типа «Person» в ArrayList типа «Person» в Gridview в eclipse android. Мои намерения состоят в том, чтобы отобразить изображение вместе с именем Person (аналогично Instagram). Вот что я пробовал до сих пор, но это, похоже, не работает, как я хочу, и это трудно понять.Добавление объектов ArrayList в GridView в Android

У вас есть какие-нибудь лучшие решения? Класс

ArrayList<Person> dbPersons = dop.getPersons(dop); //This is where I populate my list 
int[] imageId = { 
      R.drawable.image1, 
      R.drawable.image2, 
      R.drawable.image3 
    }; 

      gridView = (GridView)findViewById(R.id.grid); 
      gridView.setAdapter(new function.CustomGrid(this, dbPersons, imageId)); 
      gridView.setOnItemClickListener(new OnItemClickListener() { 

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

       } 

      }); 

Мои персоны обычно содержит:

private String FName; 
private String LName; 
private String Biography; 

Во всяком случае, я не хочу, чтобы бомбардировать этот пост с моим неисправным кодом, так что я ищу уборщика и лучшей альтернативы. Я просто хочу отобразить имя в качестве заголовка элемента gridview и рисунка под ним и сделать то же самое для остальных объектов в arraylist. Не могли бы вы помочь мне ребята :)

+0

PLease проверить это 'http://www.javacodegeeks.com/2013/08/android-custom-grid-view-example-with-image-and-text.html' –

+0

@Jedil Я думаю, что ваша ссылка мертва .. но Benildus, вам нужен код, написанный для вас на основе вашей ситуации>? – Elltz

+0

@Elltz Не приятель, просто образец, похожий на мою ситуацию, будет достаточным. Тогда я смогу проложить себе путь. Мне просто нужен образец, в котором объекты gridList, содержащие объекты, заполняются в gridview :) – Pjayness

ответ

3

ваш адаптер

public class Benildus_Adapter extends ArrayAdapter<Person> { 

ArrayList<Person> list; // your person arraylist 
Context context; // the activity context 
int resource; // this will be your xml file 

public Benildus_Adapter(Context context, int resource,ArrayList<Person> objects) { 
    super(context, resource, objects); 
    // TODO Auto-generated constructor stub 
    this.list = objects; 
    this.context = context; 
    this.resource = resource; 
} 

@Override 
public int getCount() { 
    // TODO Auto-generated method stub 
    if(list.size() == 0){ 
     return 0; 
    }else{ 
     return list.size(); 
    } 
} 

@Override 
public View getView(final int position, View convertView, ViewGroup parent) { 
    // TODO Auto-generated method stub 
    View child = convertView; 
    RecordHolder holder; 
    LayoutInflater inflater = ((Activity) context).getLayoutInflater(); // inflating your xml layout 

    if (child == null) {    
     child = inflater.inflate(resource, parent, false); 
     holder = new RecordHolder(); 
     holder.fname = (TextView) child.findViewById(R.id.fname); // fname is the reference to a textview 
     holder.lname = (TextView) child.findViewById(R.id.lname); // in your xml layout file 
     holder.bio =(TextView) child.findViewById(R.id.bio); // you are inflating.etc 
     child.setTag(holder); 
    }else{ 
     holder = (RecordHolder) child.getTag(); 
    } 

    final Person user = list.get(position); // you can remove the final modifieer. 

    holder.fname.setText(user.getFName());  
    holder.lname.setText(user.getLName()); 
    holder.bio.setText(user.getBiography()); 
    holder.image.setImageBitmap(user.getImage()); // if you use string then you download the image using 
    // the string as url and set it to your imageview.. 
    return child; 
} 

static class RecordHolder { 
    TextView fname,lname,bio; 
    ImageView image;  
} 


@Override 
public void notifyDataSetChanged() { // you can remove this.. 
    // TODO Auto-generated method stub  
    if(getCount() == 0){ 
     //show layout or something that notifies that no list is in.. 
    }else{ 
     // this is to make sure that you can call notifyDataSetChanged in any place and any thread 
     new Handler(getContext().getMainLooper()).post(new Runnable() { 

      @Override 
      public void run() { 
       // TODO Auto-generated method stub 
       Benildus_Adapter.super.notifyDataSetChanged(); 
      } 
     }); 
    } 
} 

} 

Ваш человек класс

public class Person { 

private String FName; 
private String LName; 
private String Biography; 
private Bitmap image; // add the image too to your class, you can store the url of the image 
// or save it using bitmap.. if you store the url then = String image; the load the image 
// in the getview method.. any way you choose.. 
public String getFName() { 
    return FName; 
} 
public void setFName(String fName) { 
    FName = fName; 
} 
public String getLName() { 
    return LName; 
} 
public void setLName(String lName) { 
    LName = lName; 
} 
public String getBiography() { 
    return Biography; 
} 
public void setBiography(String biography) { 
    Biography = biography; 
} 
public Bitmap getImage() { 
    return image; 
} 
public void setImage(Bitmap image) { 
    this.image = image; 
} 

} 

Редактировать я просто забыть комплект адаптер ..

gridView = (GridView)findViewById(R.id.grid); 
Benildus_Adapter bA = new Benildus_Adapter(this, R.layout.myxml,dbPersons); 
gridView.setAdapter(bA); 

надеюсь, что это поможет, дайте мне знать

Смежные вопросы