我是 android 的新手,在做一些简单的事情时遇到了麻烦!
这是一些基本代码:
主要 Activity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Lets go ahead and set our buttons up.
ServerButton = (Button)this.findViewById(R.id.ServerButton);
ClientButton = (Button)this.findViewById(R.id.ClientButton);
BTServer = new BluetoothServerService(this, mHandler);
}
@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;
}
public void ServerButtonClick(View v){
Log.d("BLUETOOTH MAIN ACTIVITY", "It got here");
BTServer.start();
}
private final Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg){
switch (msg.what){
case HANDLER_CHANGE_SERVER_STATUS:
switch(msg.arg1){
case SERVER_STATUS_OFF:
CURRENT_SERVER_STATUS = SERVER_STATUS_OFF;
//We should probably add some logging, and the change to the button
break;
case SERVER_STATUS_ON:
CURRENT_SERVER_STATUS = SERVER_STATUS_ON;
//Again lets add some logging, etc.
break;
case SERVER_STATUS_ON_CONNECTED:
CURRENT_SERVER_STATUS = SERVER_STATUS_ON_CONNECTED;
//Again lets add some logging, etc.
break;
}
}
return;
}
};
我的 XML 看起来像这样:
<Button
android:id="@+id/ServerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="146dp"
android:layout_marginLeft="64dp"
android:text="Connect to Server" />
<Button
android:id="@+id/ClientButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="Start Server"
android:onClick="ServerButtonClick"/>
在我的日志中,我看到日志说它创建了 BTServer 对象,但是当我单击该按钮时我无法显示任何日志。
有什么建议吗?
谢谢!
最佳答案
在 onCreate
方法中为 ClientButton 定义一个点击 Action
ClientButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
也为 ServerButton 定义一个类似上面的点击 Action
ServerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
关于java - OnClick 不触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20579635/