【发布时间】:2020-06-18 15:31:38
【问题描述】:
我是 android 开发的新手,并且在单击多个按钮后使用共享偏好来展示广告。我有几个按钮(如下例所示),每个按钮都有不同的意图。下面我的单一逻辑的最佳实现是什么,这样我的代码对于所有其他具有不同意图的按钮都是 DRY(不要重复自己)。 我的适配器类扩展了 RecyclerView
public class ImageAdaptor extends RecyclerView.Adapter<ImageAdaptor.MyViewHolder> {
#####################################
######################################
########################################
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View v) {
MobileAds.initialize(acontext, "ca-app-pub-3940256099942544~3347511713");
final InterstitialAd mInterstitialAd = new InterstitialAd(acontext);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
//Here is my working example on first button
//I want to achieve something like this on other clicks with different intents
//I don't want to repeat the logic over and over again
**Button1**.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final ModelStatus modelStatus = arrayList.get(getAdapterPosition());
final Intent intent = new Intent(acontext, Activity1.class);
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
acontext.startActivity(intent);
}
});
SharedPreferences preferences = acontext.getSharedPreferences("PREFRENCE",
Context.MODE_PRIVATE);
int clickCount = preferences.getInt("KEY_CLICK_COUNT", 1);
if (clickCount % 6 == 0) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
acontext.startActivity(intent);
};
}else {
acontext.startActivity(intent);
}
clickCount++;
preferences.edit().putInt("KEY_CLICK_COUNT", clickCount).apply();
}
});
**Button2**.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(acontext, Activity2.class);
//Some code with an intent
// I want my logic to go in here for 5 clicks per ad.
// I don't want to repeat myself since i have several such
//buttons with a different intent
}
});
}
}
【问题讨论】:
标签: java android android-recyclerview admob dry