2012-03-07 53 views
-1

我需要学习用java代码而不是XML代码创建relativelayouts。如何用java代码创建relativelayouts?

例如,将是很好的了解如何构建这种XML使用Java代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
<Button 
     android:id="@+id/btnButton1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button 1"/> 
<Button 
     android:id="@+id/btnButton2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button 2" 
     android:layout_toRightOf="@+id/btnButton1"/> 
    <Button 
     android:id="@+id/btnButton3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button 3" 
     android:layout_below="@+id/btnButton1"/> 
</RelativeLayout> 

我无法找到与Java代码

请,可以有人帮忙做这个的任何实例我将该布局转换为java代码?或者可以有人给我教程链接来做java代码的相关布局?

感谢

回答

1

我希望这个代码帮助您实现RelativeLayout的编程

RelativeLayout.LayoutParams expandLayoutParams = new RelativeLayout.LayoutParams(
         RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); 
expandLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); 
expandLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
expandLayoutParams.topMargin=7; 
expandLayoutParams.rightMargin=7; 
expandButton.setLayoutParams(expandLayoutParams); 

一件事。你放的代码我不认为代表你想要实现的接口。为了让你想我想是的LinearLayout与方向等于水平,所有的按键更好地利用与layout_width = 0dip和layout_weight = 1

+0

您的代码不告诉我如何添加我需要的规则来实现我的布局... – NullPointerException 2012-03-07 12:14:48

+0

我试图学习创建简单的相关布局,因为这个我想要做相对布局的布局。 – NullPointerException 2012-03-07 12:17:13

1
//you create relative layout dynamically like below: 
public class TwoPicksOnEachOther extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Grabbing the Application context   
     final Context context = getApplication();     

     RelativeLayout relativeLayout = new RelativeLayout(this);     

     final ImageView iv = new ImageView(this);   
     iv.setImageResource(R.drawable.fish2); 


     RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(  
       RelativeLayout.LayoutParams.FILL_PARENT, 
       RelativeLayout.LayoutParams.FILL_PARENT); 
     relativeLayout.addView(iv,lp);   

     // Creating transparent image 
     final ImageView iv2 = new ImageView(this); 
     iv.setImageResource(R.drawable.ctdeasytwo); 
     RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(  
       RelativeLayout.LayoutParams.FILL_PARENT, 
       RelativeLayout.LayoutParams.FILL_PARENT); 
     relativeLayout.addView(iv2,lp2); 
     setContentView(relativeLayout); 

    }   

} 
+0

你的代码不告诉我如何添加我需要实现我的布局的规则... – NullPointerException 2012-03-07 12:14:10