如何在android中的两个微调器中显示相同的选定值?

时间:2015-04-24 10:16:17

标签: android android-layout android-spinner

我是android编程的新手。我的应用程序中有两个微调器的布局。两个微调器都填充了相同的值。如果我更改了第一个微调器的值,则第二个微调器也会替换为第一个微调器中选择的相同值。

任何人请重播必要的解决方案

2 个答案:

答案 0 :(得分:1)

您可以对两个微调器使用相同的adapter,或者使用两个填充相同元素的适配器。在后一种情况下,当修改一个适配器时,您将需要在两个适配器上使用notifyDataSetChanged()

答案 1 :(得分:0)

活动代码:

import android.app.Activity;
import android.os.Bundle;
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 Activity {

    Spinner spinner1,spinner2;

    private String[] numbers= {"One","Two","Three","Four","Five","Six", "Seven", "Eight","Nine", "Ten"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,  android.R.layout.simple_spinner_item, numbers);

        spinner1.setAdapter(adapter_state);
        spinner2.setAdapter(adapter_state);

        spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                spinner1.setSelection(position);
                spinner2.setSelection(position);
            }

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

            }
        });

        spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                spinner1.setSelection(position);
                spinner2.setSelection(position);
            }

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

            }
        });

    }
}

试试这个..希望它有所帮助..