有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在另一个活动中获取变量?

如何在另一个活动中访问变量值。在我的示例中,我有一个字符串变量项,其值为spinner selected value。如何在另一个活动中访问此变量而不使用Intent

  public class LoginScreen extends Activity {

      Spinner sp;
String item;


      Spinner sp = (Spinner) findViewById(R.id.lgnspinner);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.network_array,
            安卓.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(安卓.R.layout.simple_spinner_dropdown_item);

    sp.setAdapter(adapter);

    sp.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            item = (String) parent.getItemAtPosition(position);



        public class AgAppMenu extends Activity {

共 (4) 个答案

  1. # 2 楼答案

    您可以将它们声明为静态变量,然后在其他类中可以像Activity1一样访问它们。stringName

    public static String stringName; 
    
    stringName = .. // value from Spinner
    

    然后,在所有其他活动中,您可以作为YourMainActivty.stringName访问它们

  2. # 3 楼答案

    试试这个

    步骤1:在应用程序类中创建静态绑定对象。(ApplicationClass.java)

         public static Bundle mMyAppsBundle = new Bundle():
    

    步骤2:

    从任意位置设置捆绑包中的键值对。 像这样:

       ApplicationClass.mMyAppsBundle.putString("key","value");
    

    步骤3:

    现在,您可以通过以下方式从任何位置获取这些值:

       String str = ApplicationClass.mMyAppsBundle.getString("key");
    

    在使用安全视图的捆绑对象之前应用空检查

  3. # 4 楼答案

    如果不想使用全局变量,可以在活动中创建一个方法来返回字符串

    public static String getMyString(){
        return item;
    }
    

    然后在当前活动中,您可以调用:

    String myValue = LoginScreen.getMyString();