Asma Rahim Ali Jafri
Asma Rahim Ali Jafri

Reputation: 1373

My app runs fine but the TextView won't show up

I'm making this front page of my app. Unfortunately, only the TextView won't show. The button and the background run just fine. I have even added it to the relative layout but using the addView() function. Can someone please help?

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //layout
    RelativeLayout mainLayout = new RelativeLayout(this);
    mainLayout.setBackgroundColor(Color.BLUE);

    //button
    Button mainButton = new Button (this);
    mainButton.setText("Next");
    mainButton.setBackgroundColor(Color.RED);

    //textview
    TextView mainTextView = new TextView(this);
    mainTextView.setText("Juliet Daniel Lab Molecular Biology Cancer Research Center");
    mainTextView.setTextSize(30);
    mainTextView.setBackgroundColor(Color.GREEN);

    //sizing the button
    RelativeLayout.LayoutParams btnDetails = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT
    );
    //sizing the textview
    RelativeLayout.LayoutParams textViewDetails = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT
    );

    //give id's to position relatively...note it is preferable to do this in the res folder to avoid errors
    mainButton.setId(1);
    mainTextView.setId(2);

    //give rules to position widgets relatively
    textViewDetails.addRule(RelativeLayout.ABOVE, mainButton.getId());
    textViewDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
    textViewDetails.setMargins(0,0,0,50);


    //adding the button as a part of the RelativeLayout (ADDING THE BUTTON WIDGET TO LAYOUT)
    mainLayout.addView(mainButton, btnDetails);
    //adding the textview as a part of the relative Layout
    mainLayout.addView(mainTextView, textViewDetails);

    //setting the view as out layour
    setContentView(mainLayout);

}
}

Upvotes: 0

Views: 73

Answers (1)

Munir
Munir

Reputation: 2558

It's because you set textview above button where the button is first top of root layout that's why it's not showing try to set textview below button and it's work

textViewDetails.addRule(RelativeLayout.BELOW, mainButton.getId());

Upvotes: 3

Related Questions