笔记 android 代码中设置Android:layout_gravity

  1. Button button  = new Button(this);  
  2. button.setText("One");  
  3. LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);  
  4. //此处相当于布局文件中的Android:layout_gravity属性  
  5. lp.gravity = Gravity.RIGHT;  
  6. button.setLayoutParams(lp);  
  7. //此处相当于布局文件中的Android:gravity属性  
  8. button.setGravity(Gravity.CENTER);  
  9.   
  10. LinearLayout linear = new LinearLayout(this);  
  11. //注意,对于LinearLayout布局来说,设置横向还是纵向是必须的!否则就看不到效果了。  
  12. linear.setOrientation(LinearLayout.VERTICAL);  
  13. linear.addView(button);  
  14. setContentView(linear);  

要设置在RelativeLayout中的位置时使用addRule方法
  1. params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
  2.         params.addRule(RelativeLayout.CENTER_IN_PARENT);  
  3.         mContainer.addView(progress,params);  

你可能感兴趣的:(Android)