开发者

Create Spinner Programmatically

开发者 https://www.devze.com 2023-03-09 02:22 出处:网络
I have to create a Spinner which is not in my Layout. so I want to create it Programmatic I write the following code in My Activity class

I have to create a Spinner which is not in my Layout.

so I want to create it Programmatic I write the following code in My Activity class

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");
    }
});

so My question is how I can access the spinner selected item 开发者_高级运维in the activity


Your only way to access it outside your listener is making a variable that will hold the position, so you would use it later. Something like this:

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");
        }
    });
}


In your onItemSelected:

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

The position helps you to retrieve your selected item. Which, in your case, it should be:

option[position]
0

精彩评论

暂无评论...
验证码 换一张
取 消