我正在尝试创建一个动态微调器

时间:2015-07-08 11:49:32

标签: java android spinner

我想要的是根据从第一个微调器中选择的城市填充区域微调器。我附上了必要的代码。如果有人需要什么,请随意提问。对不起,我是新手。先感谢您。

select_location_layout.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="80dp"
        android:text="@string/selectCity"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/citySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="@string/selectArea"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/areaSpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog" />

</LinearLayout>

string.xml

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

    <string name="app_name">Navigation Drawer</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="drawer_open">Open Navigation Drawer</string>
    <string name="drawer_close">Close Navigation Drawer</string>
    <string name="selectCity">Select City</string>
    <string name="selectArea">Select Area</string>

    <string-array name="drawerItems">
        <item>Location</item>
        <item>Ready for Delivery</item>
        <item>Order Cake</item>
        <item>About us</item>
        <item>Setting</item>
        <item>Login</item>
        <item>My Orders</item>
        <item>My Cart</item>
        <item>Help</item>
        <item>Contact us</item>
        <item>Rate us</item>
        <item>Share</item>
    </string-array>
    <string-array name="cities">
        <item>Ahmedabad</item>
        <item>Baroda</item>
        <item>Surat</item>
        <item>Mumbai</item>
        <item>Pune</item>
        <item>Banglore</item>
    </string-array>
    <string-array name="ahmedabad_area">
        <item>Maninagar</item>
        <item>C.T.M</item>
        <item>C.G. Road</item>
        <item>Satellite</item>
        <item>S.G. Highway</item>
        <item>Navarangpura</item>
    </string-array>
    <string-array name="baroda_area">
        <item>Alkapuri</item>
        <item>Fateganj</item>
        <item>Jaeahar Nagar</item>
        <item>Karali</item>
        <item>Mandavi</item>
        <item>Masar Road</item>
    </string-array>
    <string-array name="surat_area">
        <item>Athwa</item>
        <item>Bajipura</item>
        <item>Cenral Colony</item>
        <item>Hajira</item>
        <item>Kamrej</item>
        <item>Lajpor</item>
    </string-array>
    <string-array name="mumbai_area">
        <item>Adarsha Nagar</item>
        <item>Thane</item>
        <item>Centacruz</item>
        <item>Andheri</item>
        <item>Varsova</item>
        <item>Dadar</item>
    </string-array>
    <string-array name="pune_area">
        <item>Akurdi</item>
        <item>Bavada</item>
        <item>Chakan</item>
        <item>Daund</item>
        <item>Earth Stn</item>
        <item>Ganeshkhind</item>
    </string-array>
    <string-array name="banglore_area">
        <item>Indira Nagar</item>
        <item>Jay Nagar</item>
        <item>TipSandra</item>
        <item>Kora Mangala</item>
        <item>Rajaji Nagar</item>
        <item>White Field</item>
    </string-array>

</resources>

LocationSelection.java

   package com.pixalstudio.navigationdrawer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

public class LocationSelection extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_location_layout);

        Spinner citySpinner = (Spinner) findViewById(R.id.citySpinner);
        Spinner areaSpinner = (Spinner) findViewById(R.id.areaSpinner);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.cities, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        citySpinner.setAdapter(adapter);
        final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter
                .createFromResource(this, R.array.ahmedabad_area,
                        android.R.layout.simple_spinner_item);
        areaSpinner.setAdapter(adapter1);

        citySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> parent,
                            View view, int position, long id) {
                        adapter1.clear();

                        int stringArrayResource = 0;
                        switch (position) {
                        case 0:
                            stringArrayResource = R.array.ahmedabad_area;
                            break;
                        }
                        adapter1.addAll(getResources().getStringArray(
                                stringArrayResource));
                        adapter1.notifyDataSetChanged();

                    }

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

                    }

                });
    }

}

logcat的

    07-08 09:24:08.274: D/OpenGLRenderer(2879): Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-08 09:24:08.278: D/(2879): HostConnection::get() New Host Connection established 0xb42d7740, tid 2879
07-08 09:24:08.754: D/Atlas(2879): Validating map...
07-08 09:24:09.145: D/libEGL(2879): loaded /system/lib/egl/libEGL_emulation.so
07-08 09:24:09.146: D/libEGL(2879): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-08 09:24:09.156: D/libEGL(2879): loaded /system/lib/egl/libGLESv2_emulation.so
07-08 09:24:09.166: D/(2879): HostConnection::get() New Host Connection established 0xaf039490, tid 2897
07-08 09:24:09.204: I/OpenGLRenderer(2879): Initialized EGL, version 1.4
07-08 09:24:09.266: D/OpenGLRenderer(2879): Enabling debug mode 0
07-08 09:24:09.368: W/EGL_emulation(2879): eglSurfaceAttrib not implemented
07-08 09:24:09.368: W/OpenGLRenderer(2879): Failed to set EGL_SWAP_BEHAVIOR on surface 0xaf035800, error=EGL_SUCCESS
07-08 09:24:09.468: I/Choreographer(2879): Skipped 40 frames!  The application may be doing too much work on its main thread.
07-08 09:24:18.176: W/EGL_emulation(2879): eglSurfaceAttrib not implemented
07-08 09:24:18.177: W/OpenGLRenderer(2879): Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43c6c20, error=EGL_SUCCESS
07-08 09:24:18.211: D/AndroidRuntime(2879): Shutting down VM
07-08 09:24:18.211: E/AndroidRuntime(2879): FATAL EXCEPTION: main
07-08 09:24:18.211: E/AndroidRuntime(2879): Process: com.pixalstudio.navigationdrawer, PID: 2879
07-08 09:24:18.211: E/AndroidRuntime(2879): java.lang.UnsupportedOperationException
07-08 09:24:18.211: E/AndroidRuntime(2879):     at java.util.AbstractList.remove(AbstractList.java:638)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at java.util.AbstractList.removeRange(AbstractList.java:658)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at java.util.AbstractList.clear(AbstractList.java:466)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.widget.ArrayAdapter.clear(ArrayAdapter.java:258)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at com.pixalstudio.navigationdrawer.LocationSelection$1.onItemSelected(LocationSelection.java:35)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.widget.AdapterView.fireOnSelected(AdapterView.java:914)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:903)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.widget.AdapterView.access$300(AdapterView.java:48)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:873)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.os.Handler.handleCallback(Handler.java:739)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.os.Handler.dispatchMessage(Handler.java:95)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.os.Looper.loop(Looper.java:135)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at android.app.ActivityThread.main(ActivityThread.java:5254)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at java.lang.reflect.Method.invoke(Native Method)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at java.lang.reflect.Method.invoke(Method.java:372)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
07-08 09:24:18.211: E/AndroidRuntime(2879):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

请帮助我知道如何根据spinner1中选择的城市填充spinner2中的区域。

3 个答案:

答案 0 :(得分:2)

@Override
public void onStart(){
  super.onStart();
  citySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        String city = spinner.getSelectedItem().toString();
        String name = String.format("%s_area", city);
        Resources res = getResources();
        int id = res.getIdentifier(name, "array", getPackageName());
        String[] items = res.getStringArray(id);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, items);
        areaSpinner.setAdapter(adapter);
      }

      @Override
      public void onNothingSelected(AdapterView<?> parentView) {
        String[] items = new String[]{};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, items);
        areaSpinner.setAdapter(adapter);
      }
  });
}

答案 1 :(得分:1)

好的,这是一份工作样本。它花了比预期更长的时间,但它的工作原理。这个想法是你获得citySpinner的文本并使用它来获取areaSpinner所需的字符串数组的资源id。处理项目选择的代码放在onStart事件中,以便它只触发一次。

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.content.res.Resources;
import android.util.Log;

public class MainActivity extends Activity {

  private String TAG = "MainActivity";

  private Activity mActivity;
  private Spinner mCitySpinner;
  private Spinner mAreaSpinner;

  @Override
  protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    setContentView(R.layout.activity_main);

    Log.d(TAG, "onCreate");

    mActivity = this;

    mCitySpinner = (Spinner)findViewById(R.id.citySpinner);
    mAreaSpinner = (Spinner)findViewById(R.id.areaSpinner);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.cities, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    mCitySpinner.setAdapter(adapter);
  }

  @Override
  public void onStart(){
    super.onStart();

    Log.d(TAG, "onStart");

    mCitySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
          Log.d(TAG, "mCitySpinner.onItemSelected");

          String city = mCitySpinner.getSelectedItem().toString();
          Log.d(TAG, String.format("city:%s", city));

          String name = String.format("%s_area", city).toLowerCase();
          Log.d(TAG, String.format("name:%s", name));

          String packageName = getPackageName();
          Log.d(TAG, String.format("packageName:%s", packageName));

          Resources res = getResources();
          int rid = res.getIdentifier(name, "array", packageName);
          Log.d(TAG, String.format("rid:%d", rid));

          String[] items = res.getStringArray(rid);
          ArrayAdapter<String> adapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_spinner_item, items);
          mAreaSpinner.setAdapter(adapter);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
          Log.d(TAG, "mCitySpinner.onNothingSelected");

          String[] items = new String[]{};
          ArrayAdapter<String> adapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_spinner_item, items);
          mAreaSpinner.setAdapter(adapter);
        }
    });

  }  
}

activity_main.xml中

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="80dp"
        android:text="@string/selectCity"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/citySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="@string/selectArea"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/areaSpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog" />

</LinearLayout>

的strings.xml

<string name="app_name">Navigation Drawer</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="drawer_open">Open Navigation Drawer</string>
<string name="drawer_close">Close Navigation Drawer</string>
<string name="selectCity">Select City</string>
<string name="selectArea">Select Area</string>

<string-array name="drawerItems">
    <item>Location</item>
    <item>Ready for Delivery</item>
    <item>Order Cake</item>
    <item>About us</item>
    <item>Setting</item>
    <item>Login</item>
    <item>My Orders</item>
    <item>My Cart</item>
    <item>Help</item>
    <item>Contact us</item>
    <item>Rate us</item>
    <item>Share</item>
</string-array>
<string-array name="cities">
    <item>Ahmedabad</item>
    <item>Baroda</item>
    <item>Surat</item>
    <item>Mumbai</item>
    <item>Pune</item>
    <item>Banglore</item>
</string-array>
<string-array name="ahmedabad_area">
    <item>Maninagar</item>
    <item>C.T.M</item>
    <item>C.G. Road</item>
    <item>Satellite</item>
    <item>S.G. Highway</item>
    <item>Navarangpura</item>
</string-array>
<string-array name="baroda_area">
    <item>Alkapuri</item>
    <item>Fateganj</item>
    <item>Jaeahar Nagar</item>
    <item>Karali</item>
    <item>Mandavi</item>
    <item>Masar Road</item>
</string-array>
<string-array name="surat_area">
    <item>Athwa</item>
    <item>Bajipura</item>
    <item>Cenral Colony</item>
    <item>Hajira</item>
    <item>Kamrej</item>
    <item>Lajpor</item>
</string-array>
<string-array name="mumbai_area">
    <item>Adarsha Nagar</item>
    <item>Thane</item>
    <item>Centacruz</item>
    <item>Andheri</item>
    <item>Varsova</item>
    <item>Dadar</item>
</string-array>
<string-array name="pune_area">
    <item>Akurdi</item>
    <item>Bavada</item>
    <item>Chakan</item>
    <item>Daund</item>
    <item>Earth Stn</item>
    <item>Ganeshkhind</item>
</string-array>
<string-array name="banglore_area">
    <item>Indira Nagar</item>
    <item>Jay Nagar</item>
    <item>TipSandra</item>
    <item>Kora Mangala</item>
    <item>Rajaji Nagar</item>
    <item>White Field</item>
</string-array>

注意:此代码适用于动画汉堡菜单

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.content.res.Resources;
import android.util.Log;
import android.support.v4.widget.DrawerLayout;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONObject;
import android.widget.ListView;
import android.widget.FrameLayout;
import android.widget.SimpleExpandableListAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;

public class MainActivity extends ActionBarActivity {

  private String TAG = "MainActivity";

  private Activity mActivity;
  private DrawerLayout mDrawerLayout;
  private ListView mListView;
  private String[] mItems;
  private ActionBarDrawerToggle mActionBarDrawerToggle;

  @Override
  protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    setContentView(R.layout.activity_main);

    Log.d(TAG, "onCreate");

    mActivity = this;

    mItems = new String[]{"one", "two", "three"};
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
    mListView = (ListView)findViewById(R.id.drawer_list);
    mListView.setAdapter(new ArrayAdapter(mActivity, android.R.layout.simple_list_item_1, android.R.id.text1, mItems));
    mActionBarDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerLayout, R.string.drawer_open, R.string.drawer_close){
      @Override
      public void onDrawerClosed(View view) {
        super.onDrawerClosed(view);
        getSupportActionBar().setTitle("onDrawerClosed");
        invalidateOptionsMenu();
        syncState();
      }

      @Override
      public void onDrawerOpened(View drawerView) {
        super.onDrawerOpened(drawerView);
        getSupportActionBar().setTitle("onDrawerOpened");
        invalidateOptionsMenu();
        syncState();
      }
    };
    mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
    mActionBarDrawerToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    mActionBarDrawerToggle.syncState();
  }
}

activity_main.xml中

    

  <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
      android:id="@+id/drawer_frame"
      android:layout_width="match_parent"
      android:layout_height="match_parent" 
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      />

  </RelativeLayout>

  <ListView
    android:id="@+id/drawer_list"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="left"
    android:choiceMode="singleChoice"
    />

</android.support.v4.widget.DrawerLayout>

styles.xml

<resources>
  <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  </style>
  <style name="AppTheme" parent="AppBaseTheme">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
  </style>
  <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
  </style>
</resources>

答案 2 :(得分:1)

@ akkie4396,这样就可以了。

styles.xml

<resources>
  <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  </style>
  <style name="AppTheme" parent="AppBaseTheme">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
  </style>
  <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
  </style>
</resources>