小编Mav*_*der的帖子

如何以编程方式将Android TextView对齐到另一个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);
Run Code Online (Sandbox Code Playgroud)

java android textview android-layout

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

android ×1

android-layout ×1

java ×1

textview ×1