0

I'm really new in android and java, but im trying to make an android app.

Im trying to make something were you can just type in your name and then it should view it by a push on a button. Eclipse is giving me the "unreachable code" error. I was wondering if you guys could see what i was doing wrong. The error is given in the two rules with final in front of it. If i remove one of these rules it will just move the error to the other rule.

Thank you in advance,
Marek

    package com.tutorial.helloworld2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

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


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


final EditText nameField = (EditText) findViewById(R.id.nameField);
final TextView nameView = (TextView) findViewById(R.id.nameView);

Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        nameView.setText("Hello " + nameField.getText());
    }
});

}

}
4

2 回答 2

0

移到方法的末尾,因为方法执行将return true在此语句处结束,并且不会执行以下代码。

于 2014-03-03T19:32:43.830 回答
0

这是由于return语句,return将返回 atrue并退出您当前编写代码的整个方法。您应该onCreate()像这样编写它。

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    final EditText nameField = (EditText) findViewById(R.id.nameField);
    final TextView nameView = (TextView) findViewById(R.id.nameView);
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            nameView.setText("Hello " + nameField.getText());
        }
    });
}

现在你会得到你想要的结果

于 2014-03-03T19:35:05.477 回答