使用带有setOnItemSelectedListener的Spinner和List视图

时间:2014-06-22 19:22:50

标签: android listview android-listview spinner

我应该创建一个任务,我有一个用String数组x连接的微调器,这个数组包含三个值,所以我想在点击旋转器的任何选择时,一个特定的列表视图将给出一个特定的三个值,这是我的代码:

public class Four extends ActionBarActivity {
String x [] = {"Jordan","Saudi Arabia", "Syria"};
String Jordan[] = {"Amman","Aqaba","Sarqa"};
String Saudi[] = {"Riyadh","Jeddah","Khobar"};
String Syria[] = {"Hems","Halab","Demashk"};

Spinner sp1 ;
ListView lv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.four);

    lv1 = (ListView)findViewById(R.id.listView1);

    // Jordan List View
    ArrayAdapter<String> jor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Jordan);
    lv1.setAdapter(jor);

    // Saudi Arabia List View
    ArrayAdapter<String> saud = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Saudi);
    lv1.setAdapter(saud);

    // Syria List View
    ArrayAdapter<String> syr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Syria);
    lv1.setAdapter(syr);




    sp1 = (Spinner)findViewById(R.id.spinner1);
    ArrayAdapter<String> a = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , x);
    sp1.setAdapter(a);

    sp1.setOnItemSelectedListener(new OnItemSelectedListener() {

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


        }


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

        }
    });




}

}

1 个答案:

答案 0 :(得分:0)

onItemSelected()的thir参数(示例中为int arg2,但我建议您重命名)是您在Spinner中选择的位置。所以你可以像这样实现这个方法:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
    if (position == 0)
        lv1.setAdapter(jor);
    else if (position == 1)
        lv1.setAdapter(saud);
    else if (position == 1);
        lv1.setAdapter(syr);
}

请记住,所有涉及的变量(lv1,jor,saud,syr)必须定义为在匿名类中使用的final,例如

final ArrayAdapter<String> jor = ...
final ArrayAdapter<String> saud = ...