簡體   English   中英

Android從其他線程獲取EditText內容

[英]Android getting EditText content from other Thread

在我的問題中,我有MainActivity ,一個TextViewEditText以及一個方法,該方法應該向TextView發送消息並接收EditText的內容。 問題是從EditText接收文本,並使此方法等待用戶輸入

我將嘗試發布裁剪后的代碼,以便您將獲得一些有關我要實現的知識。

public class MainActivity extends Activity {

public class MonitorObject{
}
final MonitorObject mSync = new MonitorObject();
private TextView mConsoleOut;
private EditText mInputLine;
public String inputString;
public synchronized String getInputString(String value){this.inputString = value; return inputString;}

IOHandler IOhandler;

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

    mConsoleOut = (TextView) findViewById(R.id.consoleOut);
    mInputLine = (EditText) findViewById(R.id.actionInField);


    EditText editText = (EditText) findViewById(R.id.actionInField);
    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            synchronized (mSync){
                mSync.notify();
            }
            return true;
        }
    });
    GameCycle gameCycle = new GameCycle();
    Thread gameloop = new Thread(gameCycle);
    gameloop.start();
}

public class GameCycle implements Runnable{
    public void run(){
        game();
    }
}

public void game(){
findViewById(R.id.actionInField);
    Integer time=0;
    PlayerClass p1 = new PlayerClass(1,4);
    TileClass tile = new TileClass.Forest();
    Integer gamestate=0;


    while(gamestate==0){
        time++;
        tile.initialize_tilesettings(time, p1);
        tile.passed=true;
        List actionResponse=new ArrayList(Arrays.asList("repeat", "type", "returnval"));

        while(gamestate==0 && !actionResponse.get(1).equals("tileChange")){

            actionResponse=Arrays.asList("repeat", "type", "returnval");
            Boolean tileActions = true;

            while(!actionResponse.get(0).equals("continue")){
                //actions to be repeated

                String exe=null;

                tileActions=true;

                List<String> params = new ArrayList<>();

                <<<<<print>>>>>("\nWhat will you do?");

                synchronized (mSync){
                    try {
                        mSync.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                <<<<<getinput>>>>>String inp=returnInputString();
                String[] splitIn=inp.split(" ");


                for(String text:splitIn){
                    params.add(text.toLowerCase());
                }

                for(ActionClass action:p1.getActions()){
                    if(action.method.contains(params.get(0))){
                        exe=action.method;
                    }
                }

                if(exe==null){
                    <<<<<print>>>>>("Not a valid action");

                    actionResponse=Arrays.asList("repeat","","");
                }
                else{
                    try{
                        actionResponse=p1.excecFunctionByTag(exe, Arrays.asList(p1, tile, params));
                        if(actionResponse==null){
                            throw new RuntimeException();
                        }
                    }
                    catch (Exception e){
                        for(ActionClass action:p1.getActions()){
                            if(exe.equals(action.method)){
                                String actionEnt=action.actionEntry;
                                <<<<<print>>>>>("\nInvalid parameters, try: "+actionEnt);
                                actionResponse=Arrays.asList("repeat","","");
                            }
                        }
                    }
                    return;
                }


            }
        }
        if(gamestate==1){
            <<<<<print>>>>>('You died! Game over!\n\n<-<-< New Game >->->\n\n')
            game();
        }
        else if(gamestate==2){
            <<<<<print>>>>>("You have defeated the boss! Behind the fallen enemy you can see a path. You follow it and find a small village. You are safe!\n\n<-<-< New Game >->->\n\n")
            game();
        }
    }
}

我已經用<<<<< >>>>>標記了所需的輸入/輸出方法。

憐憫我的Java技能,因為這是我的第一個大型Java項目,整個結構都是從python轉換而來的。

再次感謝所有幫助。

問題很簡單,通常線程不會通知用戶界面或主線程。 為了解決這個問題,android有AsyncTask。 您可以將AsyncTask用作:

  1. 在onPreExecute()方法中初始化TextView和EditText。
  2. 發送或調用您的方法以在doInBackground()方法中發送所需的文本。
  3. 然后,您將在onPostExecute()方法中獲得結果。 在這里,您可以將setText()設置為您的EditText。

注意:AsyncTask是一個聯系到主ui線程的線程,為此它具有此onPostExecute()方法。

為了更好地了解AsyncTask,請檢查以下鏈接: http ://www.androidhive.info/2012/01/android-json-parsing-tutorial/

好的,據我所知,您想從UI中獲取一些文本(由UIThread處理),在工作線程上對其進行處理,然后將生成的文本再次發布到UI(UIThread)中的TextView中。

這就是我在MainActivity中要做的事情:

 final String line = editText.getText().toString();
// This Handler is associated with our UI thread as it is initialized here and will handle communication with Worker thread.
        uiHandler = new Handler();
        worker = new Worker();
        worker.start();
        worker.doWork(new Runnable() {
            @Override
            public void run() {
                // processing 'line' here and posting back
                 // result to your textView.
               // UI thread's handler is used to communicate our results back.
                 uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText(result);
                            }
                        }); 
            }
    });

最后是Worker線程類:

/* A worker thread for offloading heavy work so as to keep UI thread responsive
* and smooth */

public class Worker extends HandlerThread {
    public final String NAME = "Worker";
    private Handler handler;

    public Worker() {
        super("Worker", HandlerThread.NORM_PRIORITY);
    }

    public void prepareHandler() {
        handler = new Handler(getLooper());
    }

    // do some work in background
    public void doWork(Runnable someWork) {
        prepareHandler();
        handler.post(someWork);
    }
}

我希望這可以幫助別人。 編碼愉快!

暫無
暫無

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

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