Android动态更改图像视图
全部。我有个问题。我想在按下按钮时调整图像的大小。 这是活动中的代码:Android动态更改图像视图,android,Android,全部。我有个问题。我想在按下按钮时调整图像的大小。 这是活动中的代码: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); currentImage = new ImageView(this); RelativeLayout.LayoutParams params
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
currentImage = new ImageView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(400, 400);
currentImage.setLayoutParams(params);
images = getResources().obtainTypedArray(R.array.images);
currentImage.setImageResource(R.drawable.bronar_jenson);
RelativeLayout l = (RelativeLayout)findViewById(R.id.layout);
l.addView(currentImage);
b = (Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentImage.getLayoutParams().width = 20;
}
});
}
不幸的是,它没有像我预期的那样工作-按钮没有调整大小。提前感谢。这应该可以:
替换:
currentImage.getLayoutParams().width = 20;
与:
你可能需要比你做更多的事情!但我有两个问题。第一个问题是:为什么如果我在xml文件中创建图片,在尝试您的代码后会出现异常-“视图已经有一个parrent”。这样它就可以工作了(当我动态地创建它时),但是当我静态地创建它时(在xml中),它就不工作了。第二个问题是:为什么当我试图在onCreate only(而不是listener)中修改图片时,它是有效的!但当我试图在listener中修改它时,它不会吗?这看起来很重要,我很感兴趣。提前谢谢你!我提供的回答适用于您在问题中提供的代码。我需要查看其他两种情况的代码(静态地在xml和listener中),以便提供答案?为什么我的方法不起作用,最重要的是——你是如何理解的?我的意思是我可以在不同的情况下尝试,但我不想每次都检查2或3个选项。currentImage.getLayoutParams()返回已在此视图上设置的只读值(getter)。它们不是要在运行时使用的setter。在currentImage.getLayoutParams()上方的问题代码中,width返回值400。updateViewLayout方法实际上删除了视图,并用新的布局参数替换了视图——在本例中,图像大小更改。
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(20, 400);
l.updateViewLayout(currentImage, params);