搜索视图小部件和图标未显示在操作栏中

时间:2014-08-10 06:12:34

标签: android

我是Android的初学者。尝试在操作栏中添加搜索小部件。 这是我的菜单文件代码(" main_acitivity.xml"):

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_search"
          android:title="@string/action_search"
          android:showAsAction="always"
          android:actionViewClass="android.support.v7.widget.SearchView" />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:showAsAction="never" />
</menu>

我的MainActivity类代码是:

package com.example.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;


public class MainActivity extends ActionBarActivity {
    public final static String EXTRA_MESSAGE = "com.example.fragment.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater= getMenuInflater();
        inflater.inflate(R.menu.main_activity,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_search:
                return true;
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void sendMessage(View view){
        Intent intent= new Intent(this,DisplayMessageActivity.class);
        EditText editText= (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

我试过&#34; android.widget.SearchView&#34;同样,但它甚至没有显示图标。你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:5)

你错过了这些:

 xmlns:yourappname="http://schemas.android.com/apk/res-auto"

yourappname:showAsAction="always"
yourappname:actionViewClass="android.support.v7.widget.SearchView"/>