gpt4 book ai didi

java - 如何将多个变量从 java Activity 传递到 java 类?

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:26 28 4
gpt4 key购买 nike

我可以将字符串从 Java Activity 传递到一类库,但我无法确定如何发送多个,我需要传递三个,这里是代码:

OFActivity.java

package cc.openframeworks.androidMultiOFActivitiesExample;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import cc.openframeworks.OFAndroid;
import cc.openframeworks.androidMultiOFActivitiesExample.R.id;


public class OFActivityA extends cc.openframeworks.OFActivity{

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

}


OFAndroid of = new OFAndroid("jala");




}

Android.java

public class OFAndroid {


private static String text ;

public OFAndroid(String text) {
this.text = text ;
}


public void useText() {
Log.e("TAG" , this.text);
}

最佳答案

尝试使用 a) Array、b) List 或 c) Bundle

数组

OFActivity.java

public class OFActivityA extends cc.openframeworks.OFActivity{

// onCreate()

OFAndroid of = new OFAndroid(new String[]{"jala", "foo", "bar"});
}

Android.java

public class OFAndroid {
private String[] textArray ;

public OFAndroid(String[] textArray) {
this.textArray= textArray;
}


public void useText() {
for (String text : textArray) {
Log.e("TAG" , text);
}
}

列表

OFActivity.java

public class OFActivityA extends cc.openframeworks.OFActivity{

// onCreate()

List<String> listOfString = new ArrayList<>();
listOfString.add("jala");
listOfString.add("foo");
listOfString.add("bar");
OFAndroid of = new OFAndroid(listOfString);
}

Android.java

public class OFAndroid {
private List<String> listOfString;

public OFAndroid(List<String> listOfString) {
this.listOfString = listOfString;
}


public void useText() {
for (String text : listOfString) {
Log.e("TAG" , text);
}
}

bundle

OFActivity.java

public class OFActivityA extends cc.openframeworks.OFActivity{

// onCreate()

Bundle bundle = new Bundle();
bundle.putString("keyOfString1", "jala");
bundle.putString("keyOfString2", "foo");
bundle.putString("keyOfString3", "bar");
OFAndroid of = new OFAndroid(bundle);
}

Android.java

public class OFAndroid {
private Bundle bundle ;

public OFAndroid(Bundle bundle) {
this.bundle = bundle;
}

public void useText() {
Log.e("TAG", bundle.getString("keyOfString1")); // jala
Log.e("TAG", bundle.getString("keyOfString2")); // foo
Log.e("TAG", bundle.getString("keyOfString3")); // bar
}

顺便说一句,有什么理由在OFAndroid.java中使用静态变量吗?如果不仔细控制静态对象的生命周期和引用,很容易造成内存泄漏问题。

关于java - 如何将多个变量从 java Activity 传递到 java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318791/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com