action bar

在res目录下新建menu文件下,再新建main.xml输入以下代码


    

MainActivity需要重写 onCreateOptionsMenu(Menu menu)onOptionsItemSelected(MenuItem item) 方法

public class MainActivity extends AppCompatActivity {

    private EditText mSearchBoxEditText;

    private TextView mUrlDisplayTextView;

    private TextView mSearchResultsTextView;

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

        mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box);

        mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display);
        mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json);
    }
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemID = item.getItemId();
        if(itemID==R.id.action_search){
            Context context = MainActivity.this;
            Toast.makeText(context,"search clicked",Toast.LENGTH_LONG).show();
            return true;
        }else{
            return super.onOptionsItemSelected(item);
        }

    }
}

你可能感兴趣的:(action bar)