如何使用 HashMap 为单词及其各自的含义创建类似字典的 android 应用程序?

How do I create a dictionary-like android app using HashMap for words and their respective meanings?

我正在尝试创建一个像字典一样工作的应用程序(使用 HashMap),用户在 textEdit 中输入一个词(行话),如果该词匹配任何当用户点击 enter.

时,HashMap 中的单词将在 textView 中显示我预定义的单词含义

这是我的 java code:

import java.util.HashMap;
import java.util.Map;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity 
{   
// read input
EditText searchField = (EditText)findViewById(R.id.searchField);
String word = searchField.getText(); 
// Error: I'm being prompted to convert this to Editable, should I?

//display output;
String meaning = lookup(word);
TextView displayField = (TextView)findViewById(R.id.displayField);
displayField.setText(meaning); 
// I'm getting a multiple syntax error marker at this line


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

    Map<String, String> dictionary = new HashMap<String, String>();
    dictionary.put("Doe", "a deer, a female deer");
    dictionary.put("Ray", "a drop of golden sun");
}
    public String lookup (String input){
        return dictionary.get(input); 
// Error at this line: dictionary cannot be reslolved, multiple eclipse suggestions none of which seem to work
    }

这是我的 xml 文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.safelintels.hgsdreamdictionary.MainActivity" >

<EditText
    android:id="@+id/searchField"
    android:textSize="25sp"
    android:layout_width="330dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:ems="10"
    android:hint="Enter word"
    android:textColor="#000000"
    android:lines="1"
    android:imeOptions="actionSearch"
    android:maxLines="1"
    tools:ignore="RtlHardcoded,TextFields,HardcodedText,UnusedAttribute" />

<TextView
    android:id="@+id/displayField"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/searchField"
    android:layout_alignLeft="@+id/searchField"
    android:layout_alignParentStart="true"
    android:layout_alignRight="@+id/searchField"
    android:layout_below="@+id/searchField"
    android:textColor="#000000"
    android:textSize="20sp"
    tools:ignore="HardcodedText,RtlHardcoded,RtlCompat" />

</RelativeLayout>

本网站和其他网站上对类似问题给出的大多数答案都建议创建 database。但是,我不想要这种方法,因为我不会存储那么多单词,只会存储一些单词和含义。

提前感谢您的宝贵建议。

我推荐使用 Map class 而不是嵌套的 if 语句,因为这样会更快。 Map 是索引的,这意味着您的程序将立即转到 Map 中的匹配条目,而不是在找到匹配之前评估每个 if 条件。如果在地图中找不到输入,它将 return null.

Map<String, String> dictionary = new HashMap<String, String>;
dictionary.put("lunch", "the meal you eat in the afternoon");
dictionary.put("dinner", "the meal you eat after lunch");

    public String lookup (String input) {
        return dictionary.get(input);
    }

如果您坚决不使用 if 语句,我建议您改用 switch。它的作用与拥有一长串 if / else if 语句相同,但更易于阅读。请注意:在 Java 7 之前,您不能在 switch 块中使用字符串,这意味着您必须单独使用 if 语句。

public String otherLookup(String input) {
    switch (input) {
        case "lunch":
            return "the meal you eat in the middle of the day";
        case "dinner":
            return "the meal you eat after lunch";
        case "other":
            return "all your other strings here; very tedious";
    }
    return "";
}

在所有情况下,您都会像这样阅读文本输入:

//read in user input
EditText inputField = (EditText) findViewById(R.id.yourId);
String inputText = inputField.getText();

//display output; you can put this code inside of an onClick type of method if you want it to be triggered by a button click
String outputText = lookup(inputText);
TextView outputDisplay = (TextView) findViewById(R.id.yourOtherId);
outputDisplay.setText(outputText);

编辑后的答案: 在 UI 中添加一个按钮。当用户点击这个按钮时,它会触发你的字典查找。现在,您的应用正尝试 运行 在应用启动时立即查找单词,然后用户才能将任何内容放入 EditText 字段中。所以把它放在你的 layout.xml 中,你有 TextView 和 EditText:

<Button android:id="@+id/lookupButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Look Up Word"
            android:onClick="lookup"/>

然后将此代码作为您的主要 Activity。抱歉,我想我误解了您使用它的上下文。我相信这应该会更好:

public class MainActivity extends ActionBarActivity {

    //assign the UI widgets to variables so you can access them later.
    EditText searchField = (EditText) findViewById(R.id.searchField);
    TextView displayField = (TextView) findViewById(R.id.displayField);
    Map<String, String> dictionary = new HashMap<String, String>();

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


        dictionary.put("Doe", "a deer, a female deer");
        dictionary.put("Ray", "a drop of golden sun");
    }

    //this lookup() method is what gets called when the user clicks the Button.
    //this View parameter refers to the View that the user clicks to trigger the method call; in your case, this is the Button.
    public void lookup(View view) {
        //use .toString() to cast the input to a String that won't be updated whenever the user
        // changes what is in the EditText field; sorry, I overlooked that before
        String word = searchField.getText().toString();

        //this line looks up the value in your dictionary and sticks it in the TextView for the user to see
        displayField.setText(dictionary.get(word));
    }
}

最好将 UI 变量声明为 private,然后在 onCreate method 中初始化它们以避免 NullPointerException error:

public class MainActivity extends ActionBarActivity {   

Map<String, String> map = new HashMap<String, String>();
private EditText searchField;
private TextView displayField;
String word;

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

        searchField = (EditText) findViewById(R.id.searchField);
        displayField = (TextView) findViewById(R.id.displayField);
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            String word = searchField.getText().toString();
            displayField.setText(map.get(word);

        dictionary.put("Doe", "a deer, a female deer");
        dictionary.put("Ray", "a drop of golden sun");
    }