java—如何执行ontouch中动态创建的按钮的功能

yfjy0ee7  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(347)

我已经把画廊里的照片 RelativeLayout 试着把 Button 动态使用单独的id,在 onTouch . 现在,我正在尝试根据按钮id设置和获取值。(在我的代码中,现在所有按钮的值都相同。) Button ).
我的代码:

viewGroup= (ViewGroup) this.findViewById(createdPinViewGroup);
viewGroup.setId(R.id.ImageId);
i =0
selectedPicture.setOnTouchListener(new View.OnTouchListener() {
@Override
 public boolean onTouch(View v, MotionEvent event) {
 int x = (int) event.getX();
 int y = (int) event.getY();
 rparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
 rparams.addRule(RelativeLayout.ACCESSIBILITY_LIVE_REGION_ASSERTIVE);
 rparams.leftMargin = x;
 rparams.topMargin = y;
 rparams.height = 48;
 rparams.width = 60;
 btn = new Button(getBaseContext());
 btn.setId(i + 1);
 btn.setText("B" + i);
 btn.setLayoutParams(rparams);
 viewGroup.addView(btn);
 i++;

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getBaseContext(), "Button is Clicked", Toast.LENGTH_LONG).show();
});
krugob8w

krugob8w1#

您可以在onclick本身中获取id

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    Toast.makeText(getBaseContext(), "Button is Clicked "+v.getId(), Toast.LENGTH_LONG).show();

});

myss37ts

myss37ts2#

试试这些,也许对你有用:

Button[] btn = new Button[100];

 viewGroup= (ViewGroup) this.findViewById(createdPinViewGroup);
 viewGroup.setId(R.id.ImageId);
 i =0
 selectedPicture.setOnTouchListener(new View.OnTouchListener() {
 @Override
 public boolean onTouch(View v, MotionEvent event) {
 int x = (int) event.getX();
 int y = (int) event.getY();
 rparams = new   
 RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,   
 RelativeLayout.LayoutParams.WRAP_CONTENT);
 rparams.addRule(RelativeLayout.ACCESSIBILITY_LIVE_REGION_ASSERTIVE);
 rparams.leftMargin = x;
 rparams.topMargin = y;
 rparams.height = 48;
 rparams.width = 60;
 i++;
 btn[i] = new Button(getBaseContext());
 btn[i].setId(i + 1);
 btn[i].setText("B" + i);
 btn[i].setLayoutParams(rparams);
 viewGroup.addView(btn);

 btn[i].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //your desired functionality 
         } 
      }); 
    }

相关问题