jjzjj

java - 同一级别的 If 语句如何同时在 Android/Java 程序中执行?

coder 2023-12-28 原文

目前,我正在研究为我们提供的名为 PaintPot 的 Android 程序的代码,该程序允许用户在他们的 Android 设备上进行手指绘画。

此代码处理当点击屏幕、单击按钮等时将发生的事件。

// Here is the event dispatcher for our app.  We need to Override the method for the Form
// superclass
@Override
public boolean dispatchEvent(Component component, String id, String eventName,
                             Object[] args) {

    //if the canvas is touched by a tapping finger
    if (component.equals(myCanvas) && eventName.equals("Touched")) {
        canvasTouced(((Float) args[0]).intValue(), ((Float) args[1]).intValue());
        return true;

        //if the canvas is touched by a dragging finger, paint the line this way
    } else if (component.equals(myCanvas) && eventName.equals("Dragged")) {
        drawLine(((Float) args[2]).intValue(),
                ((Float) args[3]).intValue(),
                ((Float) args[4]).intValue(),
                ((Float) args[5]).intValue());
        return true;

        //if the canvas is touched while the blue button is selected
    } else if (component.equals(btnBlue) && eventName.equals("Click")) {
        myCanvas.PaintColor(COLOR_BLUE);
        return true;

        //if the canvas is touched while the green button is selected
    } else if (component.equals(btnGreen) && eventName.equals("Click")) {
        myCanvas.PaintColor(COLOR_GREEN);
        return true;

        //if the canvas is touched while the red button is selected
    } else if (component.equals(btnRed) && eventName.equals("Click")) {
        myCanvas.PaintColor(COLOR_RED);
        return true;

        //if the wipe button is selected
    } else if (component.equals(btnWipe) && eventName.equals("Click")) {
        myCanvas.Clear();
        return true;
    }


    return false;
}

代码运行良好,并且“按原样”执行我希望的操作。但我真正不明白的是,如果用户在 Canvas 上点击或拖动他或她的手指的 if 语句处于“同一级别”,或者如果选择了颜色按钮,则在同一 if 语句中。不应该是当用户在屏幕上点击或拖动他的手指时,确定是否制作一条线或一个点的相同代码也应该询问线或点应该是什么颜色,而不仅仅是大小点,取决于选择什么颜色的按钮?

为了更完整的引用,这里是完整的代码,如果有人好奇的话:

import android.graphics.Color;
import com.google.devtools.simple.runtime.components.android.Button;
import com.google.devtools.simple.runtime.components.Component;
import com.google.devtools.simple.runtime.components.HandlesEventDispatching;
import com.google.devtools.simple.runtime.components.android.Canvas;
import com.google.devtools.simple.runtime.components.android.Form;
import com.google.devtools.simple.runtime.components.android.HorizontalArrangement;
import com.google.devtools.simple.runtime.components.android.Label;
import com.google.devtools.simple.runtime.events.EventDispatcher;


import java.util.Random;




public class PaintPotActivity extends Form implements HandlesEventDispatching {


private Canvas myCanvas; //creates a canvas object
private Label lblStatus; //creates a label that discusses the status of the program
private Button btnRed; //creates a button for red paint
private Button btnBlue; // "" for blue paint
private Button btnGreen; // "" for green paint


private Button btnWipe; //creates a button that wipes the screen clean
private Button btnDotSize; // creates a button that changes the dot size




// Variable (field) used to for displaying number of touches
int numTouches; //declares an integer that lists out the number of touches a user made


// The equivalent to a "main" method for App Inventor apps is the $define method.
void $define() { 


    //We are going to place the color buttons in a HorizontalArrangement
    HorizontalArrangement hr = new HorizontalArrangement(this);
    btnRed = new Button(hr); 
    btnBlue = new Button(hr);
    btnGreen = new Button(hr);


    //set their color
    btnRed.BackgroundColor(Color.RED);
    btnBlue.BackgroundColor(Color.BLUE);
    btnGreen.BackgroundColor(Color.GREEN);

    //set the button text
    btnRed.Text("Red");
    btnBlue.Text("Blue");
    btnGreen.Text("Green");


    //canvas into its own HorizontalArrangement
    hr = new HorizontalArrangement(this);
    myCanvas = new Canvas(hr);
    myCanvas.Width(400);
    myCanvas.Height(400);
    myCanvas.LineWidth(10);


    //Wipe and a label into its own HorizontalArrangement
    hr = new HorizontalArrangement(this);
    btnWipe = new Button(hr);
    btnWipe.Text("Wipe");


    lblStatus = new Label(hr);
    lblStatus.Text("  touchX/touchY:");


    // Register for events.  By the second argument can be any string.    The third argument must
    // exactly match the name of the event that you want to handle for that component.  When the event
    // happens, dispatchEvent will be called with these arguments.
    EventDispatcher.registerEventForDelegation(this, "JavaBridge", "Touched");
    EventDispatcher.registerEventForDelegation(this, "JavaBridge", "Click");
    EventDispatcher.registerEventForDelegation(this, "JavaBridge", "Dragged");
}


// Here is the event dispatcher for our app.  We need to Override the method for the Form
// superclass
@Override
public boolean dispatchEvent(Component component, String id, String eventName,
                             Object[] args) {

    //if the canvas is touched by a tapping finger
    if (component.equals(myCanvas) && eventName.equals("Touched")) {
        canvasTouced(((Float) args[0]).intValue(), ((Float) args[1]).intValue());
        return true;

        //if the canvas is touched by a dragging finger, paint the line this way
    } else if (component.equals(myCanvas) && eventName.equals("Dragged")) {
        drawLine(((Float) args[2]).intValue(),
                ((Float) args[3]).intValue(),
                ((Float) args[4]).intValue(),
                ((Float) args[5]).intValue());
        return true;

        //if the canvas is touched while the blue button is selected
    } else if (component.equals(btnBlue) && eventName.equals("Click")) {
        myCanvas.PaintColor(COLOR_BLUE);
        return true;

        //if the canvas is touched while the green button is selected
    } else if (component.equals(btnGreen) && eventName.equals("Click")) {
        myCanvas.PaintColor(COLOR_GREEN);
        return true;

        //if the canvas is touched while the red button is selected
    } else if (component.equals(btnRed) && eventName.equals("Click")) {
        myCanvas.PaintColor(COLOR_RED);
        return true;

        //if the wipe button is selected
    } else if (component.equals(btnWipe) && eventName.equals("Click")) {
        myCanvas.Clear();
        return true;
    }


    return false;
}




/**
 * This method will get the touched touchX, touchY coordinates and will then create a circle
 * of random radius (between 1 to 33) with the color that was selected (RED, BLUE or GREEN).
 * It will also display the touched touchX,touchY coordinates.
 * @param x current x
 * @param y current y
 */
private void canvasTouced(int x, int y) {


    myCanvas.DrawCircle(x, y, new Random().nextInt(33));
    lblStatus.Text("  touchX/touchY:" + x + "/" + y + " touches: " + ++numTouches);


}


/**
 * Method to draw line
 * @param prevX last touch x
 * @param prevY last touch y
 * @param touchX current x
 * @param touchY current y
 */
private void drawLine(int prevX, int prevY, int touchX, int touchY) {
    myCanvas.DrawLine(prevX, prevY, touchX, touchY);
 }


}

最佳答案

dispatchEvent 在应用程序触发事件时被调用。每次按钮点击和与应用程序的交互都会引发单独的事件。每个 if 语句都决定了如何处理不同类型的事件。

Shouldn't it be when the user taps or drags his finger across the screen, the same code that determines if a line or a dot that is made should also ask for what color the line or dot should be, rather than just size of the dot, depending on what color button is selected

在这种情况下,事件之间的状态保存在 myCanvas 中 - 单击 btnBlue 将 Canvas 上的绘画颜色设置为蓝色 (myCanvas.PaintColor( COLOR_BLUE);) 然后等待另一个事件发生。如果用户随后在 Canvas 上拖动,则会绘制一条线(最终 myCanvas.DrawLine(prevX, prevY, touchX, touchY);)。由于 myCanvas 记住了状态,所以它以蓝色绘制线。

关于java - 同一级别的 If 语句如何同时在 Android/Java 程序中执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15008695/

有关java - 同一级别的 If 语句如何同时在 Android/Java 程序中执行?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  5. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  6. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  7. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐