如何在java代码中编写这个xml

时间:2011-05-24 11:21:29

标签: java android xml

Android XML:

<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/hello"
android:layout_height="28dp" android:layout_width="180dp"
android:layout_toRightOf="@+id/signinemailtxt"
android:paddingLeft="50dp"
android:layout_marginTop="65dp"
android:background="#ffffff" 

/>

爪哇:

layout=  new  RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
TextView Txt=new TextView(this);
Txt.setText("Name");

如何在java代码中获取layout_marginTop,layout_toRightOf选项

3 个答案:

答案 0 :(得分:1)

  RelativeLayout layout = new RelativeLayout(this);
TextView tv1 = new TextView(this);
tv1.setText("A");

TextView tv2 = new TextView(this);
tv2.setText("B");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId());

layout.addView(tv1);        
layout.addView(tv2, lp);

答案 1 :(得分:1)

对于layout_margin:

LayoutParams params = new LayoutParams(context, attrs);
params.setMargins(0, 5, 0, 5); //setMargins (int left, int top, int right, int bottom)

Txt.setLayoutParams(params);

答案 2 :(得分:-1)

不要声明布局和文本视图的新实例,而是获取您在xml中创建的实例:

RelativeLayout layout = (RelativeLayout) findViewById(R.id.LayoutId);
TextView Txt = (TextView) findViewById(R.id.TextViewId);

现在您可以编辑您在屏幕上看到的布局和文本视图。