添加admob插页式广告具有图片(按钮),我希望当用户单击下载时,显示插页式广告,我留照片作演示用
https://i.stack.imgur.com/AdHDR.jpg
代码mainactivity.java
import static org.apache.commons.lang3.StringUtils.capitalize;
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
public static final int MY_PERMISSIONS_REQUEST_WRITE_STORAGE = 123;
private StoryAdapter recyclerViewAdapter;
private RecyclerView recyclerView;
private File[] files;
private InterstitialAd mInterstitialAd;
private SwipeRefreshLayout recyclerLayout;
Drawer resultDrawer;
AccountHeader headerResult;
public static final int ITEMS_PER_AD = 6;
ArrayList<Object> filesList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
super.onCreate(savedInstanceState);
setTheme(Constant.theme);
setContentView(R.layout.activity_main);
if (getAppIntro(this)) {
Intent i = new Intent(this, IntroActivity.class);
startActivity(i);
}
initComponents();
//Toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setBackgroundColor(Constant.color);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
boolean result = checkPermission();
if (result) {
setUpRecyclerView();
//addNativeExpressAds();
//setUpAndLoadNativeExpressAds();
}
ColorDrawable cd = new ColorDrawable(Constant.color);
Typeface typeface = Typeface.createFromAsset(getAssets(), "sintony-regular.otf");
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(cd)
.withSelectionListEnabledForSingleProfile(false)
.withAlternativeProfileHeaderSwitching(false)
.withCompactStyle(false)
.withDividerBelowHeader(false)
.withProfileImagesVisible(true)
.withTypeface(typeface)
.addProfiles(new ProfileDrawerItem().withIcon(R.mipmap.ic_launcher).withName(getResources().getString(R.string.app_name)).withEmail(getResources()
.getString(R.string.developer_email)))
.build();
resultDrawer = new DrawerBuilder()
.withActivity(this)
.withSelectedItem(-1)
.withFullscreen(true)
.withAccountHeader(headerResult)
.withActionBarDrawerToggle(true)
.withCloseOnClick(true)
.withMultiSelect(false)
.withTranslucentStatusBar(true)
.withToolbar(mToolbar)
.addDrawerItems(
new PrimaryDrawerItem().withSelectable(false).withName(R.string.app_name).withTypeface(typeface),
new PrimaryDrawerItem().withSelectable(false).withName("Gallery").withIcon(R.drawable.ic_home_black_24dp).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener()
{
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Intent intent = new Intent(MainActivity.this, GalleryActivity.class);
startActivity(intent);
return false;
}
}).withTypeface(typeface),
new PrimaryDrawerItem().withSelectable(false).withName("Recommend to Friends").withIcon(R.drawable.ic_share_black_24dp).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
final String shareappPackageName = getPackageName();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out " +getResources().getString(R.string.app_name) + " App at: https://play.google.com/store/apps/details?id=" + shareappPackageName);
sendIntent.setType("text/plain");
startActivity(sendIntent);
return false;
}
}).withTypeface(typeface),
new PrimaryDrawerItem().withSelectable(false).withName("Rate Us").withIcon(R.drawable.ic_thumb_up_black_24dp).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
final String appPackageName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
return false;
}
}).withTypeface(typeface),
new PrimaryDrawerItem().withSelectable(false).withName("Settings").withIcon(R.drawable.ic_settings_applications_black_24dp).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
return false;
}
}).withTypeface(typeface),
new PrimaryDrawerItem().withSelectable(false).withName("Feedback").withIcon(R.drawable.ic_feedback_black_24dp).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
PackageManager manager = getApplicationContext().getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String version = info.versionName;
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{getResources().getString(R.string.developer_email)});
i.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name) + version);
i.putExtra(Intent.EXTRA_TEXT,
"\n" + " Device :" + getDeviceName() +
"\n" + " System Version:" + Build.VERSION.SDK_INT +
"\n" + " Display Height :" + height + "px" +
"\n" + " Display Width :" + width + "px" +
"\n\n" + "Have a problem? Please share it with us and we will do our best to solve it!" +
"\n");
startActivity(Intent.createChooser(i, "Send Email"));
return false;
}
}).withTypeface(typeface),
new PrimaryDrawerItem().withSelectable(false).withName("Exit").withIcon(R.drawable.ic_exit_to_app_black_24dp).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
finish();
return false;
}
}).withTypeface(typeface)
).
withSavedInstance(savedInstanceState)
.build();
}
private boolean getAppIntro(MainActivity mainActivity) {
SharedPreferences preferences;
preferences = mainActivity.getSharedPreferences(Constants.MyPREFERENCES, Context.MODE_PRIVATE);
return preferences.getBoolean("AppIntro", true);
}
private String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
}
return capitalize(manufacturer) + " " + model;
}
private void initComponents() {
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRecyclerView);
recyclerLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
recyclerLayout.setRefreshing(true);
setUpRecyclerView();
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
recyclerLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, "Refreshed!", Toast.LENGTH_SHORT).show();
}
}, 2000);
}
});
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkPermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write Storage permission is necessary to Download Images and Videos!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void checkAgain() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write Storage permission is necessary to Download Images and Videos!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpRecyclerView();
} else {
checkAgain();
}
break;
}
}
private void setUpRecyclerView() {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerViewAdapter = new StoryAdapter(MainActivity.this, getData());
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
private ArrayList<Object> getData() {
StoryModel f;
String targetPath = Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.FOLDER_NAME + "Media/.Statuses";
File targetDirector = new File(targetPath);
files = targetDirector.listFiles();
if (files == null) {
// noImageText.setVisibility(View.INVISIBLE);
}
try {
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return -1;
} else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (int i = 0; i < files.length; i++) {
File file = files[i];
f = new StoryModel();
f.setName("Story Saver: "+(i+1));
f.setUri(Uri.fromFile(file));
f.setPath(files[i].getAbsolutePath());
f.setFilename(file.getName());
filesList.add(f);
}
} catch (Exception e) {
e.printStackTrace();
}
return filesList;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.ic_whatapp) {
Intent launchIntent = MainActivity.this.getPackageManager().getLaunchIntentForPackage("com.whatsapp");
startActivity(launchIntent);
finish();
}
return super.onOptionsItemSelected(item);
}
}
StoryAdapter.java
/**
* Created by Tushar on 9/1/2017.
*/
public class StoryAdapter extends RecyclerView.Adapter<StoryAdapter.ViewHolder> {
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final int NATIVE_EXPRESS_AD_VIEW_TYPE = 1;
private Context context;
private ArrayList<Object> filesList;
public StoryAdapter(Context context, ArrayList<Object> filesList) {
this.context = context;
this.filesList = filesList;
}
@Override
public StoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case MENU_ITEM_VIEW_TYPE:
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row,null,false);
return new ViewHolder(view);
case NATIVE_EXPRESS_AD_VIEW_TYPE:
default:
View nativeExpressLayoutView = LayoutInflater.from(
parent.getContext()).inflate(R.layout.native_express_ad_container,
parent, false);
return new NativeExpressAdViewHolder(nativeExpressLayoutView);
}
}
@Override
public void onBindViewHolder(StoryAdapter.ViewHolder holder, final int position) {
int viewType = getItemViewType(position);
switch (viewType){
case MENU_ITEM_VIEW_TYPE:
final StoryModel files = (StoryModel) filesList.get(position);
final Uri uri = Uri.parse(files.getUri().toString());
holder.userName.setText(files.getName());
if(files.getUri().toString().endsWith(".mp4"))
{
holder.playIcon.setVisibility(View.VISIBLE);
}else{
holder.playIcon.setVisibility(View.INVISIBLE);
}
Glide.with(context)
.load(files.getUri())
.into(holder.savedImage);
holder.downloadID.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkFolder();
final String path = ((StoryModel) filesList.get(position)).getPath();
final File file = new File(path);
String destPath = Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.SAVE_FOLDER_NAME;
File destFile = new File(destPath);
try {
FileUtils.copyFileToDirectory(file,destFile);
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(
context,
new String[]{ destPath + files.getFilename()},
new String[]{ "*/*"},
new MediaScannerConnection.MediaScannerConnectionClient()
{
public void onMediaScannerConnected()
{
}
public void onScanCompleted(String path, Uri uri)
{
Log.d("path: ",path);
}
});
Toast.makeText(context, "Saved to: "+ destPath + files.getFilename(), Toast.LENGTH_LONG).show();
}
});
break;
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
try{
NativeExpressAdViewHolder nativeExpressHolder =
(NativeExpressAdViewHolder) holder;
NativeExpressAdView adView =
(NativeExpressAdView) filesList.get(position);
ViewGroup adCardView = (ViewGroup) nativeExpressHolder.itemView;
if (adCardView.getChildCount() > 0) {
adCardView.removeAllViews();
}
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
// Add the Native Express ad to the native express ad view.
adCardView.addView(adView);
}catch (Exception e){
e.printStackTrace();
}
}
}
public void checkFolder() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.SAVE_FOLDER_NAME ;
File dir = new File(path);
boolean isDirectoryCreated = dir.exists();
if (!isDirectoryCreated) {
isDirectoryCreated = dir.mkdir();
}
if (isDirectoryCreated) {
Log.d("Folder", "Already Created");
}
}
@Override
public int getItemCount() {
return filesList.size();
}
public class NativeExpressAdViewHolder extends StoryAdapter.ViewHolder {
NativeExpressAdViewHolder(View view) {
super(view);
}
}
@Override
public int getItemViewType(int position) {
return (position % MainActivity.ITEMS_PER_AD == 0) ? NATIVE_EXPRESS_AD_VIEW_TYPE
: MENU_ITEM_VIEW_TYPE;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView savedImage;
ImageView playIcon;
ImageView downloadID;
public ViewHolder(View itemView) {
super(itemView);
userName = (TextView) itemView.findViewById(R.id.profileUserName);
savedImage = (ImageView) itemView.findViewById(R.id.mainImageView);
playIcon = (ImageView) itemView.findViewById(R.id.playButtonImage);
downloadID = (ImageView) itemView.findViewById(R.id.downloadID);
}
}
}
图片的ID为downloadID
非常感谢,我会发现任何新手解决方案,如果需要的话,我希望我能解决,因为我已经尝试了很长时间了,所以我不能