安卓android stdio多个按钮跳转不同页面,减少代码冗余

package com.example.infomannagedemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    Button button1;
    Button button2;
    Button button3;
    Button button4;
    Button button5;
    Button button6;
    View.OnClickListener myListener=new View.OnClickListener(){

        @Override
        public void onClick(View view) {
            Intent intent = null;
            switch (view.getId()){
                case R.id.infoManage:
                    intent=new Intent(MainActivity.this,MainActivity1.class);
                    break;
                case R.id.imageBrowser:
                    intent=new Intent(MainActivity.this,MainActivity2.class);
                    break;
                case R.id.RelativeLayou:
                    intent=new Intent(MainActivity.this,MainActivity3.class);
                    break;
                case R.id.MultiplyLayout:
                    intent=new Intent(MainActivity.this,MainActivity4.class);
                    break;
                case R.id.ConstraintLayout:
                    intent=new Intent(MainActivity.this,MainActivity5.class);
                    break;
                case R.id.ImageSwitcher:
                    intent=new Intent(MainActivity.this,MainActivity6.class);
                    break;
            }
            startActivity(intent);
        }
    };

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


        button1=(Button) findViewById(R.id.infoManage);
        button2=(Button) findViewById(R.id.imageBrowser);
        button3=(Button) findViewById(R.id.RelativeLayou);
        button4=(Button) findViewById(R.id.MultiplyLayout);
        button5=(Button) findViewById(R.id.ConstraintLayout);
        button6=(Button) findViewById(R.id.ImageSwitcher);

        button1.setOnClickListener(myListener);
        button2.setOnClickListener(myListener);
        button3.setOnClickListener(myListener);
        button4.setOnClickListener(myListener);
        button5.setOnClickListener(myListener);
        button6.setOnClickListener(myListener);

    }

}

《第一行代码》里有,不然还真不会

你可能感兴趣的:(android,android,studio,java)