这是源代码:
package com.example.test44; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.content.DialogInterface.OnClickListener; //关注这里,包导错了 import android.widget.Button; import android.widget.ProgressBar; public class MainActivity extends Activity { private ProgressBar firstBar =null; private ProgressBar secondBar = null; private Button myButton = null; private int i = 0 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firstBar = (ProgressBar)findViewById(R.id.firstBar); secondBar = (ProgressBar)findViewById(R.id.secondBar); myButton = (Button)findViewById(R.id.myButton); myButton.setOnClickListener(new ButtonListener()); } class ButtonListener implements OnClickListener{ public void onClick(View v) { if(i == 0) { //设置进度条处于可见的状态 firstBar.setVisibility(View.VISIBLE); firstBar.setMax(150); secondBar.setVisibility(View.VISIBLE); } else if ( i < firstBar.getMax()){ //设置主进度条的当前值 firstBar.setProgress(i); //设置第二进度条的当前值 firstBar.setSecondaryProgress(i + 10); //因为默认的进度条无法显示进行的状态 //secondBar.setProgress(i); } else{ //设置进度条处于不可见状态 firstBar.setVisibility(View.GONE); secondBar.setVisibility(View.GONE); } i = i + 10 ; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
这时会有错,显示:The type MainActivity.ButtonListener must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int)
解决办法是:方法一.将class ButtonListener implements OnClickListener{}改为android.view.View.OnClickListener
方法二.将导入的包import android.content.DialogInterface.OnClickListener;给删了,导入import android.view.View.OnClickListener;包
而导致这个问题的原因则是:我们最开始给写的OnClickListener导入包时导错了,应该导入的包是import android.view.View.OnClickListener;结果却导成了import android.content.DialogInterface.OnClickListener;这两个方法是不同的:一个是对话框对应按钮的点击监听器,另外一个是普通View的点击监听器。
参考链接:CSDN论坛:继承OnClickListener 为什么会出错 改为android.view.View.OnClickListener就没问题了
百度知道:The type new View.OnClickListener(){} must implement the inherited abstract method View.Onclicklis