문제

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());
    }
});

}

}
도움이 되었습니까?

해결책

Move return true to the end of method as the method execution will end on this statement and no code below will be executed.

다른 팁

it is due to return statement, return will return a true and exit the entire method you have currently written code in. you should write this in onCreate() like.

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

now you will get your desired result

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top