簡體   English   中英

從MainActivity(Android)訪問另一個類中的公共無效

[英]Access public void in another class from MainActivity (Android)

我在一個名為Flashlight的類中有兩個公共空隙,分別是:

公共無效turnOnFlashLight()

公共無效turnOffFlashLight()

如何在“主要活動”中訪問這些內容?

我已經找到了許多指南,用於在MainActivity中使用另一個類,而不是僅用於訪問特定部分(在這種情況下,我試圖打開或關閉手電筒)。

這是MainActivity的內容

public class MainActivity extends android.support.v7.app.ActionBarActivity {

@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    httpserver();

public void httpserver() {
    AsyncHttpServer server = new AsyncHttpServer();
    java.util.List<WebSocket> _sockets = new java.util.ArrayList<WebSocket>();
    server.listen(5000);
    server.get("/flashon", new HttpServerRequestCallback() {
        static final int CAMERA_PIC_REQUEST = 0;
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            response.send("Ok");
            Flashlight.turnOnFlashLight();

        }
    });
}
}

這是Flashlight類https://stackoverflow.com/a/31289731/6696740

謝謝 :)

確保在MainActivity中導入了該類。 您應該只可以使用Flashlight.turnOnFlashLight()Flashlight.turnOffFlashLight( )。 您可能還想創建Flashlight類的實例,例如Flashlight flashlight = Flashlight.newInstance() ,然后創建flashlight.turnOnFlashLight()或Flashlight.turnOffFlashLight()。

在MainActivity中(假設FlashLight類的構造函數不需要任何輸入):

import Flashlight;
...
//where you need to call those methods
Flashlight flashLight = new Flashlight();
flashlight.turnOnFlashLight();
//OR
flashlight.turnOffFlashLight();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM