当我将项目用作public class HomeActivity extends Activity implements OnClickListener
并在其中使用getContentResolver
时,它会显示错误
The method getContentResolver() is undefined for the type new View.OnClickListener(){}
但是当我使用public class HomeActivity extends ActionBarActivity
时,它适用于我,但我如何处理它public class HomeActivity extends Activity implements OnClickListener
代码:
public class HomeActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnEdit = (Button) findViewById(R.id.btn_edit);
btnEdit.setOnClickListener(this);
btnGallery = (Button) findViewById(R.id.btn_gallery);
btnGallery.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.btn_edit:
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_IMAGE);
// startActivityForResult(
// Intent.createChooser(intent, "Select Photo"),
// MyConstants.TAKE_PHOTO);
break;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {return;}
if (requestCode == REQUEST_IMAGE) {
final Uri uri = data.getData();
Button button= (Button) findViewById(R.id.btn_camera);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try
{
InputStream is = this.getContentResolver().openInputStream(uri);
final Bitmap bmInImg = BitmapFactory.decodeStream(is);
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
答案 0 :(得分:1)
因为
getContentResolver()
是上下文类的方法,而不是View.OnClickListener Interface
的方法。
当你写这一行时
InputStream is = this.getContentResolver().openInputStream(uri);
您正在使用this
从View.OnClickListener接口调用该方法,这在接口中不存在,这就是Android为您提供错误的原因。
声明一个gloabal Context
变量。
// Global Var
Context context;
// In onCreate
context = this;
将此行更改为
InputStream is = this.getContentResolver().openInputStream(uri);
:此:强>
InputStream is = context.getContentResolver().openInputStream(uri);
答案 1 :(得分:0)
在这一行:
InputStream is = this.getContentResolver().openInputStream(uri);
"这"指的是您正在创建的ClickListener。你需要使用"这个"这样的封闭类:
InputStream is = HomeActivity.this.getContentResolver().openInputStream(uri);