安卓菜单

安卓菜单有点重要,在这里记录一下

main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/customStyle"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="191dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

java 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.aclihui.menu;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
RelativeLayout customStyle;

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

final static int MENU_00=Menu.FIRST;
final static int MENU_01=Menu.FIRST+1;
final static int MENU_02=Menu.FIRST+2;

@Override
public boolean onCreateOptionsMenu(Menu menu) {

menu.add(0,MENU_00,1,"红色");
menu.add(0,MENU_01,2,"灰色");
menu.add(0,MENU_02,3,"黑色");
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

customStyle=(RelativeLayout)findViewById(R.id.customStyle);
switch (item.getItemId())
{
case 1:
customStyle.setBackgroundColor(Color.RED);
break;
case 2:
customStyle.setBackgroundColor(Color.GRAY);
break;
case 3:
customStyle.setBackgroundColor(Color.BLACK);
break;
}
return true;
}
}