【发布时间】:2014-08-18 20:50:20
【问题描述】:
我对 Java 和 Android SDK 都很陌生,所以如果这个问题很愚蠢,我深表歉意。我正在编写一个应该显示一个简单按钮的应用程序,并在单击时向本地服务器发送一条消息。但是,当我点击按钮时,什么也没有发生。这是我的代码:
.java
package com.example.hellokindlefire;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloKindleFireActivity extends Activity implements OnClickListener {
private Socket socket;
private PrintWriter pw;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_kindle_fire);
button = (Button)findViewById(R.id.send_button);
button.setOnClickListener(this);
}
public void onClick(View v) {
sendSignal(v);
}
public void sendSignal(View v) {
System.out.println("Sending...");
try {
socket = new Socket("192.168.1.100", 63400);
pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("Hello!");
} catch(IOException e) {
System.out.println(e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hello_kindle_fire, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.hellokindlefire.HelloKindleFireActivity" >
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/signal"
android:id="@+id/send_button" />
</RelativeLayout>
我查看了所有按钮文档,还查看了此处的类似问题,但似乎没有任何效果。我确保在单独的程序中测试 sendSignal 中的代码,并且服务器接收到消息没有问题。
【问题讨论】:
-
尝试刷新您的工作区,您的代码一目了然。您也可以尝试将
android:onClick="sendSignal"添加到您的按钮 xml 以直接调用 sendSignal,而无需以编程方式分配侦听器。 -
我按照你的建议刷新了,但是没有效果。实际上,我最初尝试过 'android:onClick="sendSignal"' 方法,因为它看起来更容易,但我改用了这种方法,因为那个方法也不起作用。
-
除了注意到您的 onClick 错过了
@Override,这可能会解决它(但不能解决为什么在 xml 中设置它不起作用),您是否尝试过确保您拥有 @ 987654325@ xml 文件的标头?
标签: java android xml network-programming kindle-fire