java - 类转换异常按钮无法转换为 Adview

标签 java android android-layout

我试图在执行 Activity 时在 AdsView 下方放置一个按钮 - download_btn。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/selected_imageview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_above="@+id/gallery_relative_layout"
            android:layout_marginLeft="30dip"
            android:layout_marginRight="30dip"
            android:layout_marginTop="30dip" />

        <RelativeLayout
            android:id="@+id/gallery_relative_layout"
            android:layout_width="fill_parent"
            android:layout_height="150dip"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/left_arrow_imageview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="15dip"
                android:src="@drawable/arrow_left_disabled" />

            <Gallery
                android:id="@+id/gallery"
                android:layout_width="0dip"
                android:layout_height="150dip"
                android:layout_marginLeft="20dip"
                android:layout_marginRight="20dip"
                android:layout_toLeftOf="@+id/right_arrow_imageview"
                android:layout_toRightOf="@+id/left_arrow_imageview"
                android:spacing="20dip" />

            <ImageView
                android:id="@+id/right_arrow_imageview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="15dip"
                android:src="@drawable/arrow_right_enabled" />

            <Button
                android:id="@+id/set_btn"
                android:layout_width="wrap_content"
                android:layout_height="35dip"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/right_arrow_imageview"
                android:onClick="onButtonClicked"
                android:text="Set as Wallpaper" />

            <com.google.ads.AdView
                android:id="@+id/adView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                ads:adSize="BANNER"
                ads:adUnitId="XXXXXXXXXXXX"
                ads:loadAdOnCreate="true" />

            <Button
                android:id="@+id/download_btn"
                android:layout_width="wrap_content"
                android:layout_height="35dip"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/adView"
                android:onClick="onDownloadButtonClicked"
                android:text="Load More Wallpaper" />
        </RelativeLayout>
    </RelativeLayout>

</LinearLayout>

编辑:下面是代码的 Activity :

public class GalleryDemoActivity extends Activity {

    public static final String COUNTURL = "http://wallpaper.hukumnama.in/sikhwallpaper.aspx";
    public static final String IMAGEURL = "XXXXXXXXXXXXX";
    public static final String DIRECTORYNAME = "XXXXXXXXXXXXXXXX";
    private ImageView selectedImageView;
    public static int networkCount =0;
    public static int dbCount =0;
    private ImageView leftArrowImageView;

    private ImageView rightArrowImageView;

    private Gallery gallery;
    Bitmap selectedImage =null;
    private int selectedImagePosition = 0;

    private List<Bitmap> drawables;
    MyDB db = null;
    private GalleryImageAdapter galImageAdapter;
    NetworkAccess networkAccess = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);          
        getDrawablesList();
        setupUI();
    }


    private void setupUI() {

        try{
        selectedImageView = (ImageView) findViewById(R.id.selected_imageview);
        leftArrowImageView = (ImageView) findViewById(R.id.left_arrow_imageview);
        rightArrowImageView = (ImageView) findViewById(R.id.right_arrow_imageview);
        gallery = (Gallery) findViewById(R.id.gallery);

        leftArrowImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (selectedImagePosition > 0) {
                    --selectedImagePosition;
                }

                gallery.setSelection(selectedImagePosition, false);
            }
        });

        rightArrowImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (selectedImagePosition < drawables.size() - 1) {
                    ++selectedImagePosition;

                }

                gallery.setSelection(selectedImagePosition, false);

            }
        });

        gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

                selectedImagePosition = pos;

                if (selectedImagePosition > 0 && selectedImagePosition < drawables.size() - 1) {

                    leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_enabled));
                    rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_enabled));

                } else if (selectedImagePosition == 0) {

                    leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_disabled));

                } else if (selectedImagePosition == drawables.size() - 1) {

                    rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
                }

                changeBorderForSelectedImage(selectedImagePosition);
                setSelectedImage(selectedImagePosition);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }

        });

        galImageAdapter = new GalleryImageAdapter(this, drawables);

        gallery.setAdapter(galImageAdapter);

        if (drawables.size() > 0) {

            gallery.setSelection(selectedImagePosition, false);

        }

        if (drawables.size() == 1) {

            rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
        }

        }catch(Exception e){
            System.out.println("Exception in setting up UI"+e);
        }
        AdView adView = (AdView)this.findViewById(R.id.adView);
        AdRequest adrequest = new AdRequest();
        adView.loadAd(adrequest);
    }

    private void changeBorderForSelectedImage(int selectedItemPos) {

        int count = gallery.getChildCount();

        for (int i = 0; i < count; i++) {

            ImageView imageView = (ImageView) gallery.getChildAt(i);
            imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.image_border));
            imageView.setPadding(3, 3, 3, 3);

        }

        ImageView imageView = (ImageView) gallery.getSelectedView();
        imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.selected_image_border));
        imageView.setPadding(3, 3, 3, 3);
    }

    private void getDrawablesList() {

        try{
        drawables = new ArrayList<Bitmap>();
        /* String ExternalStorageDirectoryPath = Environment
         .getExternalStoragePublicDirectory(Environment.getExternalStorageDirectory() + DIRECTORYNAME)
         .getAbsolutePath();
       */

       String ExternalStorageDirectoryPath =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+DIRECTORYNAME;
       String targetPath = ExternalStorageDirectoryPath ;

       Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
       File targetDirector = new File(targetPath);

       File[] files = targetDirector.listFiles();
       files = sortFiles(files, targetPath+"/");
       if(files!=null)
       {
       for (File file : files){
           System.out.println(file.getName());
           Bitmap bm = decodeSampledBitmapFromUri(file.getAbsolutePath(), 520, 520);
           drawables.add(bm); 

       }    
       }

       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image1)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image2)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image3)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image4)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image5)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image6)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image7)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image8)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image9)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image10)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image11)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image12)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image13)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image14)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image15)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image16)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image17)).getBitmap());
       drawables.add(((BitmapDrawable)getResources().getDrawable(R.drawable.image18)).getBitmap());
        }catch(Exception e){System.out.println("Exception in drawable list creation"+e);}
    }

     public int calculateInSampleSize(

             BitmapFactory.Options options, int reqWidth, int reqHeight) {
             // Raw height and width of image
             final int height = options.outHeight;
             final int width = options.outWidth;
             int inSampleSize = 1;

             if (height > reqHeight || width > reqWidth) {
              if (width > height) {
               inSampleSize = Math.round((float)height / (float)reqHeight);   
              } else {
               inSampleSize = Math.round((float)width / (float)reqWidth);   
              }   
             }

             return inSampleSize;   
            }
      public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
             Bitmap bm = null;

             // First decode with inJustDecodeBounds=true to check dimensions
             final BitmapFactory.Options options = new BitmapFactory.Options();
             options.inJustDecodeBounds = true;
             BitmapFactory.decodeFile(path, options);

             // Calculate inSampleSize
             options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

             // Decode bitmap with inSampleSize set
             options.inJustDecodeBounds = false;
             bm = BitmapFactory.decodeFile(path, options); 

             return bm;  
            }
    private void setSelectedImage(int selectedImagePosition) {


        selectedImage = drawables.get(selectedImagePosition);
        selectedImageView.setImageBitmap(selectedImage);
        selectedImageView.setScaleType(ScaleType.FIT_XY);

    }
    public void onButtonClicked(View view)
    {
        switch(view.getId())
        {
        case R.id.set_btn:
            System.out.println("On button clicked....Wallpaper");
             WallpaperManager wm = WallpaperManager.getInstance(this);
                try {
                    System.out.println("Hieght"+wm.getDesiredMinimumHeight());
                    System.out.println("width"+wm.getDesiredMinimumWidth());
                    wm.setBitmap(selectedImage);

                    Toast.makeText(this, "Wallpaper Set SuccessFully", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    System.out.println( "Cannot set image as wallpaper"+e);
                }

        }       
    }

    private File[] sortFiles(File[] inputFiles,String directoryName){

     ArrayList<Integer> fileNames = new ArrayList<Integer>();
     File[] sortedArray = new File[inputFiles.length];
     for(File f : inputFiles){
         if(f !=null){
         fileNames.add( Integer.parseInt(f.getName().replace(".jpg", "")));
         }
     }
        Collections.sort(fileNames);
        Collections.reverse(fileNames);
        for(int i=0; i<fileNames.size();i++){
            sortedArray[i] = new File (directoryName+fileNames.get(i)+".jpg");
        }
        return sortedArray;
    } 

}

请帮我一些指示。

谢谢

安缦

最佳答案

您应该将 AdView 移动到 LinearLayout 或其他内容中,然后引用有关此 LinearLayout 而不是 AdView 的 download_btn :

   <LinearLayout android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:id="@+id/LLadView">
        <com.google.ads.AdView
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ads:adSize="BANNER"
            ads:adUnitId="XXXXXXXXXXXX"
            ads:loadAdOnCreate="true" />
   </LinearLayout>
        <Button
            android:id="@+id/download_btn"
            android:layout_width="wrap_content"
            android:layout_height="35dip"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/LLadView"
            android:onClick="onDownloadButtonClicked"
            android:text="Load More Wallpaper" />

关于java - 类转换异常按钮无法转换为 Adview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24729551/

相关文章:

java - 什么是NullPointerException,我该如何解决?

java - 如何在 JavaFX 中将文本字段的选择边框设置为某种颜色?

android - 如何在整个主题中更改 AppBarLayout 的样式?

java - 泛型不兼容类型

java - eclipse:R.layout.start 不能是或不是字段

android - Android 上带计数器的应用程序图标

java - Android:SQLite 部分或完整单词搜索无法使用 SELECT 查询进行

android - 将 ListFragment 与带有 Holder 模式的 SimpleCursorAdapter 结合使用

android - 在 fragment 中动态添加 TextView

android - 如何设置android布局以支持所有屏幕尺寸?