我有一个由微调控制器和按钮组成的片段。您可以使用微调器选择四个选项中的一个,然后该按钮将带您进入下一个活动。在同一个片段中实现多个事件侦听器 - Android
为了实现微调,我需要在Fragment上实现onItemSelectedListener,但要使用我需要实现onClickListener的按钮。 但我不能这两个? 我原以为这是一件非常简单的事情,并且需要在View上拥有多个不同的Event侦听器,所以您如何实现这一点?
这里是我使用的代码: -
公共类FragmentTypeSelect扩展片段 工具OnItemSelectedListener {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
// set the view so that it can be referenced
View theView = inflater.inflate(R.layout.fragment_type_select,
container,false);
// set OnClickListener for the button
setUpClickListener(theView,R.id.but_select);
//===============================
// NEW TYPE SPINNER
//===============================
Spinner spinner = (Spinner) theView.findViewById(R.id.new_type_spinner);
spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.types_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
return theView;
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id)
{
TextView headingText = (TextView)getView().findViewById(R.id.new_diet_type_text_heading);
TextView detailText = (TextView)getView().findViewById(R.id.new_diet_type_text_detail);
if (pos == 0)
{
headingText.setText(R.string.heading_type_1);
detailText.setText(R.string.detail_type_1);
}
if (pos == 1)
{
headingText.setText(R.string.heading_type_2);
detailText.setText(R.string.detail_type_2);
}
if (pos == 2)
{
headingText.setText(R.string.heading_type_3);
detailText.setText(R.string.detail_type_3);
}
if (pos == 3)
{
headingText.setText(R.string.heading_type_4);
detailText.setText(R.string.detail_type_4);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void onClick(View view){
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();
}
private void setUpClickListener(View theView, int childViewID) {
View childView = theView.findViewById(childViewID);
childView.setOnClickListener((OnClickListener) this);
}
}
本来我只是在微调和得到这个工作正常。然后,我尝试在onCreateView中设置OnClickListener并添加其他onClick和setUpClickListener方法。 这正是我在其他地方完成的,但在其他情况下,我没有其他事件要处理,并且使类实现了onClickListener。 Java不支持多个接口实现(据我了解),因此我的问题。
希望你能帮上忙。我可能有点厚,但对于整个面向对象以及Android来说,我还是比较新的。
你都可以做。发布你的代码,并更多地解释你的问题。 –
狮子座,我现在已经发布了上面的代码....谢谢 – RobT