简体   繁体   English

Android操作栏上带有按钮的调用方法

[英]Call method with button on Android Action Bar

I have two classes at the moment, MainActivity and DrawView . 目前,我有两个类, MainActivityDrawView The DrawView is working fine and creating a canvas that allows me to draw lines. DrawView运行正常,并创建了一个允许我绘制线条的画布。 What I have no idea how to do is when I click the button I've placed on the Action Bar it saves whatever is drawn on the canvas as an image. 我不知道该怎么办,是当我单击放置在操作栏上的按钮时,它将在画布上绘制的任何内容保存为图像。

I don't know how to use the segment of code below from my MainActivity class. 我不知道如何使用MainActivity类中的以下代码段。 Do I need to create a new class with a method in it or can I create the method within the MainActivity class (in relation to the line "//method goes here")? 我是否需要在其中创建一个带有方法的新类,还是可以在MainActivity类中创建该方法(相对于“ //方法在这里”这一行)? I'm also assuming I have to retrieve the canvas object, from DrawView , and pass it to the method as a parameter. 我还假设我必须从DrawView检索canvas对象,并将其作为参数传递给方法。 How do I do that when it's in the DrawView object? 当它在DrawView对象中时该怎么办?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    drawView = new DrawView(this);
    setContentView(drawView);
    drawView.requestFocus();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
  switch (item.getItemId()) {
    case R.id.action_save:
       //method goes here
       return true;
    default:
       return super.onOptionsItemSelected(item);
  }
}

Create a field called drawView that is private but accessible throughout the class like this: 创建一个名为drawView的字段,该字段是私有的,但可在整个类中访问,如下所示:

private DrawView drawView;

Set it in the onCreate method like you already do now: 像现在一样在onCreate方法中进行设置:

drawView = new DrawView(this);

Now you can access the drawView variable in your onOptionsItemSelected method. 现在,您可以在onOptionsItemSelected方法中访问drawView变量。 This means that you can access all public variables in that class. 这意味着您可以访问该类中的所有公共变量。 If you store your draw path in a public variable you can access it. 如果将绘制路径存储在公共变量中,则可以访问它。 You can do that by making the canvas a public field in your DrawView class. 您可以通过将画布设为DrawView类中的公共字段来实现。 Just like you made the DrawView a private field in your MainActivity class. 就像您将DrawView设置为MainActivity类中的私有字段一样。

You should be able to access the canvas like this. 您应该能够像这样访问画布。

Make the field in DrawView: 在DrawView中创建字段:

public Canvas canvas;

And you can access it like this: 您可以像这样访问它:

drawView.canvas;

Invoke method from your action bar button and write code for save in that method . 从操作栏按钮调用方法,并编写代码以保存在该方法中。 if method is in other class use static keyword to call that method and define that method static or you can create class object to access it. 如果方法在其他类中,请使用static关键字来调用该方法并将该方法定义为static,或者您可以创建类对象以对其进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM