• Android开发 ---xml构建选项菜单、上下文菜单(长按显示菜单)、发通知、发送下载通知


    1、activity_main.xml

      描述:

        定义了一个TextView和三个按钮

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >
    
        <TextView
            android:id="@+id/mainText"
            android:textSize="35dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="XML构建选项菜单"
            android:onClick="test_1"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="发送通知"
            android:onClick="test_2"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="下载通知"
            android:onClick="test_3"
            />
    </LinearLayout>

    2、MainActivity.java

       描述:

     

    package com.nf.android_menu_notifaction;
    
    import android.app.Activity;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.graphics.BitmapFactory;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.os.SystemClock;
    import android.view.ContextMenu;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.SubMenu;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class MainActivity extends Activity {
        private TextView mainText;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mainText = (TextView)findViewById(R.id.mainText);
            //为mainText绑定一个上下文菜单,注册上下文菜单
            registerForContextMenu(mainText);
        }
        //-----------------------通过代码创建选项菜单------------------------------------------
        //1、创建选项菜单
        @Override
        public boolean onCreateOptionsMenu(Menu menu){
            Intent intent = new Intent(this,NewFileActivity.class);
            intent.putExtra("message","Hello");
            menu.add(0,0,0,"新建").setIntent(intent);
            menu.add(0,1,1,"打开");
            menu.add(1,2,0,"保存");
            //添加子菜单
            SubMenu sbMenu = menu.addSubMenu("颜色");
            sbMenu.add(11,4,0,"红色");
            sbMenu.add(11,5,1,"黄色");
            sbMenu.add(11,6,2,"绿色");
            menu.add(1,3,1,"退出");
            return super.onCreateOptionsMenu(menu);
        }
        //2、选项菜单打开之前执行的操作
        @Override
        public boolean onPrepareOptionsMenu(Menu menu){
            //菜单打开前进行一些设置
         //将第一个菜单选择项设置为隐藏,或禁止点击 menu.getItem(0).setEnabled(false); return super.onPrepareOptionsMenu(menu); } //3、选项菜单中菜单项被选中 @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case 1: Toast.makeText(this,"你选中了打开",Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(this,"你选中了保存",Toast.LENGTH_SHORT).show(); break; case 3: Toast.makeText(this,"你选中了退出",Toast.LENGTH_SHORT).show(); break; case 4:
              //改变文本颜色 mainText.setTextColor(Color.RED);
    break; case 5: mainText.setTextColor(Color.YELLOW); break; case 6: mainText.setTextColor(Color.GREEN); break; } return super.onOptionsItemSelected(item); } public void test_1(View view){ Intent intent = new Intent(this,NewFileActivity.class); startActivity(intent); } //--------------------------通过代码创建上下文菜单------------------------------------
      //当你长按文本内容时,就会弹出下列菜单 @Override public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo){ SubMenu sm = menu.addSubMenu(3,7,0,"字体设置");
         //给字体设置菜单设置菜单项 sm.add(
    3,9,0,"25sp"); sm.add(3,10,1,"35sp"); sm.add(3,11,2,"45sp"); menu.add(3,8,1,"删除"); super.onCreateContextMenu(menu,v,menuInfo); } private LinearLayout main;
      //当你点击字体设置菜单中的某一项时 @Override
    public boolean onContextItemSelected(MenuItem item){ switch (item.getItemId()){ case 8:
              //点击的id为8时是删除 main
    = (LinearLayout)findViewById(R.id.activity_main); main.removeView(mainText); break; case 9:
              //点击的id为9时是将字体设置为25sp mainText.setTextSize(
    25); break; case 10:
              //同上 mainText.setTextSize(
    35); break; case 11:
              //同上 mainText.setTextSize(
    45); break; } return super.onContextItemSelected(item); } //------------------------------发通知------------------------------ //定义一个NotifactionManager对象 private NotificationManager manager;
      //创建一个日历对象
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); public void test_2(View view){ //获取NotifactionManager对象 manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); //构建一个Notifaction的Builder对象 Notification.Builder builder = new Notification.Builder(this); //设置通知相关信息 builder.setTicker("新的通知");//设置信息提示 builder.setSmallIcon(R.mipmap.ic_launcher);//设置通知提示图标
         //设置通知人的头像 builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.user2));
         //设置通知信息的标题 builder.setContentTitle(
    "部门通知");
         //设置通知信息的文本内容 builder.setContentText(
    "今天中午一点在报告厅一开部门会议,"+sdf.format(new Date())); builder.setAutoCancel(true);//查看后自动取消 builder.setWhen(SystemClock.currentThreadTimeMillis());//什么时候发出的通知 builder.setDefaults(Notification.DEFAULT_ALL);//消息提示模式 //设置震动规律 builder.setVibrate(new long[]{1000,2000,1000,3000}); //设置声音 //builder.setSound(); //设置灯 builder.setLights(Color.GREEN,1000,1000);
    //设置点击通知后执行的动作 点击通知后,跳转页面显示内容 Intent intent = new Intent(this,NewFileActivity.class); intent.putExtra("message","今天中午一点在报告厅一开部门会议,请大家准时参加,通知发布时间:"+sdf.format(new Date()));
         //获取时间
    int requestId = (int) new Date().getTime();
         //pendingIntent是一种特殊的Intent。主要的区别在于Intent的执行立刻的,而pendingIntent的执行不是立刻的
         //
    第一个参数连接上下文的context
            // 第二个参数是对PendingIntent的描述,请求值不同Intent就不同
            // 第三个参数是一个Intent对象,包含跳转目标
            // 第四个参数有4种状态
            PendingIntent pendingIntent = PendingIntent.getActivity(this,requestId,intent,PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
    
            //发出通知
         //
    发出通知,参数是(通知栏的id,设置内容的对象)     
            manager.notify(requestId,builder.build());
        }
        //发送一个下载通知
        Notification.Builder builder;
        public void test_3(View view){
            manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            builder = new Notification.Builder(this);
         
            builder.setTicker("文件开始下载");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setContentTitle("文件下载");
            builder.setContentText("文件正在下载中......");
            builder.setWhen(SystemClock.currentThreadTimeMillis());
            builder.setDefaults(Notification.DEFAULT_LIGHTS);
            builder.setProgress(100,0,false);
    
            //模拟正在执行下载
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=1;i<=100;i++){
                 builder.setProgress(
    100,i,false); if (i ==100){ builder.setContentText("文件下载完毕!"); } manager.notify(1,builder.build()); SystemClock.sleep(100);//模拟下载 } manager.cancel(1); } }).start(); }

    3、activity_new_file.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/acticity_new_file"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >
    </LinearLayout>

    4、NewFileActivity.java

    package com.nf.android_menu_notifaction;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.ContextMenu;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.Toast;
    
    public class NewFileActivity extends Activity {
        private LinearLayout main;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_new_file);
    Intent intent
    = getIntent(); String msg = intent.getStringExtra("message"); if (msg!=null&&msg.length()>0){ Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } main = (LinearLayout)findViewById(R.id.acticity_new_file);
         //为activity_new_file绑定一个上下文菜单,注册上下文菜单 registerForContextMenu(main); }
    //--------------------------使用XML构建选项菜单--------------------------------------- @Override public boolean onCreateOptionsMenu(Menu menu){ //投影加载XML文件 getMenuInflater().inflate(R.menu.menu_option,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.m1: Toast.makeText(this,"吃饭",Toast.LENGTH_SHORT).show(); break; } return super.onOptionsItemSelected(item); } //------------------------使用XML构建上下文菜单---------------------------------------- @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo){ getMenuInflater().inflate(R.menu.menu_option,menu); super.onCreateContextMenu(menu,v,menuInfo); } }

    5、menu/menu_option.xml

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/m1"
            android:title="吃饭"
            />
        <item
            android:id="@+id/m2"
            android:title="睡觉">
            <menu>
                <item android:id="@+id/m2_1"
                    android:title="宿舍"
                    />
                <item android:id="@+id/m2_2"
                    android:title="教室"
                    />
                <item android:id="@+id/m2_3"
                    android:title="走廊"
                    />
            </menu>
        </item>
        <item
            android:id="@+id/m3"
            android:title="打豆豆"
            />
        <item
            android:id="@+id/m4"
            android:title="退出"
            />
    </menu>

    6、AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.nf.android_menu_notifaction">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name=".NewFileActivity"></activity>
        </application>
        <uses-permission android:name="android.permission.VIBRATE"/>
    </manifest>

    7、头像资源

    如果您发现博客内容有什么错误,请您下方留言
  • 相关阅读:
    统计内存使用情况
    自动化测试---PO设计模式
    初识xshell
    pip插件遇到问题(fetch URL https)
    为什么大家都热衷于挖矿呢?
    80个python练习以及python一些值得收藏的教程或博客
    面试问到一个,让你写一下朋友圈点赞功能的测试用例!记录一下
    ajax异步请求302
    Java学习
    MVC 带扩展名的路由无法访问
  • 原文地址:https://www.cnblogs.com/zn615/p/8242494.html
Copyright © 2020-2023  润新知