Android:找不到这个imageView?

时间:2015-03-17 20:07:18

标签: java android button imageview onclicklistener

我从输入流加载位图并将其放在imageview上。我有一个按钮,应该在位图上画一个圆圈。错误是在onClickListener中找不到imageview(称为' touch')...我该如何解决这个问题?当我按下按钮时没有任何反应。 (注意:ZoomInZoomOut类是Imageview的扩展)

    try {
        java.io.FileInputStream in = this.openFileInput(path);
        Bitmap bitmap = BitmapFactory.decodeStream(in);
        ZoomInZoomOut touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);
        touch = arrangeImageView(touch);
        touch.setImageBitmap(bitmap);
        in.close();
        Button draw = (Button) findViewById(R.id.draw);
        draw.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v)
            {
                Bitmap imageBitmap = Bitmap.createBitmap(200,
                    200, Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(imageBitmap);
                Paint p = new Paint();
                p.setAntiAlias(true);
                p.setColor(Color.BLUE);
                canvas.drawCircle(60, 50, 25, p);
             /////////////////////Error is on the next line:
                touch.setImageBitmap(imageBitmap);
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }

这是XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"     android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="@drawable/background"
tools:context="com.commonsware.android.test1.ImageDisplayActivity"
>


<com.commonsware.android.test1.ZoomInZoomOut
    android:id="@+id/IMAGEID"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"/>

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="o"
    android:id="@+id/draw"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />


</RelativeLayout>

1 个答案:

答案 0 :(得分:3)

触摸变量在另一个范围内定义。如果您想要更多解释,请查看此link

要解决您的问题,请更改您的代码:

final ZoomInZoomOut touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);

如果您以后需要从其他范围访问变量,也可以在类中创建变量:

private ZoomInZoomOut touch;

并实例化如下:

touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);