小编ste*_*ven的帖子

如何在Android中的自定义视图中显示ImageView

我有一个活动,当按下按钮时调用自定义视图。自定义视图运行良好,直到我尝试向其添加 ImageView 为止。我已经在我的 xml 中尝试过此操作,该 xml 在我的主要活动中使用 setContentView 进行调用:

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

<com.mypackage.mycustomview android:id="@+id/fbv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >

        <ImageView android:id="@+id/pistolView"
              android:src="@drawable/pistol"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"/> 

</com.mypackage.mycustomview> 
Run Code Online (Sandbox Code Playgroud)

当我单击主要活动中启动此自定义视图的按钮时,我收到 ClassCastException。我想做的就是在我的自定义视图中制作一个可点击的图像。

如果我将 ImageView 放入我的主要活动和 main.xml 中,它会显示良好并单击,如下所示:

<Button android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play Vs CPU" />


        <ImageView android:id="@+id/pistolView"
              android:src="@drawable/pistol"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"/> 
Run Code Online (Sandbox Code Playgroud)

我真的不擅长 android 中的 xml 布局,所以我不知道我在这里缺少什么。任何帮助是极大的赞赏。

这是 mycustomview 类:

       package com.mypackage;

    import java.util.ArrayList;

    import android.app.Activity;
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Point;
    import android.graphics.drawable.Drawable;
    import …
Run Code Online (Sandbox Code Playgroud)

android view imageview

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

android ×1

imageview ×1

view ×1