gpt4 book ai didi

java - 安卓。以编程方式添加控件

转载 作者:行者123 更新时间:2023-12-01 04:45:53 25 4
gpt4 key购买 nike

我有带控件的布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/contact_phones_layout_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText
android:id="@+id/contact_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:inputType="phone" />

<Spinner
android:id="@+id/contact_phone_type"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />

</LinearLayout>

我想将它膨胀到 fragment 上的另一个布局中。这些控件的数量取决于数组中的值。数组包含控件对象。因此,每次 onCreateView 上升时,我都会从数组中填充布局:

private void addLine(PhoneLine line) {
LinearLayout layout = (LinearLayout) mLayout.findViewById(R.id.contact_phones_layout);
View view = line.getParent();
((ViewGroup) view.getParent()).removeView(view);
layout.addView(view, layout.getChildCount() - 1);
setButtonVisible(false);
}

如果行为空,则按以下方式创建控件:

private void addLine() {
LinearLayout layout = (LinearLayout) mLayout.findViewById(R.id.contact_phones_layout);
View view = inflater.inflate(R.layout.contact_phone_line, layout, false);
EditText phoneEditText = (EditText) view.findViewById(R.id.contact_phone);
Spinner phoneType = (Spinner) view.findViewById(R.id.contact_phone_type);
phoneLines.add(new PhoneLine(phoneEditText, phoneType, view));
layout.addView(view, layout.getChildCount() - 1);
}

但之后我在所有 EditText/Spinner 控件中获得相同的值,这些值等于数组中的最后一个元素。有什么问题吗?可能有更纯粹的动态添加控件的方法吗?

最佳答案

我通过在 onResume 上升时添加控件来修复此问题,而不是 onCreateView。但我还是不明白为什么 onCreateView 会改变所有的值。

关于java - 安卓。以编程方式添加控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15849772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com