Java Android SetText不起作用

时间:2016-08-13 00:01:07

标签: java android

我的客户端类应该给出x_atual,y_atual等的值...我尝试通过注释最后两行代码来调试代码,并且settext甚至不起作用。 TextViews仍然具有相同的防御文本。

public class SecondActivity extends AppCompatActivity {

TextView x_atual,y_atual,x_desejado,y_desejado,ola;
Cliente myClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    x_atual = (TextView) findViewById(R.id.x_atual);
    y_atual = (TextView) findViewById(R.id.y_atual);
    x_desejado = (TextView) findViewById(R.id.x_desej);
    y_desejado = (TextView) findViewById(R.id.y_desej);
    ola = (TextView) findViewById(R.id.textView12);

    x_atual.setText("0");
    y_atual.setText("0");
    x_desejado.setText("0");
    y_desejado.setText("0");
    ola.setText("ola");

    myClient = new Cliente(x_atual,y_atual,x_desejado,y_desejado);
    myClient.execute();
}


}

我有多个片段,但我不认为是这样。

public class Cliente extends AsyncTask<Void,String,Void> {

    String dstAddress;
    int dstPort;
    TextView x_atual,y_atual,x_desejado,y_desejado;
    Scanner r;
    String[] valores = new String[4];

    public Cliente(String addr, int port) {
        //super();
        dstAddress = addr;
        dstPort = port;
    }

    public Cliente(TextView x_atual,TextView y_atual, TextView x_desejado, TextView y_desejado) {
        //super();
        this.x_atual = x_atual;
        this.y_atual = y_atual;
        this.x_desejado = x_desejado;
        this.y_desejado = y_desejado;
    }

    @Override
    protected Void doInBackground(Void... params) {

        Socket socket = null;

        try {
            socket = new Socket(dstAddress, dstPort);

            r = new Scanner(new InputStreamReader(socket.getInputStream()));

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        valores[0] = r.nextLine();
        valores[1] = r.nextLine();
        valores[2] = r.nextLine();
        valores[3] = r.nextLine();
        publishProgress(valores[0],valores[1],valores[2],valores[3]);
try {
    Thread.sleep(60);
} catch (InterruptedException e) {
    e.printStackTrace();
}
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        x_atual.setText(valores[0]);
        y_atual.setText(valores[1]);
        x_desejado.setText(valores[2]);
        y_desejado.setText(valores[3]);
       super.onPostExecute(result);
    }

}

1 个答案:

答案 0 :(得分:0)

这是因为当您调用setText时,视图创建尚未完成。

x_atual.post(new Runnable() {
        @Override
        public void run() {
            x_atual.setText("hi!");
        }
    });

为每个人做这件事。

等待视图结束,然后它将设置文本。