我一直在阅读一些有关Android内存泄漏的文章,并观看了Google I/O 关于此主题的有趣视频.
尽管如此,我还是不完全理解这个概念,特别是当在Activity中使用内部类是安全或危险的时候.
这就是我的理解:
如果内部类的实例比其外部类(活动)存活的时间更长,则会发生内存泄漏.- > 在哪种情况下会发生这种情况?
在这个例子中,我认为没有泄漏的风险,因为匿名类扩展没有办法OnClickListener比活动更长寿,对吧?
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_generic);
Button okButton = (Button) dialog.findViewById(R.id.dialog_button_ok);
TextView titleTv = (TextView) dialog.findViewById(R.id.dialog_generic_title);
// *** Handle button click
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
titleTv.setText("dialog title");
dialog.show();
Run Code Online (Sandbox Code Playgroud)
现在,这个例子是危险的,为什么?
// We are still inside an Activity
_handlerToDelayDroidMove = new Handler();
_handlerToDelayDroidMove.postDelayed(_droidPlayRunnable, 10000);
private Runnable _droidPlayRunnable = new Runnable() {
public void run() {
_someFieldOfTheActivity.performLongCalculation(); …Run Code Online (Sandbox Code Playgroud) 我正在查看Java代码,LinkedList并注意到它使用了静态嵌套类Entry.
public class LinkedList<E> ... {
...
private static class Entry<E> { ... }
}
Run Code Online (Sandbox Code Playgroud)
使用静态嵌套类而不是普通内部类的原因是什么?
我能想到的唯一原因是,Entry无法访问实例变量,因此从OOP的角度来看,它具有更好的封装.
但我认为可能有其他原因,也许是表现.可能是什么?
注意.我希望我的条款正确,我会称之为静态内部类,但我认为这是错误的:http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
我已经定制了我的ListAdapter,我在一行中显示了3个不同的图像(项目).它完美地工作(根据它的功能).但是,无法顺利滚动ListView.
我在ImageViews上使用setBackgroundImage,我使用HashMap来缓存resourceId; 所以我不必使用
resId=getContext().getResources().getIdentifier(resName, "drawable",appContext.getPackageName());
一次又一次.
我想我错过了一些东西,因为ListView不能很好地滚动.此外,如果我在平板电脑上尝试它,我的代码会连续自动填充超过3个项目,平板电脑的列表视图几乎不可滚动.
我在这做错了什么?
更新:
我在我的Flags(国家标志)中以编程方式创建ListView的Activity的onCreate方法:
root=(ViewGroup)this.findViewById(R.id.root);
listView=new ListView(this);
listView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
/*
ArrayList<Country> dataList=new ArrayList<Country>(){{
add(new Country("jp"));
add(new Country("de"));
add(new Country("it"));
}};*/
CountryListAdapter countryListAdapter=new CountryListAdapter(this);
countryListAdapter.setDataSource(allCountries);
listView.setAdapter(regionListAdapter);
listView.setBackgroundColor(0xFF000000);
listView.setDividerHeight(0);
root.addView(listView);
Run Code Online (Sandbox Code Playgroud)
resId=getContext().getResources().getIdentifier(resName, "drawable",appContext.getPackageName());