【问题标题】:Can you create "global" methods to use in several fragments at once?您可以创建“全局”方法以同时在多个片段中使用吗?
【发布时间】:2019-09-10 22:51:02
【问题描述】:

对不起,我确定有这个问题,但我看不出我该怎么做,我想创建一个 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();
}

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

【问题讨论】:

  • Stack Overflow 主站点上的所有问题和答案都必须使用英文。请翻译您的问题或尝试Stack Overflow en español。
  • 问题是英文的,只是代码注释和变量是西班牙文
  • Activity 可以是该 Activity 中的所有 Fragment 都将调用的方法的位置。

标签: android android-fragments methods global-variables


【解决方案1】:

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

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

java代码:

context.getString(R.string.DEFAULT)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多