任何人都可以帮忙解决这个问题, 我试图在一个片段中添加一个微调器,使用自定义适配器,因为我的微调器将有动态字符串,困惑如何将微调器添加到片段,我尝试了下面的代码,并得到了ClassCastException:android.app.Application无法强制转换为android .widget.AdapterView $ OnItemSelectedListener Exception。
public class Questions_Fragment extends Fragment implements OnItemSelectedListener {
List<String> list_products = new ArrayList<String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater .inflate(R.layout.activity_questions, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//add data to List
list_products.add("0");
list_products.add("1");
list_products.add("2");
Spinner spinner = (Spinner)getActivity().findViewById(R.id.products_spinner);
int hidingItemIndex = 0;
CustomAdapter dataAdapter = new CustomAdapter(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item, list_products,
hidingItemIndex);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener((OnItemSelectedListener) getActivity().getApplicationContext());
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
if (position == 1) {
Log.d("Succes","Item Selected is 1");
}
}
class CustomAdapter extends ArrayAdapter<String> {
private int hidingItemIndex;
public CustomAdapter(Context questions_Fragment, int textViewResourceId,
List<String> list, int hidingItemIndex) {
super(questions_Fragment, textViewResourceId, list);
this.hidingItemIndex = hidingItemIndex;
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View v = null;
if (position == hidingItemIndex) {
TextView tv = new TextView(getContext());
tv.setVisibility(View.GONE);
v = tv;
} else {
v = super.getDropDownView(position, null, parent);
}
return v;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
由于你的Questions_Fragment
实现了监听器所以它应该是
spinner.setOnItemSelectedListener(this);