Ondrej Tokar
Ondrej Tokar

Reputation: 5070

Is there any other way to call a method on button click then with use of a listener?

I have just seen an android example code which doesn't make sense to me. There is declared a button, instantiated, but no listener. Even though, a method is called when you click the button.

I was thinking, if it is automatically called because the method is having the same name as the button, just with lowercase first letter. Is that an android feature, which I don't know about? I didn't know how to look for an answer, I tried, so it might be a duplicate.

CODE:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    On = (Button)findViewById(R.id.button1);
    Off = (Button)findViewById(R.id.button2);
    Visible = (Button)findViewById(R.id.button3);
    list = (Button)findViewById(R.id.button4);

    lv = (ListView)findViewById(R.id.listView1);

    BA = BluetoothAdapter.getDefaultAdapter();
}

public void on(View view){
    if (!BA.isEnabled()) {
        Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(turnOn, 0);
        Toast.makeText(getApplicationContext(),"Turned on"
                ,Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(getApplicationContext(),"Already on",
                Toast.LENGTH_LONG).show();
    }
}
public void list(View view){
    pairedDevices = BA.getBondedDevices();

    ArrayList list = new ArrayList();
    for(BluetoothDevice bt : pairedDevices)
        list.add(bt.getName());

    Toast.makeText(getApplicationContext(),"Showing Paired Devices",
            Toast.LENGTH_SHORT).show();
    final ArrayAdapter adapter = new ArrayAdapter
            (this,android.R.layout.simple_list_item_1, list);
    lv.setAdapter(adapter);

}

Upvotes: 0

Views: 40

Answers (3)

amodkanthe
amodkanthe

Reputation: 4530

check for android:onClick in android button xml whatever method name is declared there will be called when button is clicked and in this case there is no need to attach listener to button

Upvotes: 0

user3906057
user3906057

Reputation:

You can declare it in xml also like:

 android:onClick = "show"

And in your activity use like :

public void show(View v){
//handle click here
}

Upvotes: 2

Simas
Simas

Reputation: 44118

There's also the possibility to set the listener via xml, with an onClick attribute.

Upvotes: 3

Related Questions