如何从微调器中选择项目时打开新活动?单击微调器

时间:2017-09-22 07:51:29

标签: java android android-intent

从微调器中选择项目后想要打开新活动 我正在为大学项目创建应用程序,但却被困在这里 这是代码

这是布局中的微调器

<Spinner
    android:layout_width="match_parent"
    android:id="@+id/spin"
    android:layout_height="wrap_content"
    android:layout_marginRight="48dp"
    android:layout_marginEnd="48dp"
    android:layout_marginTop="103dp"
    android:layout_below="@+id/textView"
    android:layout_alignRight="@+id/textView"
    android:layout_alignEnd="@+id/textView"
    >
</Spinner>

这是strings.xml中的项目

<resources>
<string name="app_name">Spinner</string>
<string name="select_bikes">Bike Reviews</string>
<string-array name="bike_names">

    <item>Ducati Panigale</item>
    <item>Suzuki Hayabusa</item>
    </string-array>

这是我想要的代码,当我点击项目

时,它可以打开另一个活动
 Spinner spinner;
ArrayAdapter<CharSequence>adapter;

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

    spinner=(Spinner)findViewById(R.id.spin);
    adapter=ArrayAdapter.createFromResource(this,R.array.bike_names,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getBaseContext(),adapterView.getItemAtPosition(i)+" Selected",Toast.LENGTH_LONG).show();

        }

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

        }
    });
}

2 个答案:

答案 0 :(得分:1)

@Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(getBaseContext(),adapterView.getItemAtPosition(i)+" Selected",Toast.LENGTH_LONG).show();

         startActivity(new Intent(ActivityName.this,RecieverActivity.class));

    }

答案 1 :(得分:1)

尝试使用 Intent 启动活动

  

intent是要执行的操作的抽象描述。它可以与startActivity一起使用来启动活动

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getBaseContext(),adapterView.getItemAtPosition(i)+" Selected",Toast.LENGTH_LONG).show();

            if(i==0){
                Intent  intent = new Intent(YourActivity.this, WebViewActivity.class);
                intent.putExtra("URl","https://stackoverflow.com/");
                startActivity(intent);
            }else if(i==1){
                Intent  intent = new Intent(YourActivity.this, WebViewActivity.class);
                intent.putExtra("URl","https://stackoverflow.com/");
                startActivity(intent);
            }

        }

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

        }
    });