java静态变量还是通过Bundle传递变量?
假设我有一个ListView,并在列表上设置了一个Listener。传递变量的最佳方式是什么
静态变量:
public static String example;
// onItemClick
Intent intent = new Intent(Main.this, Details.class);
Main.example = "example";
startActivity(intent);
// in onCreate of Details
String example = Main.example;
捆绑:
// onItemClick
Intent intent = new Intent(Main.this, Details.class);
intent.putExtra("example","example");
startActivity(intent);
// in onCreate of Details
Bundle extras = getIntent().getExtras();
String example = extra.getString("example");
// or
Intent intent = getIntent();
String example = intent.getStringExtra("example");
# 1 楼答案
使用此代码。。这可能对你有帮助
# 2 楼答案
如果希望变量在整个应用程序中使用,那么使用静态变量或单例类(即将getter setter模型类设置为单例)
静态变量不容易被垃圾收集,所以除非需要,否则不要使用它
如果要将数据从一个活动发送到另一个活动(而不是通过应用程序),请使用bundle强>
# 3 楼答案
除了使用
static
变量外,最好使用Intent
。当您不想在应用程序中长期使用静态变量时,请使用静态变量。因为它占用内存,不容易收集垃圾。 所以,最好使用“Intent”将变量传递给其他活动