2015-04-12 83 views
-1

目前一切都是通过java代码完成的。我正在创建一个相对布局,然后将GL表面视图和一些文本视图添加到它。问题是我不能对齐一个文本视图左上角和右上角。我的代码有什么问题。还有一种更有效的方法,例如通过XML来完成此操作。因为我试过这个,但没有奏效。通过android java对齐textview

r1 = new RelativeLayout(this); 
    view = new MyGLSurfaceView(this); 
    view.setKeepScreenOn(true);//keeps activity from going to sleep 

    r1.addView(view); 
    TextView text1 = new TextView(this); 
    TextView text2 = new TextView(this); 
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 50); 
    RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 200); 
    lp.addRule(RelativeLayout.ALIGN_RIGHT); 
    text1.setLayoutParams(lp); 
    text1.setText("3 Star"); 
    text1.setBackgroundColor(0x4060ff70); 
    rp.addRule(RelativeLayout.ALIGN_LEFT); 
    text2.setLayoutParams(rp); 
    text2.setText("4 Star"); 
    text1.setTextSize(30); 
    text2.setTextSize(30); 
    //text2.setBackgroundColor(0x4060ff70); 
    r1.addView(text1); 
    r1.addView(text2); 

    setContentView(r1); 

回答

1

这可以在XML做到像这样:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Left" /> 

    <TextView 
     android:layout_alignParentTop="true" 
     android:layout_alignParentRight="true" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Right" /> 
</RelativeLayout> 
+0

怎么样的Java代码。我应该如何改变它,以便它引用这个xml文件 – will

+0

将XML文件放在res/layout中。然后'setContentView(R.layout.filename);' – Noob