Search code examples
javaandroidandroid-layoutandroid-relativelayout

How can i display programmatically a textview next to a button in a RelativeLayout in Android?


I have created a RelativeLayout which contains a Button and a TextView. With this code, the TextView is displayed above the Button. What can i do, to align the Button left and the TextView right? What is missing? This is my code:

    final RelativeLayout topRelativeLayout = new RelativeLayout(this);
    RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    topRelativeLayout.setLayoutParams(relativeLayoutParams);
    mainLinearLayout.addView(topRelativeLayout);

    final Button restartButton = new Button(this);
    restartButton.setText(R.string.restartButton);
    LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    restartButton.setLayoutParams(buttonParams);
    restartButton.setGravity(Gravity.LEFT);
    topRelativeLayout.addView(restartButton);

    final TextView timeTextView = new TextView(this);
    timeTextView.setText(R.string.timeTextView);
    timeTextView.setGravity(Gravity.RIGHT);
    topRelativeLayout.addView(timeTextView);

Thanks!


Solution

  • Try this

    RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    buttonParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    button.setLayoutParams(buttonParams);
    
    RelativeLayout.LayoutParams textviewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    textviewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
    textView.setLayoutParams(textviewParams);