如何在微调器下拉菜单上打开新活动单击

vfh0ocws  于 2021-07-04  发布在  Java
关注(0)|答案(1)|浏览(293)

如果有人能帮忙。我已经创建了微调器部分,但现在每当我点击下拉列表,我需要一个新的活动打开。我不知道应该把if-else/开关盒放在哪里。

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

    spinner = findViewById(R.id.spinner);
    flags = findViewById(R.id.flag);

    spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
            CountryData.countryNames));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            flags.setImageResource(CountryData.countryflag[spinner.getSelectedItemPosition()]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
bcs8qyzn

bcs8qyzn1#

我想你可以这样做:

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
{
    Spinner spinner;

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

        ArrayList<String> activityList = new ArrayList<>(); // list of string which will be added to Spinner
        activityList.add("Select Activity");
        activityList.add("Activity 1");
        activityList.add("Activity 2");

        spinner = findViewById(R.id.spinner);

        spinner.setAdapter(new ArrayAdapter<>(this,
                                              android.R.layout.simple_spinner_dropdown_item,
                                              activityList
        ));

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
            {
                Log.i("MyTag", "Item selected at position " + i);
                if (i==0) // check position of selected item and open activity
                {
                    // do nothing
                }
                else if (i==1)
                {
                    openActivity(NewActivity.class);
                }
                else
                {
                    openActivity(NewActivitySecond.class);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView)
            {

            }
        });
    }

    private void openActivity(Class x) //funtion which opens activity
    {
        Intent intent = new Intent(this, x);
        startActivity(intent);
    }
}

相关问题