如何在android中使用2个Spinners?

时间:2015-07-05 10:26:01

标签: android android-spinner

为什么这段代码不起作用?开关盒有什么问题吗? 我有2个旋转器(分支和学期)。选择分支时,它必须显示所选分支的Toast,并且与学期相同。

public class MainActivity extends Activity implements OnItemSelectedListener, OnClickListener{

Spinner branch, semester;
Button go;
TextView branchText, semText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    branch = (Spinner) findViewById(R.id.spinner1);
    semester = (Spinner) findViewById(R.id.spinner2);
    go = (Button) findViewById(R.id.button1);

    ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.Branch, android.R.layout.simple_spinner_item);
    branch.setAdapter(adapter);
    branch.setOnItemSelectedListener(this);

    ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this, R.array.Semester, android.R.layout.simple_spinner_item);
    semester.setAdapter(adapter1);
    semester.setOnItemSelectedListener(this);
    go.setOnClickListener(this);

}

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

    switch (view.getId())
    {
    case R.id.spinner1:
        branchText = (TextView) view;
        Toast.makeText(this, branchText.getText(), Toast.LENGTH_SHORT).show();
        break;
    case R.id.spinner2:
        semText = (TextView) view;
        Toast.makeText(this, semText.getText(), Toast.LENGTH_SHORT).show();
        break;
    }
}

3 个答案:

答案 0 :(得分:0)

SELECT sa.ContentID, SA.MSISDN, sa.DateRegistered AS minDate, sa.DateRegistered AS maxDate FROM sms.dbo.SubscriptionsArchive AS sa INNER JOIN (SELECT MSISDN, MIN(DateRegistered) AS mindate FROM sms.dbo.SubscriptionsArchive GROUP BY MSISDN) mysa ON sa.MSISDN = mysa.MSISDN AND sa.DateRegistered = mysa.mindate 更改为Toast.makeText(this, branchText.getText(), Toast.LENGTH_SHORT).show();
将所有Toast.makeText(this, branchText.getText().tostring(), Toast.LENGTH_SHORT).show();更改为branchText.getText()

答案 1 :(得分:0)

引用分支数组并使用位置来检索分支文本:

String[] branchArr = getResources().getStringArray(R.array.Branch);

case R.id.spinner1:
    Toast.makeText(this, branchArr[position], Toast.LENGTH_SHORT).show();
    break;

答案 2 :(得分:0)

您应该通过“AdapterView parent”获取所选项目的ID,而不是“View view”。

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

switch (parent.getId()){

case R.id.spinner1:
    branchText = (TextView) view;
    Toast.makeText(this, branchText.getText(), Toast.LENGTH_SHORT).show();
    break;

case R.id.spinner2:
    semText = (TextView) view;
    Toast.makeText(this, semText.getText(), Toast.LENGTH_SHORT).show();
    break;
  }
}