2

以下のコードでは、2つのテキストビューを作成し、それらをプログラムで相対レイアウトに追加しました。それらを並べて配置したいと思います。

コードは正常に実行されますが、新しい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);
4

2 に答える 2

8

次のことを試してください。

  1. textView [0]のIDを0ではなく1に設定します(idは正の整数である必要があります)
  2. textView[1]のrelativeLayoutParamsにRelativeLayout.ALIGN_TOPのルールを追加します

以下は私のために働いた:

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);
于 2012-09-02T18:11:12.870 に答える
2

推測:0以外のIDを使用してみてください。

于 2012-09-02T17:41:38.560 に答える