如何在onTouch中执行动态创建按钮的功能

时间:2015-04-28 12:14:22

标签: java android android-intent android-fragments android-activity

我在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();
});

2 个答案:

答案 0 :(得分:0)

你可以在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();

});

答案 1 :(得分:0)

尝试这些可能对您有用:

 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 
         } 
      }); 
    }