【问题标题】:unreachable statement trying to set up a button that will open a new activityunreachable 语句尝试设置将打开新活动的按钮
【发布时间】:2022-01-03 23:59:15
【问题描述】:

我对此非常陌生。我有一个快速的问题。在尝试设置该按钮以将我带到新活动时,我在第 30 行 (establecimientos = findViewById(R.id.establecimientos) 上收到一条“无法访问的声明。您能帮忙指出什么问题吗,谢谢?

这就是我的 java 的样子:

package com.example.ceibasxi;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;


public class PaginaDos extends AppCompatActivity {
    Button establecimientos;
    Button servicios;
    Button productos;

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

        Toolbar myToolbar = findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_appbar, menu);
        return true;


establecimientos = findViewById(R.id.establecimientos);
establecimientos.setOnClickListener(v -> {

servicios = findViewById(R.id.servicios);
servicios.setOnClickListener(v1 -> {
Intent intent1 = new Intent(PaginaDos.this, PaginaServicios.class);
startActivity(intent1);

productos = findViewById(R.id.producto);
productos.setOnClickListener(v11 -> {
Intent intent2 = new Intent(PaginaDos.this, PaginaProductos.class);
startActivity(intent2);}

);});})
    ;}}

【问题讨论】:

    标签: java android button android-activity unreachable-statement


    【解决方案1】:

    在您的代码中,您有以下内容:

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_appbar, menu);
        return true;
    

    在此之后您有很多代码将永远不会在方法onCreateOptionsMenu() 中执行,因为您有一个return 语句。此方法中不会执行return 语句之后的任何内容。

    在我看来,这段代码应该在 onCreate() 方法内,而不是在 onCreateOptionsMenu() 方法内。

    也许您只是移动了代码而感到困惑。

    【讨论】:

      猜你喜欢
      • 2019-03-07
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多