Toolbar的简单使用
程序员文章站
2024-03-24 12:50:34
...
//styles
改为NoActionBar
//布局
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width=“match_parent”
android:layout_height=“130dp”
android:layout_weight=“1”
android:background="#1b5fff"
>
</android.support.v7.widget.Toolbar>
//res/menu/menu.xml
Activity
package com.example.choujiang;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
private Toolbar toolbar;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("标题");
//app的图标
//toolbar.setLogo(R.drawable.ic_launcher_background);
//toolbar.setNavigationIcon(R.mipmap.ic_launcher);
//设置副标题
toolbar.setSubtitle("德伦狗");
//设定菜单个按钮的动作
toolbar.setOnMenuItemClickListener(this);
//上级按钮
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.action_settings){
Toast.makeText(MainActivity.this, "打开", Toast.LENGTH_SHORT).show();
}
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_mian,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
case R.id.action_settings:
Toast.makeText(MainActivity.this, "打开", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return false;
}
//每次显示前都会调用
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
//menu.clear();
//menu.add();
return super.onPrepareOptionsMenu(menu);
}
//关闭的时候调用
@Override
public void onOptionsMenuClosed(Menu menu) {
Toast.makeText(this, "关闭", Toast.LENGTH_SHORT).show();
super.onOptionsMenuClosed(menu);
}
//打开的时候调用
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
Toast.makeText(this, "打开", Toast.LENGTH_SHORT).show();
return super.onMenuOpened(featureId, menu);
}
}
上一篇: toolbar使用