在微调器中设置onclick侦听器时弹出错误

时间:2014-12-08 19:50:21

标签: java android xml onclick spinner

我是android的新手并且搜索了很多关于这个问题但是找不到解决方案,我在设置微调器选项上的click listner选项时遇到此错误,请帮我解决这个错误虽然它很小。

错误

AdapterView类型中的方法setOnItemSelectedListener(AdapterView.OnItemSelectedListener)不适用于参数(MainActivity)

 #MainActivity.java
 package com.example.spinners;

 import android.support.v7.app.ActionBarActivity;
  import android.os.Bundle;
 import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;


  public class MainActivity extends ActionBarActivity implements OnItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    spinner.setOnItemSelectedListener(this);
 // Create an ArrayAdapter using the string array and a default spinner layout
 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
         R.array.planets_array, android.R.layout.simple_spinner_item);
 // Specify the layout to use when the list of choices appears
 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 // Apply the adapter to the spinner
 spinner.setAdapter(adapter);
 ;

}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    // code 
}
}

activity_main.xml中

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.spinners.MainActivity" >

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="110dp" />

 </RelativeLayout>

1 个答案:

答案 0 :(得分:0)

spinner.setOnItemSelectedListener(this);

这期望this是一个实现onItemSelectedListener接口的对象,你可以按照自己的意愿去做,但你需要改变这个

public class MainActivity extends ActionBarActivity

public class MainActivity extends ActionBarActivity implements onItemSelectedListener

并实施方法

@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    // code 
}

编辑:

和这个方法

@Override
public void onNothingSelected (AdapterView<?> parent) {
    // code
}