如何以编程方式调整ImageView的大小?

时间:2015-01-26 09:59:06

标签: android

我是android的初学者,我在调整大小图像时遇到问题。图像尺寸每次都会改变(通过打印行检查),但不会出现在实际图像中。

我的代码:

   import android.os.Bundle;
    import android.app.Activity;
    import android.content.DialogInterface.OnClickListener;
    import android.view.Menu;
    import android.view.View;
    import android.view.animation.*;
    import android.widget.Button;
    import android.widget.ImageView;

    public class MainActivity extends Activity {

        public static int state = 2;
        public static ImageView image;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            image = (ImageView) findViewById(R.id.imageView1);

            final Button button2 = (Button) findViewById(R.id.button2);
            button2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    System.out.println("1- "+image.getLayoutParams().height+", "+image.getLayoutParams().width);
                    image.getLayoutParams().height += 20;
                    image.getLayoutParams().width += 20;
                    System.out.println("2- "+image.getLayoutParams().height+", "+image.getLayoutParams().width);
                }
            });
        }
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    }

1 个答案:

答案 0 :(得分:3)

您需要通知UI您的视图范围已更改。只需在image.requestLayout();方法下方添加此行println,它就可以运行:

       button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                System.out.println("1- "+image.getLayoutParams().height+", "+image.getLayoutParams().width);
                image.getLayoutParams().height += 20;
                image.getLayoutParams().width += 20;
                System.out.println("2- "+image.getLayoutParams().height+", "+image.getLayoutParams().width);
                image.requestLayout();
            }
        });