java - 如何从另一个类中的另一个按钮调用一个按钮?
问题描述
我的 MainActivity 中有一个按钮我想在另一个按钮内的 SecondActivity 中调用它基本上两个按钮都做同样的事情
主要活动
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
});
第二活动
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Calling button from MainActivity
}
});
解决方案
在 utils 类中创建一个静态方法,例如返回 OnClickListener
public static View.OnClickListener getShareButtonClickListener(Activity activity) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(activity, "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
activity.startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(activity, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
};
}
在这两项活动中
share.setOnCLickListener(MyUtilsClass.getShareButtonClickListener(this))
但我同意@Abbas 最好将您的视图(活动/片段)和您的业务逻辑分开
推荐阅读
- swift - 无法创建 UICollectionReusableView 的 IBOutlet
- scala - why DataFrame still there in spark 2.2 also even DataSet gives more performance in scala?
- c++ - 使用 std::fill 初始化结构对象
- swift - UIViewControllers 共享“通用”IBAction
- angular - 数据在延迟后加载到 UI 上
- mysql - 验证用户名是否已存在
- php - 如何从 PHP 的下拉菜单中预先选择一个选项
- python-3.x - 客户端连接后通过ws从其他类发送数据
- c# - 为什么 context.SaveChanges() 会更新表中的每一行?
- php - Laravel 在迁移时显示错误