getViewTypeCount&中的问题getItemViewType方法

时间:2012-11-26 07:06:51

标签: android android-listview admob baseadapter

我希望在列表视图的顶部插入广告,但是从admob提供的示例中,它在构造函数中使用BaseAdapter,而我使用ArrayList<Hashmap>因此我现在非常困惑请帮帮我。

public class ListAdapter extends BaseAdapter implements AdListener{

private static String admobId = null;
private Activity activity;
private ArrayList<HashMap<String, String>> data;

private static LayoutInflater inflater=null;

public ListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    this.activity = a;
    this.data = d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {
    return data.size()+1; //Adding one ads
}

public Object getItem(int position) {
    if (isItemAnAd(position)) {
        return null;
    }
    return data.get(getOffsetPosition(position));
}

public long getItemId(int position) {
    return position;
}

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

    if (isItemAnAd(position)) {
          if (vi instanceof AdView) {
            Log.d(LOGTAG, "I am reusing an ad");
            return vi;
          } else {
            Log.d(LOGTAG, "I am creating a new ad");
            AdView adView = new AdView(activity, AdSize.SMART_BANNER, getAdmobId(activity));
            AdRequest adRequestBanner = new AdRequest();
            adView.loadAd(adRequestBanner);
            return adView;
          }
    } else {

    vi = inflater.inflate(R.layout.listview, null);
    TextView subject = (TextView)vi.findViewById(R.id.subject);
    TextView permalink = (TextView)vi.findViewById(R.id.permalink);

    HashMap<String, String> map = new HashMap<String, String>();
    map = data.get(position);
     //Setting all values in listview

       subject.setText(map.get(ViewPagerAdapter.KEY_NEWS_SUBJECT));
       permalink.setText(map.get(ViewPagerAdapter.KEY_NEWS_PERMA));

    return vi;
        }
}

@Override
public int getViewTypeCount() {
 //what should i write here?
}

@Override
public int getItemViewType(int position) {
 //what should i write here?
}

//Ads
@Override
public boolean areAllItemsEnabled() {
  return false;
}

@Override
public boolean isEnabled(int position) {
  return (!isItemAnAd(position));
}

private boolean isItemAnAd(int position) {
  // Place an ad at the first 
  return (position == 0);
}

private int getOffsetPosition(int position) {
  return position - 1;
}
}

我应该在getViewTypeCount()&amp; getItemViewType()

更新:

@Override
public int getViewTypeCount() {
    return 2;
}
@Override
public int getItemViewType(int position) {
    if (isItemAnAd(position)) {
          return 0;
        } else {
          return 1;
        }
}

1 个答案:

答案 0 :(得分:4)

列表视图有两种行:广告行和普通行。所以getViewTypeCount应该返回2.让我们给广告行类型0和普通行类型1.如果getItemViewType为真,则isItemAnAd应返回0,否则返回1。