在MainActivity和没有onCreate的类之间共享变量可以通过以下几种方式实现:
public class MainActivity extends AppCompatActivity {
public static int sharedVariable;
// ...
}
public class NoCreateClass {
public void someMethod() {
MainActivity.sharedVariable = 10;
// ...
}
}
public class MainActivity extends AppCompatActivity {
// ...
private void goToNoCreateClass() {
Intent intent = new Intent(this, NoCreateClass.class);
intent.putExtra("sharedVariable", 10);
startActivity(intent);
}
}
public class NoCreateClass extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int sharedVariable = getIntent().getIntExtra("sharedVariable", 0);
// ...
}
}
public interface SharedVariableCallback {
void onSharedVariableChanged(int sharedVariable);
}
public class MainActivity extends AppCompatActivity implements SharedVariableCallback {
private int sharedVariable;
// ...
private void goToNoCreateClass() {
NoCreateClass noCreateClass = new NoCreateClass();
noCreateClass.setSharedVariableCallback(this);
}
@Override
public void onSharedVariableChanged(int sharedVariable) {
this.sharedVariable = sharedVariable;
// ...
}
}
public class NoCreateClass {
private SharedVariableCallback sharedVariableCallback;
public void setSharedVariableCallback(SharedVariableCallback callback) {
this.sharedVariableCallback = callback;
}
public void someMethod() {
int sharedVariable = 10;
if (sharedVariableCallback != null) {
sharedVariableCallback.onSharedVariableChanged(sharedVariable);
}
// ...
}
}
以上是在MainActivity和没有onCreate的类之间共享变量的几种常见方法。具体选择哪种方式取决于你的需求和项目架构。腾讯云相关产品和产品介绍链接地址方面,本回答不涉及云计算品牌商,你可以根据需求自行查找腾讯云的相关产品和文档。
领取专属 10元无门槛券
手把手带您无忧上云