这是我的代码......
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
text.setText("Application Created");
btn1 = (Button) findViewById(R.id.Mybutton);
btn1.setOnClickListener(this);
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(this);
btn1.setOnLongClickListener(**this**);*(Error Generated here)*
}
public boolean onLongClick( View v)
{
return true;
}
我试图在两个以上的按钮上使用长按侦听器,并使用switch case在单个方法(public boolean onLongClick(View v))中处理它们。我尝试了我的代码,但是当我传递 btn1.setOnLongClickListener(this); “this”在括号中“我正在同一个类中处理此事件时,它们是生成的错误。”
答案 0 :(得分:0)
btn1.setOnLongClickListener(本);
并使用View.OnLongClickListener
然后覆盖此方法
@Override
public boolean onLongClick(View view) {
switch(view.getId()){
case R.id. :
break;
}
return false;
}
答案 1 :(得分:0)
要使用 this 作为OnLongClickListener,您的类应该实现接口View.OnLongClickListener及其方法,例如:
public class MyActivity extends AppCompatActivity implements View.OnLongClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
btn1.setOnLongClickListener(this);
}
@Override
public boolean onLongClick(View view) {
// your code here
}
}
我相信你已经为btn2.setOnClickListener(this)和OnClickListener接口做了同样的事。
答案 2 :(得分:0)
1)使用View.OnLongClickListener接口实现您的活动
2)覆盖布尔方法将生成onLongClick,您可以在其中为按钮编写开关大小写。
3)使用setOnLongClickListener(this)将按钮初始化为button.setOnLongClickListener(this);
[onCreate]
示例如下 -
public class MainActivity extends AppCompatActivity implements View.OnLongClickListener{
private Button btnOne, btnTwo, btnThree;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOne = (Button) findViewById(R.id.idBtnOne);
btnTwo = (Button) findViewById(R.id.idBtnTwo);
btnThree = (Button) findViewById(R.id.idBtnThree);
btnOne.setOnLongClickListener(this);
btnTwo.setOnLongClickListener(this);
btnThree.setOnLongClickListener(this);
}
@Override
public boolean onLongClick(View v) {
switch(v.getId()){
case R.id.idBtnOne:
Toast.makeText(MainActivity.this,"Long pressed on Button 1",Toast.LENGTH_LONG).show();
break;
case R.id.idBtnTwo:
Toast.makeText(MainActivity.this,"Long pressed on Button 2",Toast.LENGTH_LONG).show();
break;
case R.id.idBtnThree:
Toast.makeText(MainActivity.this,"Long pressed on Button 3",Toast.LENGTH_LONG).show();
break;
default:
break;
}
return false;
}
}