gpt4 book ai didi

java - 在不同类android中访问变量的最佳方法

转载 作者:行者123 更新时间:2023-12-01 20:53:45 25 4
gpt4 key购买 nike

我是 Android 新手。很多时候我需要从不同的类访问变量而不创建对象,就像从 MainAvtivity 访问变量一样。我找到两种将变量传递给不同类的方法,一种方法是在主 Activity 中创建对象并在构造函数中传递变量,第二种方法是将变量设置为公共(public)静态并从第二个类访问它。哪一种是最好的方式和方法?

更新

主要 Activity :

 Public static EditText editText;
onCreate(){
// other code
editText = (EditText) findViewById(R.id.editText);
}

其他类

// accessing editText
editText.setText("Some text");

实现此目的的其他方式

主要 Activity :

 onCreate(){
// other code
EditText editText = (EditText) findViewById(R.id.editText);
new OtherClass(editText);
}

其他类

 EditText editText;
OtherClass(EditText et){
editText = et;
}

// other code
editText.setText("Some text");

最佳答案

这完全取决于实际的类本身。

Activity -> Activity = Intent(实际上是 Bundle 的包装器)

Activity -> fragment = bundle

(ParcelableSerializing 类对这些最有帮助。)

Activity/Fragment -> 别的东西 = 可能是一个构造函数,但又是一个。取决于

<小时/>

需要全局变量吗? SharedPreferencesSQLiteDatabase

public static 不应该用于 final Stringfinal int 常量 之外的其他用途。

您可以创建一个 Application 类,是的,但是单例模式不应该严重依赖它。

<小时/>

如果您确实想要比这更复杂的东西,请查看接口(interface)和 an EventBus library

模型- View -呈现器是一个很好的设计,可以遵循,用于设计 UI 和数据之间的正确接口(interface)。

编辑

public class OtherClass { // Presenter

private Model mData; // Model

public interface OnTextChangeListener {
void onTextChanged(String text); // Callback to View
}

public Model getData() {
return mData;
}

OnTextChangeListener listener; // Callback to View

// other code
mData.setName("some other string"); // Update the model
if (listener != null) {
listener.onTextChanged(mData.getName()); // Present the data
}
}

public class ExampleActivity extends Activity  // Presenter
implements OtherClass.OnTextChangeListener {

private EditText editText

@Override
void onTextChanged(String text) {
editText.setText(text); // Present the data
}

@Override
public void onCreate(Bundle b) {
// Other code...

// Bind the Presenter to the View
OtherClass x = new OtherClass();
x.listener = this; // 'this' being the *interface*, not the Activity
}

}

关于java - 在不同类android中访问变量的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42750599/

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