如何从数组适配器获取值?

时间:2015-07-16 17:04:31

标签: java android

我有一些来自语音识别的文字。

if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
    match_text_dialog = new Dialog(MainActivity.this);
        match_text_dialog.setContentView(R.layout.activity_dialog_matches_frag);
    textlist = (ListView)match_text_dialog.findViewById(R.id.list);
    matches_text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, matches_text);
    textlist.setAdapter(adapter);
    textlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
            Speech.setText("You have said " +matches_text.get(position));
            match_text_dialog.hide();
        }
    });
    match_text_dialog.show();
}
super.onActivityResult(requestCode, resultCode, data);

然后我开发了一个代码来获取一些特定的文本。

String sentence = stop.getText().toString();
String[] splitWords = sentence.split(" ");
String[] stopWords = {"I", "want", "to", "go", "to", "the"};

for (int i = 0; i < stopWords.length; i++) {
    for (int j = 0; j < splitWords.length; j++) {
        if (stopWords[i].equalsIgnoreCase(splitWords[j])) {
            splitWords[j] = null;
        }
    }
}

for (int i = 0; i < splitWords.length; i++) {
    if(splitWords[i]!= null) {
        Toast.makeText(getApplicationContext(),splitWords[i] , Toast.LENGTH_LONG).show();
    }
}

我想要做的是获取ArrayAdapter值并将其传递给我的第二个代码。 我如何获取值并将其传递给String语句?

1 个答案:

答案 0 :(得分:0)

首先,让我直截了当...你什么时候想把字符串传递给String sentence?单击列表项时?

如果是这样,创建一个方法,将代码的第二位放在方法中,并将字符串作为参数...简单的确实..

public void goToMethod(String sentence) {
         //put the String sentence code here
         String sentence;
         this.sentence = sentence;

         String[] splitWords = sentence.split(" ");
         String[] stopWords = {"I", "want", "to", "go", "to", "the"};

         for (int i = 0; i < stopWords.length; i++) {
              for (int j = 0; j < splitWords.length; j++) {
                   if (stopWords[i].equalsIgnoreCase(splitWords[j])) {
                           splitWords[j] = null;
                   }
               }
         }

         for (int i = 0; i < splitWords.length; i++) {
             if(splitWords[i]!= null) {
                   Toast.makeText(getApplicationContext(),splitWords[i], Toast.LENGTH_LONG).show();
             }
         }
}

然后,从Activity中的onItemClick()方法调用您创建的此方法。

public void onItemClick(....) {
        Speech.setText("You have said " +matches_text.get(position));
        match_text_dialog.hide();
        goToMethod(matches_text.get(position));
}

您无法直接从AdapterView取出文字。它不会那样工作。这就是为什么你得到int位置参数,来操纵输入的数组..:“)