【问题标题】:Android getting EditText content from other ThreadAndroid 从其他线程获取 EditText 内容
【发布时间】:2016-03-09 09:56:56
【问题描述】:

在我的问题中,我有我的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();
        }
    }
}

我已经用&lt;&lt;&lt;&lt;&lt; &gt;&gt;&gt;&gt;&gt;标记了所需的输入/输出方法。

请原谅我的java技能,因为这是我在java中的第一个大型项目,整个结构都是从python转换而来的。

再次感谢所有帮助。

【问题讨论】:

  • 请发布您的代码,以便我们为您提供帮助
  • 出现问题的代码?
  • @PragnaniKinnera 给你

标签: java android multithreading android-edittext android-handler


【解决方案1】:

问题很简单,通常线程不会通知回 ui 或主线程。为了解决这个问题,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/

【讨论】:

  • 非常感谢,这看起来不错。我会检查一下,一旦我尝试过,就会回复你。
  • 好吧,所以我检查了这个,发现这看起来不像是正确的方法,因为我想要打印/接收输入的方法有一段时间( ),这基本上是整个程序。这是一个文本冒险,应该通过“回合”基本上每回合读取一个输入,执行所有必需的动作,然后再次读取输入,这种方法应该在所述回合之后等待用户输入。
【解决方案2】:

好的,据我所知,您想从 UI 中获取一些文本(由 UIThread 处理),在工作线程上处理它,然后在 UI 中再次将结果文本发布到 TextView 中( UIThread)。

这就是我在 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);
    }
}

我希望这对某人有所帮助。编码愉快!

【讨论】:

  • 感谢您的努力,但这对我没有帮助,因为 EditText 内容是从“工作”线程中的不同位置多次提取的。
  • 在这种情况下,您可以将 uiHandler 传递给您的工作线程。 doWork(uiHandler, someRunnable) 上的一些东西可以用来更新 UI。能做到吗?
猜你喜欢
  • 2015-10-17
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 2016-03-25
  • 2015-09-04
相关资源
最近更新 更多