我定义了自己的自定义ArrayAdapter
,名为WordAdapter
,如下所示:
public class WordAdapter extends ArrayAdapter<Word> {
Context context;
public WordAdapter(Context context, ArrayList<Word> words) {
super(context, 0, words);
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
Word currentWord = getItem(position);
TextView miwok = (TextView) listItemView.findViewById(R.id.miwok_text_view);
miwok.setText(currentWord.getMiwokTranslation());
TextView english = (TextView) listItemView.findViewById(R.id.english_text_view);
english.setText(currentWord.getEnglishTranslation());
return listItemView;
}
}
我在课堂上需要它,它的用法如下:
public class NumbersActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
ArrayList<Word> words = new ArrayList<>();
words.add(new Word("lutti","one"));
words.add(new Word("otiiko","two"));
words.add(new Word("toldokosu","three"));
words.add(new Word("oyyisa","four"));
words.add(new Word("massoka","five"));
words.add(new Word("temmoka","six"));
words.add(new Word("kenekaku","seven"));
words.add(new Word("kawinta","eight"));
words.add(new Word("wo'e","nine"));
words.add(new Word("na'aacha","ten"));
WordAdapter itemsAdapter = new WordAdapter(this, words);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(itemsAdapter);
}
}
但它在行WordAdapter itemsAdapter = new WordAdapter(this, words);
中出错,说
WordAdapter(android.content.Context ArrayList)无法应用于com.example.android.miwok.NumbersActivity ArrayList
依赖关系:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.android.support:support-v4:23.3.0'
}
答案 0 :(得分:3)
我可以说你的代码没有问题。 AppCompatActivity
本身就是Context
。因此,无论如何,传递"this"
都应该有效。
我可以看到,存在依赖性冲突。如果您已添加appcompat依赖项,则不必添加support V4
依赖项,因为supportv4
包已附带appcompat
依赖项。
我建议删除support v4
依赖项并再次与gradle同步。它应该没问题,
即使它不起作用,只需再做一步即。
点击File -> Invalidate/Cache Restart -> Click on Invalidate cahe and Restart.
现在我非常确定,那个问题不会存在。
答案 1 :(得分:1)
当纯粹引用this
时,它可能会受到其内部方法的影响。我自己也看到过这个问题,特别是在onCreate上。
这意味着this
不会受到上下文的影响,有时可能会对课程产生影响,有时它会参考可运行的,根据我的经验,它会有所不同。你可以试试YourClass.this
,其中YourClass是Activity
扩展类(任何活动,甚至是AppCompatActivity)。在您的情况下,YourClass
为NumbersActivity
。
另外,您可以使用getApplicationContext()
或getBaseContext()