2 xiaoyan 12 xiaoyan_12 于 2013.09.05 14:09 提问

如何从 xml 中引用图像?

下面是程序中的 oncreate 方法:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    getWindow().setFormat(PixelFormat.UNKNOWN);
    surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    controlInflater = LayoutInflater.from(getBaseContext());
    View viewControl = controlInflater.inflate(R.layout.control, null);
    //ImageView img = (ImageView)controlInflater.
    LayoutParams layoutParamsControl 
        = new LayoutParams(LayoutParams.FILL_PARENT, 
        LayoutParams.FILL_PARENT);
    this.addContentView(viewControl, layoutParamsControl);
}

control.xml

<?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"
    android:gravity="center"
        >
<ImageView
    android:id="@+id/img"  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/ic_launcher"
    />
</LinearLayout>

如何从java代码中的 control.xml 中引用 ImageView?

2个回答

longhai326
longhai326   2013.09.05 15:03
已采纳

ImageView img = (ImageView)controlInflater.findViewById(R.id.img);

这样不行吗?看你的代码是在一个surfaceView上添加了layout,为何surfaceview要用layout
不太明白!

如果是SurfaceView一般是自己写一个类继承它,在canvas.drawBitmap(),就可以

之前也没有见过将SurfaceView 放在布局文件里面的

nana4ever
nana4ever   2013.09.05 15:19
View viewControl = controlInflater.inflate(R.layout.control, null);
ImageView img =(ImageView) viewControl.findViewById(R.id.img);

使用上面的代码来获取图像引用。

Csdn user default icon
上传中...
上传图片
插入图片