@tema86

Как сделать кликабельное меню из кнопок с помощью switch?

Здравствуйте, делаю меню из нескольких кнопок двумя разными методами.
Один из них обеспечивает переход в другое активити по нажатию кнопки, а второй метод нет, тоесть ничего не происходит при нажатии.

Рабочий метод:

public class main extends AppCompatActivity {

    Button b1,b2,b3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout l1 = new LinearLayout(this);
        l1.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams l2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(l1,l2);


        b1 = (Button) findViewById(R.id.b1);
        b2 = (Button) findViewById(R.id.b2);
        b3 = (Button) findViewById(R.id.b3);


        LinearLayout.LayoutParams l3 = new LinearLayout.LayoutParams(200, ViewGroup.LayoutParams.WRAP_CONTENT);
        

        b1 = new Button(this);
        b1.setText("Button 1");
        l1.addView(b1,l3);

        b2= new Button(this);
        b2.setText("Button 2");
        l1.addView(b2,l3);

        b3 = new Button(this);
        b3.setText("Button 3");
        l1.addView(b3,l3);


        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(main.this,m2.class);
                startActivity(intent);
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(main.this,m3.class);
                startActivity(intent);
            }
        });
        b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(main.this,m4.class);
                startActivity(intent);
            }
        });
    }


и не рабочий:

public class main extends AppCompatActivity {

    Button b1,b2,b3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout l1 = new LinearLayout(this);
        l1.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams l2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(l1,l2);


        b1 = (Button) findViewById(R.id.b1);
        b2 = (Button) findViewById(R.id.b2);
        b3 = (Button) findViewById(R.id.b3);


        LinearLayout.LayoutParams l3 = new LinearLayout.LayoutParams(200, ViewGroup.LayoutParams.WRAP_CONTENT);
        

        b1 = new Button(this);
        b1.setText("Button 1");
        l1.addView(b1,l3);

        b2= new Button(this);
        b2.setText("Button 2");
        l1.addView(b2,l3);

        b3 = new Button(this);
        b3.setText("Button 3");
        l1.addView(b3,l3);


       View.OnClickListener onClickListener = (new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch(v.getID()) {
                    case R.id.b1:
                            Intent intent = new Intent(main.this,m2.class);
                            startActivity(intent);
                            break;
                    case R.id.b2:
                            Intent intent1 = new Intent(main.this,m3.class);
                            startActivity(intent1);
                            break;
                    case R.id.b3:
                            Intent intent2 = new Intent(main.this,m4.class);
                            startActivity(intent2);
                            break;
                }
            }
        });
    
        b1.setOnClickListener(onClickListener);
        b2.setOnClickListener(onClickListener);
        b3.setOnClickListener(onClickListener);

}


В чем может быть проблема? спасибо
  • Вопрос задан
  • 325 просмотров
Решения вопроса 1
@viktormarkov
Сначала Вы присваиваете переменным b1, b2, b3 объекты Button, созданные методом findViewById
b1 = (Button) findViewById(R.id.b1);
        b2 = (Button) findViewById(R.id.b2);
        b3 = (Button) findViewById(R.id.b3);


Потом этим же переменным присваиваете новые объекты Button
b1 = new Button(this);
....


Соответственно, эти переменные ссылаются на совершенно другие кнопки, id которых сгенерирован автоматически.
Поэтому в switch условие и не срабатывает
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы