練習用程式,主版面沒有元件
Menu (XML file)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/submenu" android:title="子選單開始">
<menu>
<item android:id="@+id/submenu1" android:title="選項1"/>
<item android:id="@+id/submenu2" android:title="選項2"/>
</menu>
</item>
<item android:id="@+id/fin" android:title="離開"></item>
</menu>
Source Code
package com.menutest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
//android sdk tool r20之後,只需要由eclipse中將此方法給匯入並改寫即可
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
//從使用此方法中自帶的item中的.getItemId()直接與Menu與SubMenu之編號來判斷
switch(item.getItemId()){
case R.id.submenu1:
Toast.makeText(MainActivity.this, "子選項1", 3000).show();
break;
case R.id.submenu2:
Toast.makeText(MainActivity.this, "子選項2", 3000).show();
break;
case R.id.fin:
finish();
}
return super.onOptionsItemSelected(item);
}
}
沒有留言:
張貼留言