在android应用程序中使用全局变量有困难
嘿,我在声明、更改和使用全局变量时遇到问题。我尝试了整个“创建一个扩展应用程序并将变量放在那里的类”的方法,但我不确定如何实现它。这是我的类,其中包含变量在android应用程序中使用全局变量有困难,android,class,variables,global,Android,Class,Variables,Global,嘿,我在声明、更改和使用全局变量时遇到问题。我尝试了整个“创建一个扩展应用程序并将变量放在那里的类”的方法,但我不确定如何实现它。这是我的类,其中包含变量 public class MyApp extends Application { public int listPos; } 然后我尝试在这里访问和更改int listPos public class Browse extends ListActivity{ MyApp app = ((MyApp)getApplicat
public class MyApp extends Application {
public int listPos;
}
然后我尝试在这里访问和更改int listPos
public class Browse extends ListActivity{
MyApp app = ((MyApp)getApplicationContext());
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] coffeeTypes = getResources().getStringArray(R.array.coffeeTypes);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listview, coffeeTypes));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
app.listPos = position;
startActivity(new Intent(Browse.this, CoffeeTypes.class));
}
});
}
有人知道我做错了什么吗?我不确定这是否是安卓操作系统的可见性问题,您是否能够创建一个公共函数来充当变量的getter
int getListPos(){ return this.listpos; }
我知道你可以在上下文之间传递变量,你可能必须这样做
也许让您移动的临时解决方法也可以是创建一个可访问变量的静态类?创建这样一个类
class globalClass
{
static int lastPos;
}
可以使用设置值
globalClass.lastPos = value;
而get函数是
int myVal = globalClass.lastPos;
你可以使用soorya的答案进行一些修改。我个人仍然会使用myApp类,但会将listPos更改为静态并以这种方式访问它。这样做可以让您使用应用程序类
onCreate
方法在需要时初始化值(尽管在本例中不需要)或其他Android方法
public class MyApp extends Application {
public static int listPos;
}
//~~ Elsewhere:
MyApp.listPos = 5; //etc
但这并不是处理这类问题的最佳方法
您应该通过Intent
传递列表位置信息(或单击项目的id或处理数据的方式)
与其使用全局变量来跟踪此信息,不如将其保留为本地变量,以实现以下目的:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//app.listPos = position;
Intent intent = new Intent(Browse.this, CoffeeTypes.class);
intent.putExtra("position", position);
startActivity(intent);
//startActivity(new Intent(Browse.this, CoffeeTypes.class));
}
这将从传入的意图中读取“位置”数据,以便您可以使用它。如果未添加任何内容,则上面的-1是默认值
最后一个警告:您可能需要小心地来回发送列表位置,这取决于应用程序的设置方式。如果添加了新项目/删除了项目,列表位置可能不再引用您认为它所引用的项目。如果这些咖啡类型/无论你使用什么,都有一个单独的ID,它可能更适合避免上述情况,考虑使用它。 < P>我通过使变量私有,应用应用程序变量类,然后创建公共GET()和Stand()方法来改变变量。你可以试试,但从技术上看,你似乎做得对
它可能出错的一个原因是,您在onCreate中实现了这些内容,而不是onStart命令。如果您在测试此功能时使用了错误的假设/活动周期知识,则可能会出错非常棒的帮助!虽然现在我的应用程序因为一些未知的原因崩溃了,但是你的意图是正确的。更简单。@seeshiu suin我忘了添加startActivity的修改版,现在编辑。但可能与您的新问题无关。
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//app.listPos = position;
Intent intent = new Intent(Browse.this, CoffeeTypes.class);
intent.putExtra("position", position);
startActivity(intent);
//startActivity(new Intent(Browse.this, CoffeeTypes.class));
}
//in onCreate...
int incomingPosition = getIntent().getIntExtra("position",-1));
if(incomingPosition != -1) { //do stuff }