ホームページ Java &#&チュートリアル Android の基本 フローティング ボタンとステータス バーの通知

Android の基本 フローティング ボタンとステータス バーの通知

Jul 13, 2017 pm 05:21 PM

1. Web ページ

Uri uri = Uri.parse("http://www.php.cn");  
Intent it = new Intent(Intent.ACTION_VIEW, uri);  
startActivity(it);
ログイン後にコピー

を開きます。2. Web ページのコンテンツを取得します

 public String posturl(String url){
     InputStream is = null;
     String result = "";
     try{
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost = new HttpPost(url);
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();
         is = entity.getContent();
     }catch(Exception e){
         return "Fail to establish http connection!"+e.toString();
     }
     try{
         BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
         StringBuilder sb = new StringBuilder();
         String line = null;
         while ((line = reader.readLine()) != null) {
             sb.append(line + "\n");
         }
         is.close();
         result=sb.toString();
     }catch(Exception e){
         return "Fail to convert net stream!";
     }
     return result;
 }
ログイン後にコピー

3. ハイパーリンク

textView1.setText(Html.fromHtml("<a href=&#39;http://www.php.cn&#39;>php中文网 </a>"));
textView1.setMovementMethod(LinkMovementMethod.getInstance());
ログイン後にコピー

を追加します。ネットワークへのアクセスを許可します

<uses-permission android:name="android.permission.INTERNET" />
ログイン後にコピー

5.シンプルなメッセージボックス

new AlertDialog.Builder(this)
   .setTitle("标题") 
   .setMessage("简单消息框")
    .setPositiveButton("确定", null) 
    .show();
ログイン後にコピー

6. [OK] と [キャンセル] ダイアログ

new AlertDialog.Builder(this)  
    .setTitle("确认") 
    .setMessage("确定吗?") 
    .setPositiveButton("是", null) 
    .setNegativeButton("否", null) 
    .show();
ログイン後にコピー

7.入力ボックス付きダイアログボックス

new AlertDialog.Builder(this) 
    .setTitle("请输入") 
    .setIcon(android.R.drawable.ic_dialog_info) 
    .setView(new EditText(this)) 
    .setPositiveButton("确定", null) 
    .setNegativeButton("取消", null) 
    .show();
ログイン後にコピー

8.ラジオボタンのあるダイアログボックス

 new AlertDialog.Builder(this) 
    .setTitle("请选择") 
    .setIcon(android.R.drawable.ic_dialog_info)                 
    .setSingleChoiceItems(new String[] {"选项1","选项2","选项3","选项4"}, 0,  
      new DialogInterface.OnClickListener() { 
                                   
         public void onClick(DialogInterface dialog, int which) { 
            dialog.dismiss(); 
         } 
      } 
    ) 
    .setNegativeButton("取消", null) 
    .show();
ログイン後にコピー


9.複数の選択ボックスがあるダイアログ ボックス

new AlertDialog.Builder(this) 
  .setTitle("多选框") 
  .setMultiChoiceItems(new String[] {"选项1","选项2","选项3","选项4"}, null, null) 
  .setPositiveButton("确定", null)                 
  .setNegativeButton("取消", null) 
  .show();
ログイン後にコピー

10.リストボックス付きダイアログボックス

new AlertDialog.Builder(this) 
     .setTitle("列表框") 
  .setItems(new String[] {"列表项1","列表项2","列表项3"}, null) 
  .setNegativeButton("确定", null) 
  .show();
ログイン後にコピー

11.フォトフレーム

ImageView img = new ImageView(this); 
  img.setImageResource(R.drawable.ic_launcher); 
  new AlertDialog.Builder(this) 
  .setTitle("图片框") 
  .setView(img) 
  .setPositiveButton("确定", null) 
  .show();
ログイン後にコピー


12.短いプロンプト ボックスが表示されます

public void alert(String txt){
   Toast.makeText(MainActivity.this,txt, 1).show();
  }
ログイン後にコピー


13. URL トランスコーディング

 public String urlencode(String str) throws UnsupportedEncodingException{
   return java.net.URLEncoder.encode(str, "utf-8");  
  }
ログイン後にコピー

14. URL デコード

 public String urldecode(String str) throws UnsupportedEncodingException{
   return java.net.URLDecoder.decode(str, "utf-8");  
  }
ログイン後にコピー


15. Web ページのソース コードを取得します

//得到二进制数据   
    public String getDatas(String path) throws Exception{  
        // 类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。   
        URL url = new URL(path);  
         // 每个 HttpURLConnection 实例都可用于生成单个请求,   
         //但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络   
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
         //设置 URL 请求的方法   
         conn.setRequestMethod("GET");  
         //设置一个指定的超时值(以毫秒为单位),   
        //该值将在打开到此 URLConnection 引用的资源的通信链接时使用。   
        conn.setConnectTimeout(5 * 1000);  
        // conn.getInputStream()返回从此打开的连接读取的输入流   
        InputStream inStream = conn.getInputStream();// 通过输入流获取html数据   
         byte[] data = readInputStream(inStream);// 得到html的二进制数据   
       String html = new String(data);  
        return html;  
           
     }  
    //读取输入流中的数据,返回字节数组byte[]   
     public byte[] readInputStream(InputStream inStream) throws Exception{  
        //此类实现了一个输出流,其中的数据被写入一个 byte 数组   
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
         // 字节数组   
         byte[] buffer = new byte[1024];  
        int len = 0;  
        //从输入流中读取一定数量的字节,并将其存储在缓冲区数组buffer 中   
         while ((len = inStream.read(buffer)) != -1) {  
            // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流  
             outStream.write(buffer, 0, len);  
         }  
         inStream.close();  
        //toByteArray()创建一个新分配的 byte 数组。   
         return outStream.toByteArray();  
     }
ログイン後にコピー

16.ウェブ写真を表示しています

public Bitmap returnBitMap(String url) {   
         URL myFileUrl = null;   
         Bitmap bitmap = null;   
         try {   
          myFileUrl = new URL(url);   
         } catch (MalformedURLException e) {   
          e.printStackTrace();   
         }   
         try {   
          HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();   
          conn.setDoInput(true);   
          conn.connect();   
          InputStream is = conn.getInputStream();   
          bitmap = BitmapFactory.decodeStream(is);   
          is.close();   
         } catch (IOException e) {   
          e.printStackTrace();   
         }   
         return bitmap;   
      }  
 ImageView imView = (ImageView) findViewById(R.id.pic1);   
 imView.setImageBitmap(returnBitMap("https://img.php.cn/upload/course/000/001/120/595af5fa9f34f845.png"));
ログイン後にコピー


17.ボタンクリックイベント

//登录检测
   Button button=(Button)findViewById(R.id.button1);
         button.setOnClickListener(new OnClickListener(){   
    public void onClick(View v){
        }
    });
  //登录检测
ログイン後にコピー

18.ダイアログリスニングイベント

new AlertDialog.Builder(this) 
  .setTitle("亲,是否退出?") 
  .setPositiveButton("确定", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    alert("你点了确定");
   }}) 
        .setNegativeButton("取消",new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    alert("你已经取消了");
   }})
  .show(); 
  public void alert(String txt){
   Toast.makeText(this,txt, 1).show();
  }
ログイン後にコピー

19. Android 終了プログラム

private void showTips() {
 
    AlertDialog alertDialog = new AlertDialog.Builder(this)
           .setTitle("退出程序").setMessage("是否退出程序")
               .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  
                   public void onClick(DialogInterface dialog, int which) {
                       finish();
                   }
  
               }).setNegativeButton("取消",
 
               new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {
                         return;
                     }
               }).create(); // 创建对话框
         alertDialog.show(); // 显示对话框
      }
   public boolean onKeyDown(int keyCode, KeyEvent event) {
  
       if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            showTips();
            return false;
         }
  
        return super.onKeyDown(keyCode, event);
     }
ログイン後にコピー

20. Android WebView コンポーネント

 WebView mWebView = new WebView(this);
  
  mWebView.setWebViewClient(new webViewClient());//调用自身打开
 
  mWebView.getSettings().setJavaScriptEnabled(true); 
  mWebView.loadUrl("http://www.php.cn/member/1.html"); 
 setContentView(mWebView);  
class webViewClient extends WebViewClient{ 
           //重写shouldOverrideUrlLoading方法,使点击链接后不使用其他的浏览器打开。 
        @Override 
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            view.loadUrl(url); 
            //如果不需要其他对点击链接事件的处理返回true,否则返回false 
            return true; 
        } 
            
       }
ログイン後にコピー


21.パラメータなしでアクティビティジャンプ

Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);
ログイン後にコピー

22.次のアクティビティにデータを渡します (Bundle と Intent.putExtras を使用)

Intent it = new Intent(Activity.Main.this, Activity2.class);
Bundle bundle=new Bundle();
bundle.putString("name", "This is from MainActivity!");
it.putExtras(bundle);       // it.putExtra(“test”, "shuju”);
startActivity(it);            // startActivityForResult(it,REQUEST_CODE);
ログイン後にコピー

データの取得には、

Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");
ログイン後にコピー

23 を使用できます。結果を前のアクティビティに返します (startActivityForResult(it, REQUEST_CODE) によって開始されたアクティビティの場合は setResult を使用します)

Intent intent=getIntent();
Bundle bundle2=new Bundle();
bundle2.putString("name", "This is from ShowMsg!");
intent.putExtras(bundle2);
setResult(RESULT_OK, intent);
ログイン後にコピー

24。前のアクティビティの結果処理関数(onActivityResult)をコールバックします

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_CODE){
            if(resultCode==RESULT_CANCELED)
                  setTitle("cancle");
            else if (resultCode==RESULT_OK) {
                 String temp=null;
                 Bundle bundle=data.getExtras();
                 if(bundle!=null)   temp=bundle.getString("name");
                 setTitle(temp);
            }
        }
    }
ログイン後にコピー

25。 Android タイマー

 Timer timer = new Timer(); 
   timer.schedule(task,10000,2000);   
      
TimerTask task = new TimerTask(){   
           public void run() {  
            Message message = new Message();  
            message.what = 1;  
            handler.sendMessage(message);   
            }   
           };  
Handler handler = new Handler(){ 
          public void handleMessage(Message msg) {    
           switch (msg.what) {    
           case 1:     
            alert("hear me?");    
            break;    
            }   
           super.handleMessage(msg);   
           }   
          };
ログイン後にコピー

26. Android 用の BGM を挿入します

MediaPlayer mediaPlayer = new MediaPlayer();
          Uri uri = Uri
               .parse("http://www.php.cn/asset/1.mp3");  
  try {
   mediaPlayer.setDataSource(Sound.this, uri);
  } catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalStateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 
try {
   mediaPlayer.prepare();
  } catch (IllegalStateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 mediaPlayer.start();
ログイン後にコピー

27。 int と string の変換


1 文字列 String を整数に変換するには、

1) または
i = Integer の 2 つの方法があります。 parseInt([String],[int radix]);

2). int i = Integer.valueOf(my_str).intValue();

注: 文字列を Double、Float、Long に変換する方法は似ています。

2 整数を文字列 String に変換するにはどうすればよいですか?

A. 3 つの方法があります:

1.) String s = String.valueOf(i);

2.) String s = Integer.toString(i) ) ;

3.) String s = "" + i;

注: Double、Float、Long を文字列に変換する方法は似ています。画面の幅と高さを取得します

DisplayMetrics dm = getResources().getDisplayMetrics(); 
int screenWidth = dm.widthPixels; 
int screenHeight = dm.heightPixels - 50;
ログイン後にコピー

29。画像ドラッグ

private int screenWidth; 
private int screenHeight; 
private ImageView img1; 
private ImageView img2;
img1 = (ImageView) findViewById(R.id.imageView1); 
img2 = (ImageView) findViewById(R.id.imageView2);
DisplayMetrics dm = getResources().getDisplayMetrics(); 
screenWidth = dm.widthPixels; 
screenHeight = dm.heightPixels - 50;
img1.setOnTouchListener(movingEventListener); 
img2.setOnTouchListener(movingEventListener);
private OnTouchListener movingEventListener = new OnTouchListener() { 
int lastX, lastY; 
@Override 
public boolean onTouch(View v, MotionEvent event) { 
    switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
        lastX = (int) event.getRawX(); 
        lastY = (int) event.getRawY(); 
        break; 
    case MotionEvent.ACTION_MOVE: 
        int dx = (int) event.getRawX() - lastX; 
        int dy = (int) event.getRawY() - lastY;
        int left = v.getLeft() + dx; 
        int top = v.getTop() + dy; 
        int right = v.getRight() + dx; 
        int bottom = v.getBottom() + dy; 
        // 设置不能出界 
        if (left < 0) { 
            left = 0; 
            right = left + v.getWidth(); 
        }
        if (right > screenWidth) { 
            right = screenWidth; 
            left = right - v.getWidth(); 
        }
        if (top < 0) { 
            top = 0; 
            bottom = top + v.getHeight(); 
        }
        if (bottom > screenHeight) { 
            bottom = screenHeight; 
            top = bottom - v.getHeight(); 
        }
        v.layout(left, top, right, bottom);
        lastX = (int) event.getRawX(); 
        lastY = (int) event.getRawY();
        break; 
    case MotionEvent.ACTION_UP: 
        break; 
    } 
    return true; 
} 
};
ログイン後にコピー

30。ステータス バー通知メッセージ プロンプト コード

 private void addNotificaction(int id) {
   NotificationManager manager = (NotificationManager) this
   .getSystemService(Context.NOTIFICATION_SERVICE);
   // 创建一个Notification
   Notification notification = new Notification();
   // 设置显示在手机最上边的状态栏的图标
   notification.icon = R.drawable.ic_launcher;
   // 当当前的notification被放到状态栏上的时候,提示内容
   notification.tickerText = "注意了,我被扔到状态栏了";
   
 
   // 添加声音提示
   notification.defaults=Notification.DEFAULT_SOUND;
   // audioStreamType的值必须AudioManager中的值,代表着响铃的模式
   notification.audioStreamType= android.media.AudioManager.ADJUST_LOWER;
   
   //下边的两个方式可以添加音乐
   //notification.sound = Uri.parse("http://www.php.cn/asset/1.mp3"); 
   //notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6"); 
   Intent intent = new Intent(this, functions.class);
   PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
   // 点击状态栏的图标出现的提示信息设置
   notification.setLatestEventInfo(this, "内容提示:", "我就是一个测试文件", pendingIntent);
   manager.notify(id, notification);
   
  }
ログイン後にコピー

31。 Android ポップアップ レイヤー [ポップアップ ウィンドウ] コード

private void showPopUp(View v) {
   LinearLayout layout = new LinearLayout(this);
   layout.setBackgroundColor(Color.GRAY);
   TextView tv = new TextView(this);
   tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
   tv.setText("I&#39;m a pop -----------------------------!");
   tv.setTextColor(Color.WHITE);
   layout.addView(tv);
   PopupWindow popupWindow = new PopupWindow(layout,120,120);
   
   popupWindow.setFocusable(true);
   popupWindow.setOutsideTouchable(true);
   popupWindow.setBackgroundDrawable(new BitmapDrawable());
   
   int[] location = new int[2];
   v.getLocationOnScreen(location);
   
   popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1]-popupWindow.getHeight());
  }  
  showPopUp(LayoutInflater.from(getBaseContext()).inflate(R.layout.popview, null));
ログイン後にコピー

32。 Android は、新しい XML レイアウト ファイル


LayoutInflater.from(getBaseContext()).inflate(R.layout.popview, null);
ログイン後にコピー

33 を通じてビュー オブジェクトを取得します。ホバー機能に必要な権限


<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
ログイン後にコピー

34.フローティングボタンを追加


 权限  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> 
 
WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window");  
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();  
wmParams.type=2002;  //type是关键,这里的2002表示系统级窗口,你也可以试试2003。  
wmParams.format=1;  
wmParams.flags=40;  
wmParams.width=40;  
wmParams.height=40;  
wm.addView(LayoutInflater.from(getBaseContext()).inflate(R.layout.popview, null), wmParams);//创建View
ログイン後にコピー
この記事はphp中国語ウェブサイトユーザー「Ty80」によって提供され、元のアドレス: http://www.php.cn/java-article-374028.html


転載しないでください~~~

phpを学ぶ php中国語ウェブサイトにアクセスするだけです。

以上がAndroid の基本 フローティング ボタンとステータス バーの通知の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

会社のセキュリティソフトウェアはアプリケーションの実行に失敗していますか?それをトラブルシューティングと解決する方法は? 会社のセキュリティソフトウェアはアプリケーションの実行に失敗していますか?それをトラブルシューティングと解決する方法は? Apr 19, 2025 pm 04:51 PM

一部のアプリケーションが適切に機能しないようにする会社のセキュリティソフトウェアのトラブルシューティングとソリューション。多くの企業は、内部ネットワークセキュリティを確保するためにセキュリティソフトウェアを展開します。 ...

エンティティクラス変数名をエレガントに取得して、データベースクエリ条件を構築する方法は? エンティティクラス変数名をエレガントに取得して、データベースクエリ条件を構築する方法は? Apr 19, 2025 pm 11:42 PM

データベース操作にMyBatis-Plusまたはその他のORMフレームワークを使用する場合、エンティティクラスの属性名に基づいてクエリ条件を構築する必要があることがよくあります。あなたが毎回手動で...

MapsTructを使用したシステムドッキングのフィールドマッピングの問題を簡素化する方法は? MapsTructを使用したシステムドッキングのフィールドマッピングの問題を簡素化する方法は? Apr 19, 2025 pm 06:21 PM

システムドッキングでのフィールドマッピング処理は、システムドッキングを実行する際に難しい問題に遭遇することがよくあります。システムのインターフェイスフィールドを効果的にマッピングする方法A ...

名前を数値に変換してソートを実装し、グループの一貫性を維持するにはどうすればよいですか? 名前を数値に変換してソートを実装し、グループの一貫性を維持するにはどうすればよいですか? Apr 19, 2025 pm 11:30 PM

多くのアプリケーションシナリオでソートを実装するために名前を数値に変換するソリューションでは、ユーザーはグループ、特に1つでソートする必要がある場合があります...

Intellijのアイデアは、ログを出力せずにSpring Bootプロジェクトのポート番号をどのように識別しますか? Intellijのアイデアは、ログを出力せずにSpring Bootプロジェクトのポート番号をどのように識別しますか? Apr 19, 2025 pm 11:45 PM

intellijideaultimatiateバージョンを使用してスプリングを開始します...

Javaオブジェクトを配列に安全に変換する方法は? Javaオブジェクトを配列に安全に変換する方法は? Apr 19, 2025 pm 11:33 PM

Javaオブジェクトと配列の変換:リスクの詳細な議論と鋳造タイプ変換の正しい方法多くのJava初心者は、オブジェクトのアレイへの変換に遭遇します...

データベースクエリにTKMYBATISを使用するときに、エンティティクラスの変数名の構築クエリ条件をエレガントに取得する方法は? データベースクエリにTKMYBATISを使用するときに、エンティティクラスの変数名の構築クエリ条件をエレガントに取得する方法は? Apr 19, 2025 pm 09:51 PM

データベースクエリにTKMYBATISを使用する場合、クエリ条件を構築するためにエンティティクラスの変数名を優雅に取得する方法は一般的な問題です。この記事はピン留めします...

eコマースプラットフォームSKUおよびSPUデータベースデザイン:ユーザー定義の属性と原因のない製品の両方を考慮する方法は? eコマースプラットフォームSKUおよびSPUデータベースデザイン:ユーザー定義の属性と原因のない製品の両方を考慮する方法は? Apr 19, 2025 pm 11:27 PM

eコマースプラットフォーム上のSKUおよびSPUテーブルの設計の詳細な説明この記事では、eコマースプラットフォームでのSKUとSPUのデータベース設計の問題、特にユーザー定義の販売を扱う方法について説明します。

See all articles