Whisher
Whisher

Reputation: 32726

android Button onClick in xml reference parameter

just for learning purpose

<Button 
android:id="@+id/button"
android:text=""
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:onClick="updateTime"/>


public class MainActivity extends Activity {
Button btn;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    btn = (Button) findViewById(R.id.button);
    updateTime(btn);

}

public void updateTime(View b) {
    btn.setText(new Date().toString());
}

}

if View b it's a reference to btn how can pass it

as View ? I've tried like

public void updateTime(Button b) {
    b.setText(new Date().toString());
}

but it doesn't work Can you help me, please?

Thanks in advance.

Upvotes: 0

Views: 529

Answers (1)

Jeshurun
Jeshurun

Reputation: 23186

Have you tried:

public void updateTime(View b) {
    ((Button)b).setText(new Date().toString());
}

From the documentation:

This name must correspond to a public method that takes exactly one parameter of type View

So if you are defining updateTime as a click action listener in the xml layout, then your callback must match the signature public void updateTime(View v), which means you can't declare it as accepting a Button as an argument.

Also, android:onClick only works for API level 4 and up, so if you're targeting API levels below that, you will have to declare the click action listener in code..

Upvotes: 1

Related Questions