单击“按钮”,以相同的形式创建图层。 Android的

时间:2012-12-30 22:22:41

标签: android android-layout android-intent

我对Android很新。

我想创建一个动态的OnClick按钮功能。

enter image description here

点击上面的“+”,它应该创建一个其他图层,如下所示。

enter image description here

我的困惑,我的整个设计UI都在layout.xml中。

我们如何在OnClick的“+”按钮的UI中包含另一个图层。

任何输入都会有所帮助。

谢谢!!!

2 个答案:

答案 0 :(得分:1)

你可以以编程方式执行此操作。 XML用于静态布局。

请原谅我的伪Android:

private LinearLayout root;

public void onCreate(Bundle b){

    LinearLayout root = new LinearLayout(this);

    root.addChild(createGlucoseReadingView());

    setContentView(root);

}

private View createGlucoseReadingView() {
   LinearLayout glucoseRoot = new LinearLayout(this);
   glucoseRoot.addChild(new TextView(this));
   return glucoseRoot;
}

public void onPlusClick(View button){
   root.addChild(createGlucoseReadingView());
}

沿着这些方向,我显然遗漏了格式并在视图中添加了布局参数,但是你明白了。

答案 1 :(得分:0)

在您的XML中有一个Vertical Linear Layout在运行时添加和删除EditTexts,这里我向您展示了我在演示中使用过的代码。处理和维护用法。

单击“添加和减少”按钮单击

    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

        case R.id.btnadd:
            createTextview(counter);
            counter++;
            if (counter > 3) {
                btnAdd.setVisibility(View.GONE);
                btnRemove.setVisibility(View.VISIBLE);
            }
            break;
        case R.id.btnremove:
            removeView(counter);
            txtoption[counter - 1] = null;
            counter--;
            if (counter < 3) {
                btnAdd.setVisibility(View.VISIBLE);
                btnRemove.setVisibility(View.GONE);
            }

            break;
        }
    }

创建和删除视图的功能

private void createTextview(int index) {
    txtoption[index] = new EditText(this);
    txtoption[index].setSingleLine(true);
    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    param.bottomMargin = 10;
    txtoption[index].setLayoutParams(param);
    txtoption[index].setBackgroundResource(R.drawable.textbox);
    txtoption[index].setTypeface(ttfDroidSherif);
    lnpolloptions.addView(txtoption[index]);

}

private void removeView(int index) {
    lnpolloptions.removeView(txtoption[index - 1]);
}

您的垂直LinearLayout包含所有edittext子项

LinearLayout lnpolloptions = (LinearLayout) findViewById(R.id.lnpolloptions);

要在运行时删除的edittext的数组

private EditText[] txtoption = new EditText[4];

单击提交以从每个文本框中获取值

            int length = txtoption.length;
            for (int i = 0; i < length; i++) {
                if (txtoption[i] != null) {
                    Log.i("Value",""+txtoption[i].getText());
                }
            }