【发布时间】:2011-12-02 22:55:52
【问题描述】:
我已尝试使用 this 链接,但无法让它用于微调器和单选按钮。
有没有更好或更简单的方法在不同种类的各种项目之间共享监听器?
编辑 - 我应该提到我想要共享侦听器的原因是我需要使用在其他类中使用时遇到问题的各种适配器。
【问题讨论】:
标签: android radio-button spinner listener
我已尝试使用 this 链接,但无法让它用于微调器和单选按钮。
有没有更好或更简单的方法在不同种类的各种项目之间共享监听器?
编辑 - 我应该提到我想要共享侦听器的原因是我需要使用在其他类中使用时遇到问题的各种适配器。
【问题讨论】:
标签: android radio-button spinner listener
你可以定义一个类来实现 Spinner 和单选按钮的监听器,
创建该类的一个实例,然后将该实例分配给单选按钮和微调器。 例如:
package italialinux.example;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
public class ButtonAction implements OnClickListener, OnItemSelectedListener {
TextView btnLocalText;
public ButtonAction(TextView tv) {
super();
btnLocalText = tv;
}
@Override
public void onClick(View arg0) {
btnLocalText.setText("Hello from a ButtonAction!!");
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
【讨论】:
如果您希望它们在单击时执行相同的功能,只需在 setOnClickListener() 方法中将相同的侦听器实例添加到每个视图/小部件。如果没有,那么您将不得不检测单击了哪个视图并相应地执行所需的操作
【讨论】:
我认为下面的代码示例就是你要找的
//the import for onClickListener you need is here (along with other imports --- you can get all of them by pressing ctrl+shift+o on Eclips IDE)
导入android.view.View.OnClickListener;
公共类 MyActivity 扩展 Activity 实现 OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button myButton = (Button) findViewById(R.id.myButtonId);
ImageView myImageView = (ImageView) findViewById(R.id.myImageViewId);
RadioButton myRadioButton = (RadioButton) findViewById(R.id.myRadioButtonId);
CheckBox myCheckBox = (CheckBox) findViewById(R.id.myCheckBoxId);
myButton.setOnClickListener(this);
myImageView.setOnClickListener(this);
myRadioButton.setOnClickListener(this);
myCheckBox.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.myButtonId:
// do the work here for Button click listener
break;
case R.id.myImageViewId:
// do the work here for Image click listener
break;
case R.id.myRadioButtonId:
// do the work here for RadioButton click listener
break;
case R.id.myCheckBoxId:
// do the work here for CheckBox click listener
break;
}
}
}
【讨论】: