我正在创建一个简单的应用程序,您可以使用一个按钮将单词添加到用户词典,然后通过单击另一个按钮来显示用户词典单词。我在将单词添加到词典时遇到一些问题。特别是第一个参数,上下文,在addWord(this)中。以下是主要活动的副本和错误的副本。任何帮助或指导表示赞赏。
错误:
错误:不兼容的类型:无法转换为上下文
MainActivity
public abstract class MainActivity extends Activity implements View.OnClickListener {
EditText edtTxt;
TextView txtVw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtTxt = findViewById(R.id.editText1);
txtVw = findViewById(R.id.Display);
Button button1 = (Button) findViewById(R.id.insertWord);
button1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
UserDictionary.Words.addWord(this, edtTxt.getText().toString(), 10, UserDictionary.Words.LOCALE_TYPE_ALL);
Toast.makeText(getApplicationContext(), "Word Successfully Added to USER DICTIONARY", 10).show();
}
});
Button button2 = (Button) findViewById(R.id.displayWord);
button2.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri dic = UserDictionary.Words.CONTENT_URI;
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(dic, null, null, null, null);
txtVw.setText("");
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex(UserDictionary.Words.WORD));
txtVw.append("\nword: " + word);
}
}
});
}
}
答案 0 :(得分:0)
尝试一下。
使用onCreate()
方法。
String text = edtTxt.getText().toString();
button1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
UserDictionary.Words.addWord(MainActivity.this, text, 10, UserDictionary.Words.LOCALE_TYPE_ALL);
Toast.makeText(getApplicationContext(), "Word Successfully Added to USER DICTIONARY", 10).show();
}
});