如何为每个EditText设置ID?

时间:2014-01-20 08:38:01

标签: java android android-inflate

我制作了这些代码。 每次我点击按钮,EditText都会在滚动布局中膨胀。 如何获取每个EditText的ID? 取每个人的价值?

ScrollView scrollview;
LinearLayout  linearLayout;
LinearLayout.LayoutParams layoutParams;
//EditText hello;
static int i = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    Button sum_1 = (Button)findViewById(R.id.sum);


    scrollview = (ScrollView)findViewById(R.id.scrollview);
    linearLayout = (LinearLayout)findViewById(R.id.gamehistory);
    Button b = (Button)findViewById(R.id.Button01);
    layoutParams = new LinearLayout.LayoutParams
            (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    b.setOnClickListener(new View.OnClickListener(){


        public void onClick(View v) {



                EditText hello = new EditText(MainActivity.this);

                hello.setText("enter value" + i++);
                linearLayout.addView(hello, layoutParams);

                hello.setId(i++);


        }

    });

2 个答案:

答案 0 :(得分:1)

您想要在布局中添加ID的唯一原因是您可以在代码中保留该视图..在这里您已经可以访问EditText

然后只需将所有EditTexts添加到List然后从那里使用它们就更容易了 甚至是EditText []

答案 1 :(得分:0)

        b.setOnClickListener(new View.OnClickListener(){


        public void onClick(View v) {



                EditText hello = new EditText(MainActivity.this);

                hello.setText("enter value" + i++);
                linearLayout.addView(hello, layoutParams);

                hello.setId(i++);

               hello.setTag("edit");
        }

    });



int childcount = linearLayout.getChildCount();
    for (int i = 0; i < childcount; i++) {
             View v1 = linearLayout.getChildAt(i);
            if(v1.getTag.equls("edit"){

                    System.out.println(v1..getId());
             }

    }