我试过使用this链接,但我无法让它适用于微调和单选按钮。Android - 如何在微调器和单选按钮之间共享监听器?
是否有更好或更简单的方式在不同品种的不同项目之间共享听众?
编辑 - 我应该提到,我想分享听众的原因是我需要使用各种适配器,我在其他类中遇到了麻烦。
我试过使用this链接,但我无法让它适用于微调和单选按钮。Android - 如何在微调器和单选按钮之间共享监听器?
是否有更好或更简单的方式在不同品种的不同项目之间共享听众?
编辑 - 我应该提到,我想分享听众的原因是我需要使用各种适配器,我在其他类中遇到了麻烦。
可以定义实现监听两个微调和单选按钮类,
创建类的一个实例,然后将该实例分配到两个单选按钮和微调。 例如:
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扩展活动实现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;
}
}
}
不幸的是,它只是让我的程序崩溃。感谢您的尝试! – KRL
的问题是,我需要使用我在使用其他类的麻烦各种适配器。 – KRL
这不起作用? – Ivan
您在那里添加的奇妙示例,谢谢。对于其他人来说,像我自己一样,这是需要添加到你的按钮/旋钮/ misc来调用课程; clr.setOnClickListener(new ButtonAction('whatever value')); – KRL