java android 2.2.5
先在res目录下新建menu目录,然后点右键新建个menu resource文件名字叫main,写入如下代码:<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/add_item"
android:title="@string/m_titlename"
/>
<item
android:id="@+id/remove_item"
android:title="@string/m_remove"
/>
</menu>
android:title这里书上是直接给赋值一个字符串,我是给一个变量,这样更正规一些。所有变量的声明都在values目录下的strings.xml文件里,所以我们要打开这个文件修改为如下内容:<resources>
<string name="app_name">Test</string>
<string name="m_titlename">Add</string>
<string name="m_remove">Remove</string>
</resources>
然后打开主文件MainActivity.java写入如下代码,注意:以后所有文件的包名都要改成你自己原来的,不要用我代码里的:
package com.example.xinwei.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "you clicked button1", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_item:
Toast.makeText(this, "You clicked add", Toast.LENGTH_SHORT).show();
break;
case R.id.remove_item:
Toast.makeText(this, "You clicked remove", Toast.LENGTH_SHORT).show();
break;
default:
}
return super.onOptionsItemSelected(item);
}
void myClick(View v){
Toast.makeText(this, "这是我的方法", Toast.LENGTH_SHORT).show();
}
}
效果图:
页:
[1]