为什么我不能一个TextView添加到我的Android中的LinearLayout?
我有一堆添加一个TextView到我的LinearLayout麻烦。以下是我有:为什么我不能一个TextView添加到我的Android中的LinearLayout?
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
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);
}
}
我没有得到在logcat中的任何错误,它只是不工作。
任何想法?
确保您的视图之间的间距是正确的
<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>
您也可以尝试mainLayout.addView(newView, 0);
按钮之前,将其添加为验证
没有为您的TextView
因为Button
正在他们都没有空间。
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="some button text" />
将其更改为wrap_content
这是否......没有工作。谢谢。 – Brian
布赖恩是正确的。第一行还有一个错字。我想它应该是android.com
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
而不是android/com。
我错过了......谢谢。 – Brian
好了,从'mainLayout.addView(NewView的),所以切换;''到mainLayout.addView(NewView的,0);'工作!它在按钮前显示我的文字。我不明白的是为什么它不会将它追加到我的原始代码中的按钮之后。 – Brian
那是一个完整的代码?因为我已经尝试过了,它在这两种情况下 –
不......不完整的工作超精细。我想尽可能缩短我的帖子。 – Brian