如何以编程方式将Android TextView对齐到另一个TextView的右侧

时间:2012-09-02 17:26:13

标签: java android android-layout textview

在下面的代码中,我创建了两个文本视图,并以编程方式将它们添加到相对布局中。我希望将它们并排排列。

代码运行正常但未将新TextView放在上一个TextView的右侧,而新TextView位于边距(0,0,0,0),即屏幕右上角:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    relativeLayout= (RelativeLayout) findViewById(R.id.relative_Layout);

    textView[0] = new TextView(this);//creates first textview
    textView[0].setId(0);
    textView[0].setText("1");
    textView[0].setBackgroundResource(R.drawable.shape);//parses an image from shape.xml

    relativeLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
    textView[0].setLayoutParams(relativeLayoutParams);

    relativeLayout.addView(textView[0]);//creates another textview

    textView[1] = new TextView(this);

    textView[1].setBackgroundResource(R.drawable.shape);

    RelativeLayout.LayoutParams relativeLayoutParams=
            new RelativeLayout.LayoutParams((RelativeLayout.LayoutParams.WRAP_CONTENT),(RelativeLayout.LayoutParams.WRAP_CONTENT));//create params for new textview

    relativeLayoutParams.addRule(RelativeLayout.RIGHT_OF, textView[0].getId());//to align the textview side by side
    textView[1].setText("2");

    relativeLayout.addView(textView[1], relativeLayoutParams);

2 个答案:

答案 0 :(得分:8)

尝试以下方法:

  1. 将textView [0]的id设置为1而不是0(id需要为正整数)
  2. 将RelativeLayout.ALIGN_TOP的规则添加到textView [1]的relativeLayoutParams
  3. 以下对我有用:

    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.test);
    RelativeLayout.LayoutParams relativeLayoutParams;       
    TextView[] textView = new TextView[2];
    
    // 1st TextView
    textView[0] = new TextView(this);
    
    relativeLayoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    
    textView[0].setId(1); // changed id from 0 to 1
    textView[0].setText("1");   
    
    relativeLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
    
    relativeLayout.addView(textView[0], relativeLayoutParams);
    
    // 2nd TextView
    textView[1] = new TextView(this);
    
    relativeLayoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);      
    
    textView[1].setText("2");
    
    relativeLayoutParams.addRule(RelativeLayout.RIGHT_OF,
            textView[0].getId());
    relativeLayoutParams.addRule(RelativeLayout.ALIGN_TOP,
            textView[0].getId()); // added top alignment rule
    
    relativeLayout.addView(textView[1], relativeLayoutParams);
    

答案 1 :(得分:2)

只是一个猜测:你可以尝试使用不同于0的ID吗?