您可以创建"global"方法以同时在多个片段中使用吗?



很抱歉这个问题,我确定有,但我看不出我该怎么做,我想创建一个保存全局方法的 java 文件,从而在我需要的片段中使用它们,如果你能帮我怎么做,如果你能给我一个例子,那会很有帮助

我没有尝试任何东西,因为我没有什么可谈论的,我想尝试我拥有的所有片段,如果有连接,如果没有,我关闭应用程序,我拥有的代码工作正常,但在我看来,我通过放置相同的方法来抓住错误的所有片段

private void verificarconexion() {
//para saber si hay internet
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// Estas conectado a un Wi-Fi
Log.d("MIAPP", " Nombre red Wi-Fi: " + networkInfo.getExtraInfo());
}
} else {
//Intent salida=new Intent( Intent.ACTION_MAIN); //Llamando a la activity principal
Toast.makeText(getContext(), "no tienes internet", Toast.LENGTH_LONG).show();
mostrarsalir();
}

}
private void mostrarsalir() {
final CharSequence[] opciones={"Aceptar","Cancelar"};
final AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
builder.setCancelable(false);
builder.setTitle("No se detectan redes de internet");
builder.setItems(opciones, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (opciones[i].equals("Aceptar")){
getActivity().finish();
System.exit(0);
int p = android.os.Process.myPid();
android.os.Process.killProcess(p);
}else{
getActivity().finish();
System.exit(0);
int p = android.os.Process.myPid();
android.os.Process.killProcess(p);
}
}
});
builder.show();
}

我想将方法写在一个可以从任何片段调用它的地方,因为如果我想更改我显示的消息的字母,我不必查看该方法所在的所有片段

您可以轻松地使用字符串资源在所有项目中定义一次字符串: 字符串.xml:

<string name="DEFAULT">Default</string>

Java代码:

context.getString(R.string.DEFAULT)

如果你想定义一次函数,只需定义一个带有静态函数的类,如下所示:

public class Helper{
public static void function(){
//code
}
}
//call function
Helper.function();

最新更新