简体   繁体   English

Android从其他线程获取EditText内容

[英]Android getting EditText content from other Thread

In my problem, I have my MainActivity , with a TextView and EditText , and a method, which should send out messages to the TextView and receive the content of an EditText . 在我的问题中,我有MainActivity ,一个TextViewEditText以及一个方法,该方法应该向TextView发送消息并接收EditText的内容。 The problem is receiving text from the EditText, and making this method wait for the user input 问题是从EditText接收文本,并使此方法等待用户输入

I'll try to post my cropped code so you will gain some knowledge about what I am trying to achieve. 我将尝试发布裁剪后的代码,以便您将获得一些有关我要实现的知识。

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();
        }
    }
}

I have marked the required input/output methods with <<<<< >>>>> . 我已经用<<<<< >>>>>标记了所需的输入/输出方法。

Have mercy with my java skills, since this is my first large project in java and the whole structure is converted from python. 怜悯我的Java技能,因为这是我的第一个大型Java项目,整个结构都是从python转换而来的。

Again, all help is greatly appreciated. 再次感谢所有帮助。

The problem is simple that normally threads don't notify back to the ui or the main thread. 问题很简单,通常线程不会通知用户界面或主线程。 And to solve this issue android has AsyncTask. 为了解决这个问题,android有AsyncTask。 You can use AsyncTask as: 您可以将AsyncTask用作:

  1. Initiate your TextView and EditText in onPreExecute() method. 在onPreExecute()方法中初始化TextView和EditText。
  2. Send or call your methods to send what so ever text you want in doInBackground() method. 发送或调用您的方法以在doInBackground()方法中发送所需的文本。
  3. You will then get the result in onPostExecute() method. 然后,您将在onPostExecute()方法中获得结果。 Here you can setText() to your EditText. 在这里,您可以将setText()设置为您的EditText。

Note: AsyncTask is a thread that contact backs to the main ui thread, for which it has this onPostExecute() method. 注意:AsyncTask是一个联系到主ui线程的线程,为此它具有此onPostExecute()方法。

For better understanding of AsyncTask check this link: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 为了更好地了解AsyncTask,请检查以下链接: http ://www.androidhive.info/2012/01/android-json-parsing-tutorial/

Okay, so as far I understand from your question, You want to get some text from UI (which is handled by UIThread), process it on a worker thread and post the resultant text in a TextView again in UI (UIThread). 好的,据我所知,您想从UI中获取一些文本(由UIThread处理),在工作线程上对其进行处理,然后将生成的文本再次发布到UI(UIThread)中的TextView中。

This is how I would do it in MainActivity: 这就是我在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);
                            }
                        }); 
            }
    });

and finally, the Worker thread class : 最后是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);
    }
}

I hope this helps someone. 我希望这可以帮助别人。 Happy coding! 编码愉快!

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

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