0

我是 android 开发的新手,我遇到了一些问题。

我想先创建一个用户界面,我有一个关于添加动态字段的问题。我已经在使用 XML 来设置我的界面,但我不知道如何继续。

例如,用户可以选择 1 2 3 或 4 并根据选择我希望对话框显示该数量的 EditText。同样的事情也将适用于以后。一个表格将在标题处显示该数量的文本视图。

有没有办法通过使用一些 XML 和一些 java 来做到这一点?因为我相信只使用 java 来设计不同的东西会很痛苦。

如果您需要更多信息,请告诉我。

提前致谢

4

2 回答 2

0

You should check out the visibility attribute of a View.

If you have a fixed set of ui elements (say, 5 buttons) you can just include them in the layout and show them later with setVisibility(View.Visible).

However, if you have a dynamic amount of elements (the user can chose from 1 to n buttons) then you will have to implement it in Java. You can still use XML layouts for parts of the work, but most stuff will have to be done by hand.

于 2013-10-25T11:05:04.680 回答
0

我已经写了一个示例代码,看看它是否对你有帮助

public class ActivityMain extends Activity {

    LinearLayout main;
    private int id = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        main = (LinearLayout) findViewById(R.id.parent);
        main.setOrientation(LinearLayout.VERTICAL);

        final EditText editText = (EditText) findViewById(R.id.et_count);

        Button button = (Button) findViewById(R.id.btn);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                final int count = Integer.parseInt(editText.getText()
                        .toString());
                addEditText(count);
            }
        });

    }

    private void addEditText(int count) {

        for (int i = 0; i < count; i++) {

            LinearLayout editTextLayout = new LinearLayout(this);
            editTextLayout.setOrientation(LinearLayout.VERTICAL);
            main.addView(editTextLayout);

            EditText editText1 = new EditText(this);
            editText1.setId(id++);
            editTextLayout.addView(editText1);

        }
    }
}

和布局 test.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent"
    android:padding="10dp" >

    <EditText
        android:id="@+id/et_count"
        android:layout_width="100dp"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />

</LinearLayout>

添加样式

editTextLayout.setTextAppearance(getApplicationContext(), R.style.boldText);
于 2013-10-25T11:17:29.247 回答