簡體   English   中英

在運行時創建的按鈕如何分別在clicklistener上進行設置?

[英]Buttons created on runtime how to set on clicklistener for each?

我正在基於給定的數組大小創建按鈕。 我的問題是,當按下所有其他按鈕時,如何使onclicklistener變為其背景顏色。

例如:存在3個按鈕。 當按下button1時,按鈕2和3更改其背景顏色。 這是我的代碼:

for( j = 0; j < arrayName.length; j++) {
    //create the button
    final Button btn = new Button(this);

    //set all your button attributes, like text color,background color etc. here
    btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    btn.setText(arrayName[j]);
    btn.setId(j);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Toast.makeText(ProductPage.this,btn.getText().toString(),Toast.LENGTH_SHORT).show();
        }
    });
    //add the button to your linear layout
    buttonLayout.addView(btn);
}

您可以實現如下

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

實現常見的onclick偵聽器

 @Override
public void onClick(View v) {

    for(int i = 0 ; i < buttonLayout.getChildCount() ; i++){
        View buton = buttonLayout.getChildAt(i);
        buton.setBackground();
    }
}

為所有按鈕設置相同的偵聽器

for (int j = 0; j < arrayName.length; j++) {
            //create the button
            final Button btn = new Button(this);

            //set all your button attributes, like text color,background color etc. here
            btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            btn.setText(arrayName[j]);
            btn.setId(j);
            btn.setOnClickListener(this);
            //add the button to your linear layout
            buttonLayout.addView(btn);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM