Android动态设置布局宽高

例如设置一个图片宽高 关键代码:

//取控件当前的布局参数
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView.getLayoutParams();
//设置宽度值
params.width = dip2px(MainActivity.this, width);
//设置高度值
params.height = dip2px(MainActivity.this, height);
//使设置好的布局参数应用到控件
imageView.setLayoutParams(params);

高度除了可以设置成以上固定的值,也可以设置成wrap_content或match_content

ViewGroup.LayoutParams.WRAP_CONTENT
ViewGroup.LayoutParams.MATCH_PARENT

xml



    

    

        

        

        

    

    

代码

public class MainActivity extends Activity implements View.OnClickListener {
    private EditText editWidth;
    private EditText editHeight;
    private ImageView imageView;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editWidth = findViewById(R.id.edit_width);
        editHeight = findViewById(R.id.edit_height);
        imageView = findViewById(R.id.img);
        button = findViewById(R.id.btn_change);

        button.setOnClickListener(this);
    }

    /**
     * dp转为px
     *
     * @param context  上下文
     * @param dipValue dp值
     * @return
     */
    private int dip2px(Context context, float dipValue) {
        Resources r = context.getResources();
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
    }

    @Override
    public void onClick(View view) {
        if (!TextUtils.isEmpty(editHeight.getText().toString()) && !TextUtils.isEmpty(editWidth.getText().toString())) {
            int width = Integer.parseInt(editWidth.getText().toString());
            int height = Integer.parseInt(editHeight.getText().toString());

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView.getLayoutParams();
            params.width = dip2px(MainActivity.this, width);
            params.height = dip2px(MainActivity.this, height);
            // params.setMargins(dip2px(MainActivity.this, 1), 0, 0, 0); // 可以实现设置位置信息,如居左距离,其它类推
            // params.leftMargin = dip2px(MainActivity.this, 1);
            imageView.setLayoutParams(params);
        } else {
            Toast.makeText(MainActivity.this, "请输入宽高!", Toast.LENGTH_LONG).show();
        }
    }
}

你可能感兴趣的:(Android从入门到放弃)