onClicklistener设置为微调器时强制关闭

时间:2014-05-15 20:33:41

标签: android android-fragments android-spinner

当我在我的片段中为微调器设置onCLick监听器时,我会关闭此力:

05-15 16:28:59.266  11419-11419/com.beerportfolio.beerportfoliopro W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41576d40)
05-15 16:28:59.356  11419-11419/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.beerportfolio.beerportfoliopro, PID: 11419
    java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.
            at android.widget.Spinner.setOnItemClickListener(Spinner.java)
            at com.beerportfolio.beerportfoliopro.BreweryPage2.onCreateView(BreweryPage2.java:57)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1097)
            at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1895)
            at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1514)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:958)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
            at android.os.Handler.handleCallback(Handler.java)
            at android.os.Handler.dispatchMessage(Handler.java)
            at android.os.Looper.loop(Looper.java)
            at android.app.ActivityThread.main(ActivityThread.java)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
            at dalvik.system.NativeStart.main(Native Method)

我的片段看起来像这样:

public class BreweryPage2 extends Fragment {

    public BreweryPage2(){}

    String breweryId = "";
    SearchView searchView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.brewery_page, container, false);
        setHasOptionsMenu(true);


        //get user information
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        final String userID = prefs.getString("userID", null);

       //todo: get brewery id from shared preferences
        final String breweryId = prefs.getString("breweryID", null);

        //set spinner up
        final Spinner visitedBrewery = (Spinner) rootView.findViewById(R.id.visitSpinner);

        //set spinner onCLick
        visitedBrewery.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
                String choice = visitedBrewery.getSelectedItem().toString();

                if (choice.equals("yes")){
                    //add to database
                    //construct url
                    String url = "myURL";

                    //async task to get beer taste tag percents
                    new AddBreweryVisit(getActivity() ).execute(url);

                }

                else{
                    //delete from database
                    String url = "myURL2";

                    //async task to get beer taste tag percents
                    new KillBreweryVisit(getActivity() ).execute(url);

                }




            }
        });



        //construct url
        String url = "myURL3";

        Log.d("visit" , url);

        //async task to get beer taste tag percents
        new GetBreweryDataJSON(getActivity() , visitedBrewery).execute(url);



        return rootView;
    }

}

第57行是这一行:

    visitedBrewery.setOnItemClickListener(new AdapterView.OnItemClickListener()

3 个答案:

答案 0 :(得分:0)

它可能只是更容易放......

   visitedBrewery.setOnItemClickListener(this);

然后让BreweryPage2实现它。

可能有一种更简单的方法,但这是我倾向于做的,我还没有遇到任何问题

答案 1 :(得分:0)

您可以按照此示例操作。比如

文件:res / values / strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MyAndroidApp</string>
    <string name="country_prompt">Choose a country</string>

    <string-array name="country_arrays">
        <item>Malaysia</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
    </string-array>

</resources>

文件:res / layout / main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/country_arrays"
        android:prompt="@string/country_prompt" />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />

</LinearLayout>

MyAndroidAppActivity.java。代码

public class MyAndroidAppActivity extends Activity {

  private Spinner spinner1, spinner2;
  private Button btnSubmit;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addItemsOnSpinner2();
    addListenerOnButton();
    addListenerOnSpinnerItemSelection();
  }

  // add items into spinner dynamically
  public void addItemsOnSpinner2() {

    spinner2 = (Spinner) findViewById(R.id.spinner2);
    List<String> list = new ArrayList<String>();
    list.add("list 1");
    list.add("list 2");
    list.add("list 3");
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner2.setAdapter(dataAdapter);
  }

  public void addListenerOnSpinnerItemSelection() {
    spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
  }

  // get the selected dropdown list value
  public void addListenerOnButton() {

    spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    btnSubmit = (Button) findViewById(R.id.btnSubmit);

    btnSubmit.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {

        Toast.makeText(MyAndroidAppActivity.this,
        "OnClickListener : " + 
                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) + 
                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
            Toast.LENGTH_SHORT).show();
      }

    });
  }
}

和File:CustomOnItemSelectedListener.java

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(), 
        "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
  }

}

[参考] [Android微调器(下拉列表)示例] 1

实际上变成了setOnItemSelectedListener而不是setOnItemClickListener。

祝你好运。

答案 2 :(得分:0)

spinner.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });

如果返回True,则单击微调器时将不显示微调器的下拉项。