How can I use duplicate IDs in different layouts?

前端 未结 5 477
太阳男子
太阳男子 2020-12-17 15:59

I have two different layouts for two different Activities. There is a button in each of these layouts with the same id: \"@+id/btnOK\". When I set a property for one of thes

5条回答
  •  情深已故
    2020-12-17 16:40

    You can have the same IDs but it should be in different layouts. The same layout cannot handle duplicate IDs. I have taken two layouts as you did containing buttons having as "btn". I am calling the Activity2 having newxml.xml from the Activity1 having main.xml.

    Here is my code:

    main.xml:

    
    
    
        

    Activity1:

    setContentView(R.layout.main);
    
    Button button=(Button) findViewById(R.id.btn);
    button.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Activity1.this,Activity2.class);
                startActivity(intent);
            }
        });
    

    newxml:

    
    
        

    Activity2:

    setContentView(R.layout.newxml);
    
    Button button=(Button) findViewById(R.id.btn);
    button.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    

提交回复
热议问题