动态设置view或布局的宽高

时间:2025-01-27 08:22:51
  • package ;  
  •   
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  •   
  • public class MainActivity extends Activity {  
  •       
  •     private EditText editWidth;  
  •     private EditText editHeight;  
  •     private ImageView imageView;  
  •     private Button button;  
  •       
  •   
  •     @Override  
  •     protected void onCreate(Bundle savedInstanceState) {  
  •         super.onCreate(savedInstanceState);  
  •         setContentView(.activity_main);  
  •         editWidth = (EditText) findViewById(.edit_width);  
  •         editHeight = (EditText) findViewById(.edit_height);  
  •         imageView = (ImageView) findViewById();  
  •         button    = (Button) findViewById();  
  •           
  •         (changeClickListener);  
  •           
  •     }  
  •       
  •     private OnClickListener changeClickListener = new OnClickListener() {  
  •         @Override  
  •         public void onClick(View v) {  
  •             if (() != null && () != null  
  •                     && !().toString().equals("")  
  •                     && !().toString().equals("")) {  
  •   
  •                 int width = (().toString());  
  •                 int height = (().toString());  
  •   
  •                  params = () ();  
  •                  = dip2px(MainActivity.this, width);  
  •                  = dip2px(MainActivity.this, height);  
  •                 // (dip2px(, 1), 0, 0, 0); // 可以实现设置位置信息,如居左距离,其它类推  
  •                 //  = dip2px(, 1);  
  •                 (params);  
  •   
  •             } else {  
  •                 (MainActivity.this"请输入宽高!", Toast.LENGTH_LONG).show();  
  •             }  
  •   
  •         }  
  •     };  
  •       
  •     /** 
  •      * dp转为px 
  •      * @param context  上下文 
  •      * @param dipValue dp值 
  •      * @return 
  •      */  
  •     private int dip2px(Context context,float dipValue)   
  •     {  
  •         Resources r = ();  
  •         return (int) (  
  •                 TypedValue.COMPLEX_UNIT_DIP, dipValue, ());  
  •     }  
  •       
  • }