【问题标题】:How to add to linear layout in java (without XML)如何在java中添加到线性布局(没有XML)
【发布时间】:2020-11-29 00:19:15
【问题描述】:

我想在线性布局(垂直)中添加一行文本

我想在java函数中添加它们

如何做到这一点?

【问题讨论】:

标签: android android-linearlayout


【解决方案1】:

要在 Java 中动态添加,如下所示: 线性布局 myLayout = new LinearLayout(MainActivity.this) ;

【讨论】:

    【解决方案2】:

    这样做:

    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    
    //add layout params
    LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    
    //add TextView inside the vertical LinearLayout
    TextView textView = new TextView(this);
    textView.setTextSize(16); //set the text size here
    textView.setTextColor(Color.BLACK); // set the text color here
    textView.setText("Texts"); // set the text here
    textView.setTypeface(Typeface.BOLD); // set the text style here
    linearLayout.addView(textView, p); // add the TextView to the LinearLayout
    

    您可以根据需要在LinearLayout 中添加任何视图。

    【讨论】:

      【解决方案3】:

      使用 addView :

      LinearLayout layoutCard  = new LinearLayout(getApplicationContext());
      TextView text = new TextView(getApplicationContext());
      text.setText("hello");
      layoutCard.addView(text);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多