如何使用CursorAdapter在Listview中实现Native express广告

时间:2017-06-09 12:31:00

标签: android listview android-cursoradapter google-admob native-ads

我有cursoradapter的listview。 现在我想在listview中实现原生快递广告。

我已经看到使用简单的baseAdapter实现原生广告,通常我们使用List<Object>将数据传递给适配器,并检查getView()方法中的项目类型以添加​​广告。

 @Override
public View getView(int position, View convertView, ViewGroup parent)
        throws IllegalArgumentException {
    Object item = getItem(position);

    if (item instanceof Listing) {
        // Listing items already have all the data required, so they just need to be displayed.
                  return listingLayout;
    } else if (item instanceof AdPlacement) {
        return ((AdPlacement) item).getView(convertView, parent);
    } else {
        // Any unknown items will cause exceptions, though this shouldn't ever happen.
        throw new IllegalArgumentException(
                String.format("Adapter can't handle getView() for list item of type %s",
                        item.getClass().getName()));
    }


}

如何在cursoradapter中检查这个条件,因为cursoradapter只有方法newItem()和光标细节

 @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View v = LayoutInflater.from(context).inflate(R.layout.list_item_station, parent, false);
        ViewHolder holder = new ViewHolder();

        v.setTag(holder);
        return v;
    }

如何在cursoradapter中每10个项目后添加原生广告

Bellow是我用于在列表中添加数据的当前代码。

public class StationsCursorAdapter extends CursorAdapter{


    public StationsCursorAdapter(Context context) {
        super(context, null, true);
            }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View v = LayoutInflater.from(context).inflate(R.layout.list_item_station, parent, false);
        ViewHolder holder = new ViewHolder();

        v.setTag(holder);
        return v;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.titleTextView.setText(cursor.getString(cursor.getColumnIndex(Station.NAME)));
    }

    private static final class ViewHolder {
               TextView titleTextView;
           }

}

3 个答案:

答案 0 :(得分:1)

实现查看项目类型另一个。您应该定义不同类型的布局和膨胀。看看RecyclerView Item Type

创建正确的View Inflating后,您可以检查OnBind方法中的类型,并为每个View实现另一种行为。

@Override
public void bindView(View view, Context context, Cursor cursor) {
    ViewHolder holder = (ViewHolder) view.getTag();
    if (holder instance of Dog) {
         // Handle one case
    } else {
         // Handle other case
    }
}

答案 1 :(得分:1)

创建文件list_item_native_ad.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="132dp">

    <com.google.android.gms.ads.NativeExpressAdView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/nativeAd"
        ads:adSize="FULL_WIDTHx132"
        ads:adUnitId="@string/native_ad_unit_id"/>
</LinearLayout>

在适配器中创建NativeAdViewHelper

public class NativeAdViewHolder extends RecyclerView.ViewHolder {

        private final NativeExpressAdView mNativeAd;

        public NativeAdViewHolder(View itemView) {
            super(itemView);
            mNativeAd = (NativeExpressAdView) itemView.findViewById(R.id.nativeAd);
            mNativeAd.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    super.onAdLoaded();
                    if (mItemClickListener != null) {
                        Log.i(TAG, "onAdLoaded");
                    }
                }

                @Override
                public void onAdClosed() {
                    super.onAdClosed();
                    if (mItemClickListener != null) {
                        Log.i(TAG, "onAdClosed");
                    }
                }

                @Override
                public void onAdFailedToLoad(int errorCode) {
                    super.onAdFailedToLoad(errorCode);
                    if (mItemClickListener != null) {
                        Log.i(TAG, "onAdFailedToLoad");
                    }
                }

                @Override
                public void onAdLeftApplication() {
                    super.onAdLeftApplication();
                    if (mItemClickListener != null) {
                        Log.i(TAG, "onAdLeftApplication");
                    }
                }

                @Override
                public void onAdOpened() {
                    super.onAdOpened();
                    if (mItemClickListener != null) {
                        Log.i(TAG, "onAdOpened");
                    }
                }
            });
            AdRequest adRequest = new AdRequest.Builder()
                    .addTestDevice(MainActivity.TEST_DEVICE_ID)
                    .build();
            //You can add the following code if you are testing in an emulator
            /*AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .build();*/
            mNativeAd.loadAd(adRequest);
        }
    }

在适配器中覆盖方法getItemViewType()

@Override
    public int getItemViewType(int position) {
        if (position>1 && position % 3 == 0) {//in your case replace % 3 with % 10.
            return NATIVE_AD_VIEW_TYPE;
        }
        return DEFAULT_VIEW_TYPE;
    }

覆盖方法getViewTypeCount()

@Override
public int getViewTypeCount() {
            return 2;
        }

newView()方法

@Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view;
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        switch (viewType) {
            default:
                view = layoutInflater
                        .inflate(R.id.content, parent, false);
                return new ViewHolder(view);
            case NATIVE_AD_VIEW_TYPE:
                view = layoutInflater.inflate(R.layout.list_item_native_ad, parent, false);
                return new NativeAdViewHolder(view);
        }
    }

bindView()方法

@Override
    public void bindView(View view, Context context, Cursor cursor) {
        if (!(holder instanceof ViewHolder)) {
            return;
        }
        holder.titleTextView.setText(cursor.getString(cursor.getColumnIndex(Station.NAME)));
    }

希望它会对你有所帮助!

答案 2 :(得分:1)

我建议你不要在这种情况下使用游标适配器,因为它效率低,而是应该将数据从Database提取到列表中,并使用CustomAdapter扩展BaseAdapter来相应地绑定视图。

如果您只需要使用游标适配器,那么您需要修改游标数据以在每第10个位置放置广告项目。您可以改变光标,如:

    public Cursor getModifiedCursorWithAds(Cursor cursor) {
        int size = cursor.getCount();
        MatrixCursor matrixCursor = new MatrixCursor(cursor.getColumnNames());
        int totalAds = size / 10;
        int negativeIds = -1;
        cursor.moveToFirst();
        //assuming only two columns in cursor
        for (int i = 0; i < (size + totalAds); i++) {
            if (i % 10 == 0 && i != 0) {
                matrixCursor.addRow(new String[]{"" + negativeIds--, "Ads data"}); //add dummy data for displaying ads(on the basis of negative ids, ad will be displayed
            } else {
                matrixCursor.addRow(new String[]{cursor.getString(0), cursor.getString(1)}); //add data from actual cursor, if you have more than 2 data modify this statement
                cursor.moveToNext();
            }
        }
        cursor.close();
        return matrixCursor;
    }

修改newView以返回广告和其他项目的不同视图,并在bindView回调中以相应方式绑定。

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view;
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        int viewType = cursor.getInt(0);
        if (viewType >= 0) {
            view = layoutInflater
                    .inflate(R.id.list_item_content, parent, false);
            ViewHolder holder = new ViewHolder();
            view.setTag(holder);
        } else {
            view = layoutInflater.inflate(R.layout.list_item_native_ad, parent, false);
            AdViewHolder holder = new AdViewHolder();

            view.setTag(holder);
        }
        return view;
    }

我没有测试过上面的代码,因此可能需要进行一些更改才能使其正常工作。