简体   繁体   中英

TextView unreachable code

Here the code:

package com.example.appbsp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
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;

    TextView textView1 = (TextView)
             findViewById(R.id.textView1);
}

}

First I added a new TextView in activity_main.xml and gave it the Id: @+id/textView1 Then I entered this code in MainActivity.java for futher outputs:

TextView textView1 = (TextView)
             findViewById(R.id.textView1);

Then I imported android.widget.TextView but then the upper code becomes red underlined and it says unreachable code and just "remove" as quick fix. One month before it worked and now I don´t work anymore. Anyone knows an answer?

(Target SDK:API 18; Compile with API 19)

I´ma newbe so please try to give a not too complicated answer. Sorry for bad English. Thanks

put return to at bottom.

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


    TextView textView1 = (TextView)
             findViewById(R.id.textView1);

     return true;
}

Because you wrote the return true before that statement so that why this line TextView textView1 = (TextView) findViewById(R.id.textView1); is unreachable because compiler wont reach to this statement.

Do like this

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

and Intialize the views in the onCreate like

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView1 = (TextView) findViewById(R.id.textView1);            
    // you can set the text here any
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM