How to programmatically align an Android TextView to the right of another TextView

前端 未结 2 1109
情歌与酒
情歌与酒 2020-12-18 13:50

In the below code I have created two text views and added them programmatically to a relative layout. I want to align them side by side.

The code runs fine but is n

相关标签:
2条回答
  • Just a guess: can you try to use a different id than 0 ?

    0 讨论(0)
  • 2020-12-18 14:12

    Try the following:

    1. Set the id of textView[0] to 1 instead of 0 (id needs to be a positive integer)
    2. Add to the relativeLayoutParams of textView[1] a rule for RelativeLayout.ALIGN_TOP

    The following worked for me:

    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);
    
    0 讨论(0)
提交回复
热议问题