报错: Android studio 使用 setOnClickListener()方法时无法使用单个view以外的多个view添加 setOnClickListener()的方法。
出现场景: 平时是一个按钮绑定一个事件,现在有多个按钮,需要添加多个事件,不想像单个view添加事件一样,在参数内重写View.OnClickListener下的onClik方法,会导致代码过于冗余,没有可读性。
环境: Android 10.0
尝试: 首先是上C站看了几个高赞答案,其中最符合的是
Button btn = (Button) findViewById(R.id.mybutton);
Button btn2 = (Button) findViewById(R.id.mybutton2);
btn.setOnClickListener(listener);
btn2.setOnClickListener(listener);
View.OnClickListener listener = View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.mybutton:
break;
case R.id.mybutton2:
break;
}
}
转自:Android Studio 中 View 的 setOnClickListener 添加方法(不能用this)
此类方法中我的onClick(View v)中的v会报错,显示Cannot resolve symbol ‘view’
解决: 在尝试中,发现上述代码中没有new View对象,导致无法重写View.OnClickListener()中的onClik()方法,解决办法就是在上述代码中,View.OnClickListener()前添加new。(这也说明了写博客的时候要注意上下文的问题,否则容易让读者云里雾里)
完整代码:
private TextView txt_topbar;
private TextView txt_channel;
private TextView txt_message;
private TextView txt_better;
private TextView txt_setting;
private FrameLayout ly_content;
View.OnClickListener handler = null;
txt_topbar = findViewById(R.id.txt_topbar);
ly_content = findViewById(R.id.ly_content);
txt_channel = findViewById(R.id.txt_channel);
txt_better = findViewById(R.id.txt_better);
txt_message = findViewById(R.id.txt_message);
txt_setting = findViewById(R.id.txt_setting);
handler = new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentTransaction fTransaction = fManager.beginTransaction();
hideAllFragment(fTransaction);
switch (view.getId()){
case R.id.txt_channel:
setSelected();
txt_channel.setSelected(true);
if(fg1 == null){
fg1 = new MyFragment("第一个fragment");
fTransaction.add(R.id.ly_content, fg1);
}else {
fTransaction.show(fg1);
}
break;
case R.id.txt_message:
setSelected();
txt_message.setSelected(true);
if(fg2 == null){
fg2 = new MyFragment("第二个fragment");
fTransaction.add(R.id.ly_content, fg2);
}else {
fTransaction.show(fg2);
}
break;
case R.id.txt_better:
setSelected();
txt_better.setSelected(true);
if(fg3 == null){
fg3 = new MyFragment("第三个fragment");
fTransaction.add(R.id.ly_content, fg3);
}else {
fTransaction.show(fg3);
}
break;
case R.id.txt_setting:
setSelected();
txt_setting.setSelected(true);
if(fg4 == null){
fg4 = new MyFragment("第四个fragment");
fTransaction.add(R.id.ly_content, fg4);
}else {
fTransaction.show(fg4);
}
break;
}
fTransaction.commit();
}
};
txt_channel.setOnClickListener(handler);
txt_better.setOnClickListener(handler);
txt_message.setOnClickListener(handler);
txt_setting.setOnClickListener(handler);
|