Android development Linking XML button to Java

前端 未结 1 661
傲寒
傲寒 2020-12-04 04:10

I am new to android development, I am basically trying to create a very basic app which will enable the user to switch on their wifi.

My XML file:

&         


        
相关标签:
1条回答
  • 2020-12-04 04:38

    There are several ways of doing this.

    1. What you can do is add this line to your <Button tag in xml

      android:onClick="setWifiOn"

    then change the parameter of that function to

    public void getWifiOn(View v){
    
    
    return wifi_on;
    
    } 
    

    with this you don't need the onClick or any listeners

    2.You can do something similar if you want all Buttons to share the same function then give them all the function name like

    android:onClick="someFunction"
    

    then in Java do something like

    public void someFunction(View v)
    {
        Button btn = (Button)v;  
        switch (v.getId())
        {
           case (R.id.wifi_on:
            setWifiOn(btn);
            break;
           case (R.id.differentBtnId):
           // do some other things
           break;
         }
    }
    
    }
    

    3.Less attractive in many situations, IMHO

        public class MainActivity extends Activity implements OnClickListener {
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button wifiBtn = (Button) findViewById(R.id.wifi_on);
        wifiBtn.setOnClickListener(this);  // your onClick below will be called then you will still have to check the id of the Button
        // multiple buttons can set the same listener and use a switch like above
    
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    
    }
    

    Note number 3 is the only one in which you need implements OnClickListener

    Button Docs

    I left out the other way because I think its the ugliest if you have more than one Button

    0 讨论(0)
提交回复
热议问题