android - TextView 未显示在 RelativeLayout 中

标签 android android-layout

<分区>

我正在尝试从 Java 动态构建 View ,但我很困惑为什么这不起作用。

TextView displayText 根本不显示在屏幕上。我不明白为什么它不会像上面那样用户输入他们的名字。

public class MainActivity extends AppCompatActivity {

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

        RelativeLayout ceriLayout = new RelativeLayout(this);

        Button genButton = new Button(this);
        genButton.setText("Press here");
        genButton.setId(0);

        TextView displayView = new TextView(this);
        displayView.setText("What is going to go here huh");
        displayView.setId(1);

        EditText nameView = new EditText(this);
        nameView.setText("Enter your name");
        nameView.setId(2);

        RelativeLayout.LayoutParams button = new  RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );

        RelativeLayout.LayoutParams name = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        RelativeLayout.LayoutParams display;
        display = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );

        button.addRule(RelativeLayout.CENTER_HORIZONTAL);
        button.addRule(RelativeLayout.CENTER_VERTICAL);

        display.addRule(RelativeLayout.CENTER_HORIZONTAL);
        display.addRule(RelativeLayout.ABOVE, nameView.getId());

        name.addRule(RelativeLayout.CENTER_HORIZONTAL);
        name.addRule(RelativeLayout.ABOVE, genButton.getId());



        ceriLayout.addView(genButton, button);
        ceriLayout.addView(nameView,name);

        setContentView(ceriLayout);

    }
}

最佳答案

您没有将 displayView 添加到您的 ceriLayout 中。这就是它没有出现的原因。

建议:请尝试学习在.xml 布局文件中编写您的View 组件,并将这些布局设置为 Activity 的内容 View 。

关于android - TextView 未显示在 RelativeLayout 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38860793/

相关文章:

Android MotionEvent.getActionIndex() 和多点触控

android - 图像 GridView 内部 fragment

Android:如何使滑动屏幕导航舒适

Android 应用布局在物理设备上崩溃

Android OpenGL ES 不绘制纹理

java - 无法解析示例 Google VR 项目中的依赖项

Android:使用 TYPE_APPLICATION_OVERLAY 的窗口类型 2038 的权限被拒绝

android - 如果 "Embedded Google assistant SDK"已被释放?

android - 回收者 View 中仅显示一项

android:dither ="true"不抖动,怎么了?