Android应用搜索操作栏未获得结果

时间:2017-09-26 05:09:21

标签: android android-actionbar searchview

我正在为我的网站制作应用程序。我正在开展一项活动,即MainActivity。我不是一个只是学习的Android开发人员。问题是,我已经搜索了我的mainactivity的操作栏。搜索视图即将到来,我可以在其中输入单词。但是当我按下提交时,没有任何反应。我需要结果在同一个活动中。主要活动。搜索查询将加载网页搜索。我的菜单是R.menu.main,搜索的菜单项是R.id.action_search  请告诉我我做错了什么。这是我的Androidmanifest.xml代码

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
<uses-permission android:name="android.permission.CAMERA"/>
android:hardwareAccelerated="true"
<application android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="Bengalflora.in"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="Bengalflora.in"
        android:theme="@style/AppTheme.NoActionBar"
        android:launchMode="singleTop"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <meta-data android:name="android.app.default_searchable"
            android:value="com.mywebsite.mywebsite.MainActivity"
            android:resource="@xml/searchable" />
        <meta-data
            android:name="android.app.searchable"
            android:value="com.mywebsite.mywebsite.MainActivity"
            android:resource="@xml/searchable" />
    </activity>
    <activity android:name=".Splash">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name=".Aboutus"
        android:label="About us"
        android:parentActivityName=".MainActivity" >

        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />
    </activity>
</application>

这是我的主要活动

 public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener{
    private static final int REQUEST_INTERNET = 200;
    private static final int TIME_INTERVAL = 1000; // # milliseconds, desired time passed between two back presses.
    private long mBackPressed;
    private ProgressBar mProgressBar;

    private static final String target_url="https://bengalflora.in";
    private static final String target_url_prefix="bengalflora.in";
    private Context mContext;
    private WebView mWebviewPop;
    private FrameLayout mContainer;
    WebView mwebView;

    String mypage_error = "file:///android_asset/error/index.html";

    private static final String TAG = MainActivity.class.getSimpleName();
    private String mCM;
    private ValueCallback<Uri> mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR=1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        if(Build.VERSION.SDK_INT >= 21){
            Uri[] results = null;
            //Check if response is positive
            if(resultCode== Activity.RESULT_OK){
                if(requestCode == FCR){
                    if(null == mUMA){
                        return;
                    }
                    if(intent == null){
                        //Capture Photo if no image available
                        if(mCM != null){
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    }else{
                        String dataString = intent.getDataString();
                        if(dataString != null){
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        }else{
            if(requestCode == FCR){
                if(null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            }
        }
    }
    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})

    @Override
    protected void onCreate(Bundle savedInstanceState)   {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int Permission_All = 1;
        String[] Permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MEDIA_CONTENT_CONTROL, Manifest.permission.CAMERA, };
        if(!hasPermissions(this, Permissions)){
            ActivityCompat.requestPermissions(this, Permissions, Permission_All);
        }

        //
        mProgressBar = (ProgressBar) findViewById(R.id.pb);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        mwebView = (WebView) findViewById(R.id.myWebView);
        assert mwebView != null;
        WebSettings webSettings = mwebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);


        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        CookieManager.getInstance().setAcceptThirdPartyCookies(mwebView, true);

        mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mwebView.getSettings().setAppCacheEnabled(true);
        mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);
        webSettings.setEnableSmoothTransition(true);
        mwebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        mwebView.getSettings().setAllowFileAccess(true);
        if(Build.VERSION.SDK_INT >= 21){
            webSettings.setMixedContentMode(0);
            mwebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT >= 19){
            mwebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19){
            mwebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mwebView.setWebViewClient(new Callback());
        mwebView.setWebViewClient(new CustomWebViewClient());

        mwebView.loadUrl("https://bengalflora.in/gallery/index.php");




        mwebView.setWebChromeClient(new WebChromeClient(){
            public void onProgressChanged(WebView view, int newProgress){
                // Update the progress bar with page loading progress
                mProgressBar.setProgress(newProgress);
                if(newProgress >= 90){
                    // Hide the progressbar
                    mProgressBar.setVisibility(View.GONE);
                }
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
                mwebView.loadUrl(mypage_error);
            }



            //For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg){
                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                MainActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FCR);
            }
            // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
            public void openFileChooser(ValueCallback uploadMsg, String acceptType){
                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                MainActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FCR);
            }
            //For Android 4.1+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
            }
            //For Android 5.0+

            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams) {
                if(mUMA != null){
                    mUMA.onReceiveValue(null);
                }
                mUMA = filePathCallback;
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
                    File photoFile = null;
                    try{
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCM);
                    }catch(IOException ex){
                        Log.e(TAG, "Image file creation failed", ex);
                    }
                    if(photoFile != null){
                        mCM = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    }else{
                        takePictureIntent = null;
                    }
                }
                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("image/*");
                Intent[] intentArray;
                if(takePictureIntent != null){
                    intentArray = new Intent[]{takePictureIntent};
                }else{
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, FCR);
                return true;
            }
        });
    }

    //new code start
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        // Inflate the menu; this adds items to the action bar if it is present.


        //
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        Intent searchIntent = getIntent();
        String query = searchIntent.getStringExtra(SearchManager.QUERY);
        if(Intent.ACTION_SEARCH.equals(searchIntent.getAction())) {
            mwebView.loadUrl("http://google.co.in/?q="+query);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.action_upload:
                mwebView.loadUrl("https://xyz/uploadpage.php");
                return true;
            case R.id.action_reload:
                mwebView.reload();
                return true;

            case R.id.action_about:
                startActivity(new Intent(this, Aboutus.class));
                return true;



            case R.id.action_exit:
                finish();


        }


        return super.onOptionsItemSelected(item);
    }

    ///////////////multiple permission code
    public static boolean hasPermissions(Context context, String... permissions){

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && context!=null && permissions!=null){
            for(String permission: permissions){
                if(ActivityCompat.checkSelfPermission(context, permission)!=PackageManager.PERMISSION_GRANTED){
                    return  false;
                }
            }
        }
        return true;
    }
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_local) {
            mwebView.loadUrl("http://xyz/index.php?/category/1&mobile=true");
        } else if (id == R.id.nav_spices) {
            mwebView.loadUrl("http://xyz?/category/84&mobile=true");
        } else if (id == R.id.nav_vherbarium) {
            mwebView.loadUrl("http://xyz/index.php?/category/36&mobile=true");
        } else if (id == R.id.nav_usersupload) {
            mwebView.loadUrl("http://xyz/index.php?/category/user&mobile=true");
        } else if (id == R.id.nav_recent) {
            mwebView.loadUrl("http://xyz/index.php?/recent_pics&mobile=true");

        } else if (id == R.id.nav_login) {
            mwebView.loadUrl("http://xyz/identification.php?mobile=true");
        } else if (id == R.id.nav_register) {
            mwebView.loadUrl("http://xyz/register.php?mobile=true");

        } else if (id == R.id.nav_contact) {
            mwebView.loadUrl("http://xyz/contact/&mobile=true");
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public class CustomWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon){
            // Do something on page loading started
            // Visible the progressbar
            mProgressBar.setVisibility(View.VISIBLE);
        }


        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            mwebView.loadUrl(mypage_error);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            if(url.contains("something")) return true;
            return false; //Default is to not override unless our condition is met.
        }
        public void onPageFinished(WebView webView, String url) {


            String webUrl = webView.getUrl();
            System.out.println(webUrl);
            if(url.startsWith("https://xyz/plugins/oAuth/auth.php?provider=Facebook&openid_identifier=&init_auth=1#_=_"))
            {
                String redirectUrl = "https://xyz/gallery/facloginapp.php";
                webView.loadUrl(redirectUrl);
                return;
            }
            super.onPageFinished(webView, url);
            mProgressBar.setVisibility(View.GONE);
        }
    }
    public class Callback extends WebViewClient {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            mwebView.loadUrl(mypage_error);
        }
    }
    // Create an image file
    private File createImageFile() throws IOException{
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_"+timeStamp+"_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg",storageDir);
    }
    @Override
    public boolean onKeyDown(int keyCode,  KeyEvent event){
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode){
                case KeyEvent.KEYCODE_BACK:

                    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                    if (drawer.isDrawerOpen(GravityCompat.START)) {
                        drawer.closeDrawer(GravityCompat.START);
                    }

                    else{

                        if(mwebView.canGoBack()){
                            mwebView.goBack();
                        }
                        else if   (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
                        {
                            super.onBackPressed();

                        }
                        else { Toast.makeText(getBaseContext(), "Press back button once quickly to exit", Toast.LENGTH_SHORT).show(); }

                        mBackPressed = System.currentTimeMillis();





                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }}

1 个答案:

答案 0 :(得分:0)

有很多实现,但常见的是在应用栏中包含搜索视图。

创建带有搜索视图的菜单资源文件。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/search"
    android:title="Search"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    />
</menu>

然后在活动或片段设置oncreateoptionsmenu并膨胀上面的菜单项

 @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.main_menu, menu);
    MenuItem item = menu.findItem(R.id.search);
    SearchView searchview = (SearchView) item.getActionView();
    searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Log.d("hello", query);
            msp_editor.putString("query", query);
            msp_editor.commit();
            fetchData(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
}

通过创建res / xml / searchable.xml文件并在清单文件中声明元数据来创建可搜索的配置,您可以从官方documentation获得有关设置的更多说明,但在上面的代码中我可以使用我给出了搜索视图的实现。当用户输入搜索查询时,我会通过查询侦听器并将查询传递给我的改装api调用。