Android:如何从Spinner获取所选项目的ID

时间:2014-11-08 05:32:02

标签: android spinner android-spinner

在我的情况下,我想从Spinner获取所选项目的ID。我的模态类中有两个字段,分别是id和name。我列出了所有数据,并将此列表设置为适配器。我试图通过使用getSelectedItem()方法获取selectedItem Id。但我只能获得项目列表的第一个id。

这是我的代码。

public class ModifyEventFragment extends DialogFragment{
Context context;
CalEvent eve;
Project proj;
Spinner eventType,stage;
public static String eid,pid,type;
public static List<EventType> event_type;
public static List<ProjectStatus> cust_stage;
EditText where,when,who,notes;
String eve_type,stage_val,when_val,who_val,notes_val;
String modified_where,modified_who,modified_when,modified_notes;
public ModifyEventFragment(Project proj)
{
    this.proj=proj;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.modify_project_event, container,
            false);
    context = rootView.getContext();
    eventType = (Spinner) rootView.findViewById(R.id.modifyEventType);
    stage =(Spinner) rootView.findViewById(R.id.modifyStage);
    where = (EditText)rootView.findViewById(R.id.modifyWhere);
    who = (EditText)rootView.findViewById(R.id.modifyWho);
    when = (EditText)rootView.findViewById(R.id.modifyWhen);
    notes =(EditText) rootView.findViewById(R.id.modifyNotes);
    eve = CalEvent.getCalEvent(ProjectEventFragment.calevent.eve_id);
    event_type = EventType.listAll();
    CustomEventTypeAdapter adapter = new CustomEventTypeAdapter(context, event_type);
    eventType.setAdapter(adapter);
    type=((EventType)eventType.getSelectedItem()).et_id;
    cust_stage = ProjectStatus.listAll();
    CustomStatusAdapter adapter1 = new CustomStatusAdapter(context, cust_stage);
    stage.setAdapter(adapter1);
    where.setText(eve.followup_location.toString());
    where.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_where = s.toString();
        }
    });
    who.setText(eve.person_met.toString());
    who.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_who = s.toString();
        }
    });
    when.setText(eve.event_start.toString());
    when.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_when = s.toString();
        }
    });
    notes.setText(eve.notes.toString());
    notes.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            modified_notes = s.toString();
        }
    });
    Button save = (Button) rootView.findViewById(R.id.modifyeventsave);

    save.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            eve.followup_location = modified_where;
            eve.event_start = modified_when;
            eve.person_met = modified_who;
            eve.notes = modified_notes;
            System.out.println("print type"+type);
            eve.save();
            ProjectEventFragment.adapter.notifyDataSetChanged();
        }
    });

    return rootView;
}

这是CustomEventType适配器代码。

public class CustomEventTypeAdapter extends BaseAdapter{
Context ctx;
List<EventType> ps;
LayoutInflater inflater;
public CustomEventTypeAdapter(Context ctx,List<EventType> ps)
{
    this.ctx=ctx;
    this.ps=ps;
    inflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return ps.size();
}

@Override
public EventType getItem(int position) {
    // TODO Auto-generated method stub
    return ps.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return ps.get(position).getId();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    if (convertView == null)
        rowView = inflater.inflate(R.layout.spinner_item_local, parent,
                false);
    TextView textView = (TextView) rowView.findViewById(R.id.spinner_item_text);

    EventType proj = getItem(position);
    try {
        textView.setText(proj.name);

    } catch (Exception e) {

    }

    return rowView;
}

有人可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:2)

从我的班级分享示例代码以获取所选的项目ID -

spinner1 .setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                spinner1 = parent.getItemAtPosition(position).toString();
                count = position; //this would give you the id of the selected item
            }

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

干杯:)

答案 1 :(得分:2)

使用position:

从适配器列表夹中获取所选项目数据
eventType.setOnItemSelectedListener(new OnItemSelectedListener() {
     @Override
     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
         String id = event_type.get(position).getId();
     }

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

     }
});

答案 2 :(得分:0)

在您的微调器上使用view.OnItemSelectedListener,您将在int中获得一个位置,您可以将其用作所选项目的ID

答案 3 :(得分:0)

您有一个 @Service public class PersonServiceImpl implements PersonService { @Autowired private PersonRepository personRepository; @Override public Person updatePerson(Person oldPerson) throws Exception { oldPerson.setId(oldPerson.getId()) ; // pass the associated id for which you want to update and set that id to the same person [ basically setting the same id to the oldPerson ] this way it will not create new entry because here we are not making new ID ] //oldPerson.set others [ what is to be updated ] return personRepository.save(oldPerson); // now save [old person with updated content but same id as it was before ] } } bean。现在,其中有bot.on('message', message => { if (message.member.hasPermission("ADMINISTRATOR")) { if (!message.guild) return; if (message.content.startsWith('+kick')) { const user = message.mentions.users.first(); if (user) { const member = message.guild.member(user); if (member) { member .kick('Optional reason that will display in the audit logs') .then(() => { message.reply(`Successfully kicked ${user.tag}`); }) .catch(err => { message.reply('I was unable to kick the member'); console.error(err); }); } else { message.reply("That user isn't in this guild!"); } } else { message.reply("You didn't mention the user to kick!"); } } } }); 个方法ProjectStatus

Override

然后制作String toString()并将其设置在public class ProjectStatus { private Integer id; // Long, String any type private String name; // more properties if you need @Override // Mandatory public String toString() { return name; // name + " ("+id+")"; // can also be returned } // Getter & Setter } 中,以使用状态选项加载Spinner。

ArrayAdapter<ProjectStatus>

现在选择Spinner,它是任何//Task 1. List<ProjectStatus> cust_stages = ProjectStatus.listAll(); // Or using any JSON Data OR API call; //Task 2. ArrayAdapter<ProjectStatus> statusAdapter = new ArrayAdapter<ProjectStatus>( this, android.R.layout.simple_spinner_item, cust_stages ); statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //Task 3. Spinner stage =(Spinner) rootView.findViewById(R.id.modifyStage); stage.setAdapter(statusAdapter); 中的属性,如下所示。

ProjectStatus