我的应用运行正常,但TextView不会出现

时间:2017-12-27 09:39:29

标签: java android

我正在制作我应用的首页。不幸的是,只有TextView赢了。按钮和背景运行得很好。我甚至将它添加到相对布局中但使用addView()函数。有人可以帮忙吗?

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

}
}

1 个答案:

答案 0 :(得分:3)

这是因为您在textview上方设置了button,其中textview首先位于根布局的首位,这就是为什么它没有显示尝试设置{{1}下方按钮和它的工作

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