gpt4 book ai didi

java - 未定义类型 new View.OnClickListener(){}

转载 作者:行者123 更新时间:2023-11-30 02:37:57 24 4
gpt4 key购买 nike

当我将项目用作 public class HomeActivity extends Activity implements OnClickListener 并在其中使用 getContentResolver 时,它向我显示错误

未为类型 new View.OnClickListener() 定义方法 getContentResolver(){}

但是当我使用 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();
}

}
});

}
}

最佳答案

推理:


Because getContentResolver() is the method of the Context Class, not the method of View.OnClickListener Interface.

当你写这行的时候

InputStream is = this.getContentResolver().openInputStream(uri);

您正在使用 this 从 View.OnClickListener 接口(interface)调用方法,接口(interface)中不存在该方法,这就是 Android 给您错误的原因。

See Context class HereView.OnClickListener Here


回答:


声明一个全局上下文变量。

       // Global Var
Context context;

// In onCreate
context = this;

将此行更改为

       InputStream is = this.getContentResolver().openInputStream(uri);

这个:

       InputStream is = context.getContentResolver().openInputStream(uri);

关于java - 未定义类型 new View.OnClickListener(){},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26204196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com