通过edittext将文本设置为textview

时间:2013-09-19 17:28:05

标签: android android-edittext textview textwatcher

我无法使用edittext在android textview项目中设置文本:

 public class MainActivity extends Activity {
        TextView  textView1;
        private Button button1;
        private EditText editText1;
        private Editable e;
        private String ee;
        private SharedPreferences sh1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


        textView1 = (TextView) findViewById(R.id.textView1);
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                saveM1(editText1.getText().toString());

            }

        });
        editText1.addTextChangedListener(eeeee);
        sh1 = getSharedPreferences("sh1",MODE_PRIVATE);

        }
        private void saveM1(String save1){

              SharedPreferences.Editor preferencesEditor = sh1.edit();
             preferencesEditor.putString("save1",save1); //change this line to this
             preferencesEditor.commit();

         }

        @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 boolean onOptionsItemSelected(MenuItem item){
            switch(item.getItemId())
            {
            case R.id.action_settings:
    Intent i = new Intent(this,aa.class);
    startActivity(i);

                return true;
            }
            return true;
        }
    public TextWatcher eeeee = new TextWatcher(){

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            e = editText1.getText(); //eeee
            textView1.setText("e"+e);

        }

    };
    }

我的应用崩溃了。请帮忙。

2 个答案:

答案 0 :(得分:2)

你刚忘了

editText1 = (EditText) findViewById(R.id.editText1);

这就是你的应用崩溃的原因

答案 1 :(得分:2)

您的应用因nullpointer而崩溃。这是因为您使用editText1而未在onCreate中初始化

   editText1 = (EditText) findViewById(R.id.edittextID)