根据其他数组显示一个数组值

时间:2014-05-14 06:37:21

标签: android arrays

我已经创建了数组。一个是美国的所有州(Full Form),另一个是美国各州的简称。我已经在一个微调器中显示了状态(完整形式)。现在我是什么我要做的就是根据用户在微调器中选择的简短形式显示状态。我怎样才能实现它。

2 个答案:

答案 0 :(得分:1)

您应该使用映射,即在两个数组中应该映射元素。我举个例子。

    String[] fullForm = { Alabama,  California,  Florida,   Illinois};
    String[] shortForm = {AL, CA, FL, IL};

    ArrayAdapter<String> ad = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,fullForm );

spinner.setAdapter(ad);

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                // TODO Auto-generated method stub


                Toast.makeText(getApplicationContext(), " You selected " + fullForm[position] + "\n Short form is : " + shortForm[position], Toast.LENGTH_SHORT).show();
            }

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

            }
        });

答案 1 :(得分:1)

// try this way,hope this will help you...

**activity_main.xml**

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

     <Spinner
         android:id="@+id/spnState"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</LinearLayout>

**MainActivity.java**

public class MainActivity extends Activity {

    Spinner spnState;
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_main);
        spnState = (Spinner) findViewById(R.id.spnState);
        String[] stateFullNameArray = new String[]{"statefullname1","statefullname2","statefullname3","statefullname4","statefullname5"};
        final String[] stateShortNameArray = new String[]{"stateshortname1","stateshortname2","stateshortname3","stateshortname4","stateshortname5"};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,stateFullNameArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnState.setAdapter(adapter);

        spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,stateShortNameArray[position],Toast.LENGTH_SHORT).show();
            }

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

            }
        });
    }


}