我尝试在运行时添加到自定义视图。
MainActivity.java
package com.example.bug;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.view.ViewGroup root = (android.view.ViewGroup)getWindow().getDecorView().findViewById(android.R.id.content);
View v0 = this.getLayoutInflater().inflate(R.layout.custom_view, null);
View v1 = this.getLayoutInflater().inflate(R.layout.custom_view, null);
((android.widget.TextView)v0.findViewById(R.id.textView1)).setText("Text view 1");
((android.widget.TextView)v1.findViewById(R.id.textView1)).setText("Text view 2");
// I expect v1 will below v0 as we are using vertical LinearLayout.
// However, they are overlapping each others.
root.addView(v0);
root.addView(v1);
}
}
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
但是,我不明白。我希望第二个视图将在第一个视图的底部。但是,我得到了重叠的结果。
(通过Java方式完成)
有没有我做错了什么步骤?谢谢你。
请注意,如果我通过 XML 方式而不是 Java 添加 2 个自定义视图,则一切正常。但我仍然不明白为什么我的 Java 方式不起作用?
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<include layout="@layout/custom_view"/>
<include layout="@layout/custom_view"/>
</LinearLayout>