There are two identical View's, in them onDraw() and OnTouchEvent() methods. Separately, each works perfectly. But when adding them to the Activity , only the one that was added last works.

How to fix?

 public class PlayActivity extends AppCompatActivity{ RelativeLayout rlPlay; int wrapContent = RelativeLayout.LayoutParams.WRAP_CONTENT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play); rlPlay=(RelativeLayout) findViewById(R.id.rlPlay); RelativeLayout.LayoutParams lParams = new RelativeLayout.LayoutParams(wrapContent,wrapContent); Protect1 pt1=new Protect1(this); Protect2 pt2=new Protect2(this); rlPlay.addView(pt1,lParams); rlPlay.addView(pt2,lParams); } } 

    1 answer 1

    In my opinion, your views fall on each other, so the feeling that only one works. Try to give them different coordinates.

    As in the following code, just specify your View. Code from here

     public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); EditText editText = new EditText(this); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); // use same id as defined when adding the button params.addRule(RelativeLayout.LEFT_OF, 1001); editText.setLayoutParams(params); editText.setHint("Введите имя кота...."); Button button = new Button(this); RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); button.setLayoutParams(params2); button.setText("Нажми нежно!"); // give the button an id that we know button.setId(1001); RelativeLayout layout = new RelativeLayout(this); layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); layout.addView(editText); layout.addView(button); setContentView(layout); } 
    • The fact is that yes, it overlaps, but when swipe, the object must change the coordinates, and this it does only in the area of ​​the Layout allotted to it. That is, the view's area of ​​movement must be on the entire playing field, on which the same view's are. And the last added view overlaps the previous ones. - Nortedhas