从String Array创建按钮并设置onClickListener

时间:2013-07-27 03:40:14

标签: android arrays for-loop dynamic android-button

我必须获取数组并使用它来动态创建onClickListener()。我已经使用这种方法来创建动态按钮。任何人都知道如何使用数组动态创建onClickListener()?

for (int i = 0; i < categoryName.size(); i++) {

    Button btn = new Button(this);
    btn.setId(Integer.parseInt(categoryID.get(i).toString()));
    btn.setHint(categoryID.get(i).toString());
    btn.setText(categoryName.get(i)); //another array with the name of the IDS
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //example
            Toast.makeText(getApplicationContext(),categoryID.get(i),Toast.LENGTH_LONG).show();
        }
    });
    buttonLayout.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}

2 个答案:

答案 0 :(得分:1)

仅放置btn.setOnClicklistener(this);而不是

btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        //example
        Toast.makeText(getApplicationContext(),categoryID.get(i),Toast.LENGTH_LONG).show();
    }
}); 

的onClick():

@Override
public void onClick(View v) {
    //example
    //you can check its view 
    //here V gives you BtnId 
}

答案 1 :(得分:0)

只需将categoryNamecategoryID数组设为final