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

如何在Android的自定义视图中显示ImageView,android,view,imageview,Android,View,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"

我有一个活动,当按下按钮时调用自定义视图。在我尝试向其添加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> 

当我单击主活动中启动此自定义视图的按钮时,我得到一个ClassCastException。我只想在我的自定义视图中创建一个可点击的图像

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


我真的不擅长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 android.os.Handler;
    import android.os.Message;
    import android.text.format.Time;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    public class mycustomview extends View{
            final Paint mPaint = new Paint();
            private Context mContext;
            private Resources res = getResources();
            private GameControls _controls;
            private GameJoystick _joystick;
            private GameJoystick Rjoystick;
            Paint paint = new Paint();
            private long currTime;
            private Time time = new Time();
            private Hero mHero;
            private Gun mGun;
            private Bitmap heroBit;
            private float possibleX;
            private float possibleY;
            private float lazerX;
            private float lazerY;
            public ArrayList<Wall> wallList = new ArrayList<Wall>();
            private Canvas mCanvas;
            private Bitmap splat;
            private Bitmap pistolBit;
            private Bitmap building;
            private ImageView pistol;
            private int i = 0;
            private int w = 0;
            Wall wall;

            private RefreshHandler mRedrawHandler = new RefreshHandler();

        class RefreshHandler extends Handler {

            @Override
            public void handleMessage(Message msg) {
                    //Log.d("3", "here3");
                FanBoyView.this.update();
                FanBoyView.this.invalidate();
            }

            public void sleep(long delayMillis) {
                    this.removeMessages(0);
                sendMessageDelayed(obtainMessage(0), delayMillis);
            }
        };


        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            //Log.d("-------------------->code", Integer.toString(keyCode));
            if (keyCode == KeyEvent.KEYCODE_FOCUS) {
                    //Log.d("-------------------->cam", "pressed");
              fireGun();
              return true;
            }
            return false;
         }

            public mycustomview(Context context, AttributeSet a) {
                    super(context, a);
                    mContext = context;

                    time.setToNow();
                    currTime = time.toMillis(false);
                    this.setFocusable(true);
                    this.setFocusableInTouchMode(true);
                    this.requestFocus();

                    final Paint paint = mPaint;
            paint.setColor(0xffffffff);
            paint.setAntiAlias(true);
            paint.setStrokeWidth(1);
            paint.setStrokeCap(Paint.Cap.ROUND);
            paint.setStyle(Paint.Style.STROKE);

                    setFocusable(true);

                    _joystick = new GameJoystick(mContext.getResources());
                    Rjoystick = new GameJoystick(mContext.getResources());
                    _controls = new GameControls();
                    setOnTouchListener(_controls);

                    Drawable bg = res.getDrawable(R.drawable.street);
                    this.setBackgroundDrawable(bg);
            setWalls();
            }

            @Override
            protected void  onFinishInflate(){
                    //ImageView img = (ImageView) findViewById(R.id.pistolView);
                    /*img.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            Log.d("pistol","clicked");
                        }
                    });*/
            }
...
package com.mypackage;
导入java.util.ArrayList;
导入android.app.Activity;
导入android.content.Context;
导入android.content.res.Resources;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.Canvas;
导入android.graphics.Paint;
导入android.graphics.Point;
导入android.graphics.drawable.drawable;
导入android.os.Handler;
导入android.os.Message;
导入android.text.format.Time;
导入android.util.AttributeSet;
导入android.util.Log;
导入android.view.KeyEvent;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.widget.ImageView;
导入android.widget.LinearLayout;
导入android.widget.TextView;
公共类mycustomview扩展了视图{
最终油漆mPaint=新油漆();
私有上下文;
私有资源res=getResources();
私人游戏控制(u控制),;
私人游戏操纵杆;
私人游戏杆;
油漆=新油漆();
私人长时间;
私人时间=新时间();
私人英雄姆赫罗;
私人枪支管理局;
私有位图位;
私人浮动可能性;
可能的私人浮动;
私人浮动拉泽克斯;
私人游船旅馆;
public ArrayList wallList=new ArrayList();
私人帆布mCanvas;
私有位图splat;
私有位图位;
私人大厦;
私人影像手枪;
私有整数i=0;
私有int w=0;
墙;
private RefreshHandler mRedrawHandler=新的RefreshHandler();
类RefreshHandler扩展处理程序{
@凌驾
公共无效handleMessage(消息消息消息){
//日志d(“3”,“此处为3”);
FanBoyView.this.update();
FanBoyView.this.invalidate();
}
公共无效睡眠(长延迟毫秒){
此.removeMessages(0);
sendMessageDelayed(获取消息(0),delayMillis);
}
};
@凌驾
公共布尔onKeyDown(int-keyCode,KeyEvent事件){
//Log.d(“----------------------->code”,Integer.toString(keyCode));
if(keyCode==KeyEvent.keyCode\u焦点){
//Log.d(“------------------>凸轮”,“按下”);
火枪();
返回true;
}
返回false;
}
公共mycustomview(上下文,属性集a){
超级(上下文,a);
mContext=上下文;
time.setToNow();
currTime=time.toMillis(false);
此参数为.setFocusable(true);
此.setFocusableInTouchMode(true);
this.requestFocus();
最终油漆=mPaint;
paint.setColor(0xffffffff);
paint.setAntiAlias(真);
油漆。设置行程宽度(1);
油漆固定行程盖(油漆固定行程盖圆形);
绘制.设置样式(绘制.样式.笔划);
设置聚焦(真);
_操纵杆=新游戏操纵杆(mContext.getResources());
Rjoystick=新游戏操纵杆(mContext.getResources());
_控件=新游戏控件();
setOnTouchListener(_控件);
可提取bg=res.getDrawable(R.Drawable.street);
本工程为可退耕(bg);
设置墙();
}
@凌驾
充气时受保护的空隙(){
//ImageView img=(ImageView)findViewById(R.id.VIEW);
/*setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
Log.d(“手枪”,“咔哒声”);
}
});*/
}
...

因为视图不能有子视图,所以您得到了ClassCastException,添加子视图是为了视图组

ImageView和TextView是普通视图,而LinearLayout和ListView是视图组。因此,后者可以有子视图,而前者不能


您可以只扩展视图组而不是视图,并进行必要的调整,但在我看来,您应该使用相对布局,将自定义视图放在底部,将imageview放在顶部。

首先,正如李周所说,您需要使您的类从视图组扩展到相对布局、线性布局

public class CustomView extends RelativeLayout {
Context context;
private ImageView imgView;
private TextView lblView;
LayoutInflater inflater;
/*Do I need all three constructors for an Android custom view?*/

//if you add your View from xml and also spcify the android:style attribute like : <com.mypack.MyView style="@styles/MyCustomStyle" />
//you will also need the first constructor public MyView(Context context, AttributeSet attrs,int defStyle)
public CustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
    init();
}
//you will need the constructor public MyView(Context context, AttributeSet attrs), otherwise you will get an Exception when Android tries to inflate your View.
public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    init();
}

//The third constructor is usually used when you extend a style and customize it, and then you would like to set that style to a given View in your layouts
public CustomView(Context context) {
    super(context);
    this.context = context;
    init();
}



public void init()
{
    LayoutInflater.from(context).inflate(R.layout.widget_customview_main, this);
    lblView =(TextView) findViewById(R.id.lblView);
    imgView = (ImageView) findViewById(R.id.imgView);
}
公共类CustomView扩展了RelativeLayout{
语境;
私有图像视图imgView;
私有文本视图lblView;
充气机;
/*Android自定义视图是否需要所有三个构造函数*/
//如果您从xml添加视图,并指定android:style属性,如:
//您还需要第一个构造函数publ
public class CustomView extends RelativeLayout {
Context context;
private ImageView imgView;
private TextView lblView;
LayoutInflater inflater;
/*Do I need all three constructors for an Android custom view?*/

//if you add your View from xml and also spcify the android:style attribute like : <com.mypack.MyView style="@styles/MyCustomStyle" />
//you will also need the first constructor public MyView(Context context, AttributeSet attrs,int defStyle)
public CustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
    init();
}
//you will need the constructor public MyView(Context context, AttributeSet attrs), otherwise you will get an Exception when Android tries to inflate your View.
public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    init();
}

//The third constructor is usually used when you extend a style and customize it, and then you would like to set that style to a given View in your layouts
public CustomView(Context context) {
    super(context);
    this.context = context;
    init();
}



public void init()
{
    LayoutInflater.from(context).inflate(R.layout.widget_customview_main, this);
    lblView =(TextView) findViewById(R.id.lblView);
    imgView = (ImageView) findViewById(R.id.imgView);
}
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
class = "com.ikolmobile.satso."
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/lblView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="60dp"
    android:text="My Custom View" />

<ImageView
    android:id="@+id/imgView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="31dp"
    android:src="@drawable/abc_ab_bottom_solid_dark_holo" />

</RelativeLayout>