简体   繁体   English

为什么不能在Android的LinearLayout中添加TextView?

[英]Why can I not add a TextView to my LinearLayout in Android?

I am having a bunch of trouble adding a TextView to my LinearLayout. 我在将TextView添加到LinearLayout时遇到了很多麻烦。 Here is what I have: 这是我所拥有的:

activity_main.xml activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="some button text" />

</LinearLayout>

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main_layout);
        TextView textView = new TextView(this);
        textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        textView.setText("Hello, world!");

        mainLayout.addView(textView);
    }
}

I don't get any errors in LogCat, it just doesn't work. 我在LogCat中没有收到任何错误,但这是行不通的。

Any ideas? 有任何想法吗?

There is no space for your TextView because Button is taking them all. 因为Button将它们全部占用,所以TextView没有空间。

<Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="some button text" />

Change it to wrap_content 将其更改为wrap_content

Make sure the spacing between your views is correct 确保视图之间的间距正确

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some button text" />

</LinearLayout>

You can also try mainLayout.addView(newView, 0); 您也可以尝试mainLayout.addView(newView, 0); to add it before the button for verification 将其添加到验证按钮之前

Brian is right. 布莱恩是对的。 There is also an typo in the first line. 第一行也有错字。 I guess it should be android.com 我猜应该是android.com

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

and not android/com. 而不是android / com。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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