我試圖添加一個帶有EditText元素的新LinearLayout,只要我的應用程序上的按鈕被推入。我有的xml是以編程方式添加線性佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/app"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<EditText android:id="@+id/dish_name"
android:layout_width="match_parent"
android:layout_height="58dp"
android:hint="@string/dish_name"
android:background="@drawable/my_border"
android:paddingLeft="10dip"/>
<LinearLayout android:id="@+id/ingredient_list"
android:layout_width="match_parent"
android:layout_height="58dp"
android:weightSum="1"
android:layout_marginTop="20dp">
<EditText android:id="@+id/edit_message"
android:layout_width="0dp"
android:layout_height="42dp"
android:hint="@string/edit_message"
android:background="@drawable/my_border"
android:layout_weight="1"
android:paddingLeft="10dip"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
</LinearLayout>
我想重複第二個LinearLayout以及它的EditText裏面。 Java代碼我至今是:
public void sendMessage(View view) {
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setWeightSum(1f);
params.weight = 1.0f;
params.setMargins(0,20,0,0);
EditText editText = new EditText(this);
editText.setBackgroundResource(R.drawable.my_border);
editText.setHint(R.string.edit_message);
editText.setLayoutParams(params);
LinearLayout container = (LinearLayout)findViewById(R.id.app);
container.addView(editText);
}
我遇到的問題是,當我按一下按鈕我得到如下:
我想要的EditText框與我在xml中定義的高度相同,但它佔用了整個屏幕。
任何想法?
remove * layout.setWeightSum(1f); params.weight = 1.0f; * – Atula