0

在下面的代码中,他们OnItemSelectedListener直接实例化了内部setOnItemSelectedListener()方法,但它是一个接口,下面的代码如何正常工作,请向任何人解释...

public void addListenerOnSpinnerItemSelection() {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
                Toast.makeText(parent.getContext(), "OnItemSelected: " +parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();

            }

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

            }
        });
    }
4

3 回答 3

1

" new OnItemSelectedListener()" 将创建该接口的一个对象,这个对象是我们正在使用的spinner1.setOnItemSelectedListener()

它类似于:

OnItemSelectedListener listener = new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
                    Toast.makeText(parent.getContext(), "OnItemSelected: " +parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();

                }

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

                }
            });

spinner1.setOnItemSelectedListener(listener);
于 2013-07-05T10:03:00.873 回答
0

因为它的匿名类。

  1. 匿名类同时声明和初始化。

  2. 匿名类必须扩展或实现一个且只有一个类或接口。

  3. 由于匿名类没有名字,所以只能使用一次。

例如:

 button.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}
});
于 2013-07-05T10:27:33.967 回答
0

我在适配器中使用微调器来获取开始时间,所以这是我的代码,只需实现 AdapterView.OnItemSelectedListener 即可:

((ViewHolder) viewHolder).startTimeSpinner.setTag(R.id.startTimeSpinner, viewHolder);

((ViewHolder) viewHolder).startTimeSpinner.setOnItemSelectedListener(this);

@覆盖

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    switch (parent.getId()) {

        case R.id.startTimeSpinner:
            ViewHolder holder = (ViewHolder) parent.getTag(R.id.startTimeSpinner);
            mFromSelectedItemPosition = holder.startTimeSpinner.getSelectedItemPosition();
            mFromSelectedTime = holder.startTimeSpinner.getSelectedItem().toString();
            mFromAmPmSelectedItem = holder.startTimeSpinner.getSelectedItem().toString();
            break;
    }
}
于 2019-06-15T10:56:11.607 回答