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

标签 java android android-fragments android-inflate

我有带控件的布局:

<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/

相关文章:

java - Android Activity 和 Java 类之间的通信

android - android 中的 websockets 和同步适配器

android - 如何让滑动面板中的元素监听点击事件

android - fragment 内的 TabLayout 给出错误的项目 View

java - 多线程中如何获取锁以及在哪个对象上获取锁?

java - java android应用程序和PHP脚本之间交换数据最安全的方法?

java - 将方法输出从 java 类移动到 HTML

java - 是否可以创建类似于字符串的对象池?

android - 将图像上传到 Android 中的服务器时通知栏中的进度条

机器人 : open chrome custom tab from fragment