【问题标题】:Pass variable from an activity to a java class将变量从活动传递到 Java 类
【发布时间】:2017-03-19 21:34:05
【问题描述】:

我想将一个 int 从 FirstActivity 传递给 TheAdapter(不是一个活动)。当在 FirstActivity 中单击一个按钮时,它会打开 SecondActivity,它会创建一个 TheAdapter 的实例,并在列表视图中显示其内容。

第一个活动:

viewBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            number = 5; //this is an integer
            Intent in = new Intent(FirstActivity.this, SecondActivity.class);
            startActivity(in);
        }
    });

第二个活动:

TheAdapter adapter = new TheAdapter(this, 0);
myListView.setAdapter(adapter);

我想从 FirstActivity 获取整数,以便在 TheAdapter 中使用它。

【问题讨论】:

    标签: java android android-activity


    【解决方案1】:

    第一个活动:

    viewBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            number = 5; //this is an integer
            Intent in = new Intent(FirstActivity.this, SecondActivity.class);
            in.putExtra("name of your value (eg. adapter_int)", number);
            startActivity(in);
        }
    });
    

    第二个活动:

    Intent intent = getIntent();
    int yourInt = intent.getExtra("name of your value (eg. adapter_int)", 0); // 0 is a default value
    

    【讨论】:

    • 那行得通,我通过它的构造函数将它传递给另一个类,谢谢
    【解决方案2】:
    Intent in = new Intent(FirstActivity.this, SecondActivity.class);
    in.putExtra(Key , value);
    startActivity(in);
    

    //在SecondActivity中

    Bundle bundle = this.getIntent().getExtras();
    
    //for example int param
    int param = 0;
    if(bundle == null){
         Log.e(TAG, "bundle is null.");
    }else{
         param = bundle.getInt(key);
    }
    

    如果你想要传递对象(可序列化对象)它应该很有用

    public class Serializer {
    
    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }
    
    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }
    

    }

    【讨论】:

    • 你可以在 bundle.getInt(key , defaultValue) 中添加参数默认值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2015-12-04
    • 2018-09-09
    • 2013-02-25
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    相关资源
    最近更新 更多