如何显示其他类的输入文本

时间:2014-10-17 02:30:29

标签: java android eclipse

这是我的输入编辑文本类

package com.example.websocketclient;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

EditText name;
Button enter;

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

        enter.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                name = (EditText) findViewById(R.id.editTextdname);
                String dname = name.getText().toString();
                sendname(dname);                
            }
        });

    }

    public void sendname(String dname) {
        Intent i = new Intent(this,Chatroom.class);
        Bundle bundle = new Bundle();
        bundle.putString("myname", dname);
        i.putExtras(bundle);
        startActivity(i);
    }


    @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;
    }

}

这是我显示EditText到TextView类

package com.example.websocketclient;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class Chatroom extends Activity {

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

        uname = (TextView) findViewById(R.id.textViewmynam);

        //kuha  
        Bundle bundle = getIntent().getExtras();
        String urname = bundle.getString("myname");
        uname.setText(urname);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.chatroom, menu);
        return true;
    }

}

当我运行它...它说不幸的是,它会关闭.. 我想从 - >传递数据EditText到我的另一个类到我的显示类 - > TextView的。

2 个答案:

答案 0 :(得分:1)

与ρяσѕρєяK回答一起,为了传递你的值,因为你只传递一个字符串,你可以使用:

 intent.putExtra("value","key");

并且在获得时,

String value= getIntent.getStringExtra("key","default_value");

答案 1 :(得分:0)

  

它说不幸的是,它会关闭..

因为在调用enter之前没有初始化setOnClickListener Button对象。这样做:

setContentView(R.layout.activity_main); 
// initilize Button here 
enter= (Button) findViewById(R.id.BUTTON_ID_IN_XML);