简体   繁体   中英

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);

}
}

这是因为您将textview设置在按钮上方,而该button位于根布局的顶部,这就是为什么它不显示的原因,请尝试将textview设置在按钮下方,这样就可以了

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM