本文介绍了以编程方式创建Imagebutton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想以编程方式创建多个ImageButton.我能够创建它们,但是无论单击按钮0,按钮1还是按钮2,单击事件侦听器都将继续接收相同的视图(按钮2).

I want to create several ImageButtons programmatically. I am able to create them but the click event listener keeps receiving the same view (Button 2), whether I click on button 0 ,button1 or button 2.

    RelativeLayout gameBoard = (RelativeLayout) findViewById(R.id.RelGameboard);

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);

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

        ImageButton btnGreen = new ImageButton(this);
        btnGreen.setImageResource(R.drawable.bola_verde);
        btnGreen.setLayoutParams(lp);
        btnGreen.setOnClickListener(mGreenBallOnClickListener);
        btnGreen.setBackgroundColor(Color.TRANSPARENT);
        btnGreen.setTag(i);
        btnGreen.setId(i);

                    gameBoard.addView(btnGreen);


     }'

点击事件侦听器:

private View.OnClickListener mGreenBallOnClickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        //check which green ball was clicked
        ImageButton imgBtn = (ImageButton) v;

    Log.i("greeny","Clicked on green ball->"+imgBtn.getTag()+" v.ID->"+v.getId());
    }
};

对于绘制的任何图像按钮,当我单击时,都会得到:单击绿色的球-> 2 v.ID-> 2

For any imagebutton drawn, when I click I get : Clicked on green ball->2 v.ID->2

按钮的位置不同(我为每个按钮设置了不同的填充,但是为了简化代码,我没有在此处放置它)

The buttons are in different positions ( i set a different padding for each one of them but in order to simplify the code I didn't put it here )

推荐答案

尝试添加onClickListener-

private View.OnClickListener ClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int selected_item = (Integer) v.getTag();
    }
};

编辑

尝试创建 ImageButtons -

Try creating a array of ImageButtons -

ImageButton[] btnGreen = new ImageButton[3];

for (int i = 0; i < 3; i++) {
    btnGreen[i] = new ImageButton(this);
    btnGreen[i].setImageResource(R.drawable.bola_verde);
    btnGreen[i].setLayoutParams(lp);
    btnGreen[i].setOnClickListener(ClickListener);
    btnGreen[i].setBackgroundColor(Color.TRANSPARENT);
    btnGreen[i].setTag(i);
    btnGreen[i].setId(i);

    gameBoard.addView(btnGreen[i]);
}

这篇关于以编程方式创建Imagebutton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:57