其他分享
首页 > 其他分享> > 在Android中如何在按钮单击中调用两个功能?

在Android中如何在按钮单击中调用两个功能?

作者:互联网

我在活动中创建了一个按钮和两个函数/方法,一个方法强制退出应用程序,另一种方法删除缓存目录.

现在,我想在单击按钮时调用这两种方法,我已经取消了退出,但是我不知道下一步该怎么做.

我的活动代码:

package com.beta.accs;

import android.app.Activity;
import android.content.ComponentName;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.File;
import android.content.Context;
import android.widget.Button;

public class MainActivity extends Activity {

    public WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.WebViewSNCF);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.loadUrl("https://www.oui.sncf/services/acces-plus"); //Ton url de page Principal;
        webView.setWebViewClient(new WebViewClient()); //pour rester dans l'aplication meme en cliquant partout a l'ecran.
        webView.getSettings().setBuiltInZoomControls(true);
    }

    public void clickExit(View view) {
        moveTaskToBack(true);

        Process.killProcess(R.id.WebViewSNCF);
        System.exit(1);
    }

    public void clicReturn(View view) {
        if (webView.canGoBack()) {
            webView.goBack();
        }
    }

    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {}
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        } else if(dir!= null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;
        }
    }
}

请告诉我如何单击一个按钮即可调用这两种方法.

解决方法:

像这样:

Button your_btn = findViewById(R.id.button); // reference to your button ID in your layout xml file
your_btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         deleteCache(); // delete cache
         clickExit(); // exit
     }
});

标签:android-button,android
来源: https://codeday.me/bug/20191024/1922768.html