簡體   English   中英

如何在Android中以編程方式使用相對布局創建編輯文本?

[英]How to create an edit text using Relative Layout programmatically in android?

我試圖在Java代碼的基礎上通過XML創建新的編輯文本。 我希望這個新的編輯文本顯示在舊編輯文本的右側,並在圖像視圖下方,該視圖也是用XML創建的,為此我使用RelativeLayout:

private void createEditText(){
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            editText.getLayoutParams().width,
            editText.getLayoutParams().height);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    layoutParams.addRule(RelativeLayout.RIGHT_OF, editText.getId());
    layoutParams.addRule(RelativeLayout.BELOW, imageView.getId());
    final EditText newEditText = new EditText(this);
    newEditText.setBackgroundResource(R.drawable.rounded_edittext);
    newEditText.setLayoutParams(layoutParams);

    relativeLayout.addView(newEditText);
}

但是新的編輯文本顯示在屏幕頂部,而忽略了我在代碼中使用的addRule函數。 這是RealtiveLayout:

<RelativeLayout
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center" />

我究竟做錯了什么? Java代碼或XML文件是否有錯誤?

您需要為newEditText設置索引。 默認值為-1,這意味着它將在其他視圖之前添加。 您可以使用relativeLayout.getChildCount();獲得子級的數量relativeLayout.getChildCount(); 由於計數是子代的數量,因此它也是添加newEditText的正確索引。

private void createEditText(){
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
        editText.getLayoutParams().width,
        editText.getLayoutParams().height);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.addRule(RelativeLayout.RIGHT_OF, editText.getId());
layoutParams.addRule(RelativeLayout.BELOW, imageView.getId());
final EditText newEditText = new EditText(this);
newEditText.setBackgroundResource(R.drawable.rounded_edittext);

relativeLayout.addView(newEditText,relativeLayout.getChildCount(),layoutParams);
}

並且由於將newEditText最終版本,因此請記住,每次啟動該應用程序時,都不能多次使用此方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM