【问题标题】:Create ImageView programmatically without Layout在没有布局的情况下以编程方式创建 ImageView
【发布时间】:2013-11-28 09:04:20
【问题描述】:

我正在尝试在代码中创建一个 ImageView,设置图像资源,然后将 ImageView 作为子视图添加到我的主视图中。我发现的所有示例都为此使用了布局。但是在我的视图的构造函数中,我不知道该怎么做。

这里是sn-ps的代码:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new CanvasView(this));

    }
}

观点:

public class CanvasView extends SurfaceView implements SurfaceHolder.Callback {
    public CanvasView(Context context) {
        super(context);

        SurfaceHolder sh = getHolder();
        sh.addCallback(this);

        ImageView iv = new ImageView(context);
        iv.setImageResource(R.drawable.wand);

        // how to add iv to myself?
    }
}

【问题讨论】:

  • 为什么是ImageView?可以直接使用SurfaceViewonDraw方法直接绘制Bitmap对。

标签: java android imageview surfaceview


【解决方案1】:

你不能这样做。两者都需要一个容器:例如

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyContainer(this));

    }
}

public class MyContainer extends LinearLayout {
  public MyContainer(Context context) {
    addView(new CanvasView(context));
    ImageView iv = new ImageView(context);
    iv.setImageResource(R.drawable.wand);
    addView(iv);
  }
}

请记住,如果您需要直接从所需的 xml 文件中扩充视图,对于 MyContainerCanvasView 的构造函数,其参数为 ContextAttributeSet

【讨论】:

  • 在这种情况下,ImageView 将填充我的 CanvasView?
  • 不,它没有。需要在SurfaceView里面画Bitmap吗?
  • 是的,这基本上就是我正在尝试的。但我也可以从 ImageView 而不是 SurfaceView 派生我的视图。
  • 或者你也可以覆盖 SurfaceView.draw 并使用 canvas.drawBitmap
  • 没错,这就是我目前正在尝试的;)
【解决方案2】:

这取决于您使用的布局,这里有一些代码,所有视图都是以编程方式创建的。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout rootLayout = new LinearLayout(getApplicationContext());
    rootLayout.setOrientation(LinearLayout.VERTICAL);

    ImageView imageView = new ImageView(getApplicationContext());
    imageView.setImageResource(R.drawable.sample);

    rootLayout.addView(imageView);

    setContentView(rootLayout);
}

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多