以编程方式创建微调器

时间:2011-05-28 00:32:59

标签: android

我必须创建一个不在我的布局中的Spinner。

所以我想创建它Programmatic我在My Activity类中编写以下代码

Spinner spinner = new Spinner(this);
String option[]={"By Date","By Transaction ID","By Customer Phone"};
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,option);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item );
spinner.setAdapter(spinnerArrayAdapter);
spinner.performClick();
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parentview, View v,int position, long id)
    {
        Log.d("in select","yes");
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) 
    {
        Toast.makeText(MainMenu.this,"no",Toast.LENGTH_LONG).show();
        Log.d("In No select","No");
    }
});

所以我的问题是我如何访问活动中的微调器选定项目

2 个答案:

答案 0 :(得分:2)

在听众之外访问它的唯一方法是创建一个保持位置的变量,以便稍后使用它。 像这样:

public class YourActivity extends Activity {
    private int curPos;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    Spinner spinner = new Spinner(this);
    String option[]={"By Date","By Transaction ID","By Customer Phone"};
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,option);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item );
    spinner.setAdapter(spinnerArrayAdapter);
    spinner.performClick();
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentview, View v,int position, long id)
        {
            curPos = position;
            Log.d("in select","yes");
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) 
        {
            Toast.makeText(MainMenu.this,"no",Toast.LENGTH_LONG).show();
            Log.d("In No select","No");
        }
    });
}

答案 1 :(得分:1)

onItemSelected

@Override
public void onItemSelected(AdapterView<?> parentview, View v,int position, long id)
{
    Log.d("in select","yes");
}

position可帮助您检索所选项目。在你的情况下,它应该是:

option[position]