2014年12月30日 星期二

JavaScript-基本 用法

Java 不等於 JavaScript !

1 . 需要的工具 ?
您可以下載 Notepad++ 來編寫。

2 . Html vs JavaScript vs jQuery 關係?
一) JavaScript 最主要讓您的網頁更活,不會死板板的
二) 通常一個JavaScript Function  會對應一個 Html 的原件
三) JQuery 是以 JavaScript基底
四) JQuery 可以看成工具包 ( 效果、事件...等 ) 都已經寫在裡面
三) Script可放在html任何位置內, 但Head 和 body 不要間斷,都是可以使用的。
      但一般常用於Head 或 Body 內

3 . 如何開始 ?
一) 開啟 Notepad++
二) 將以下的程式碼貼在編輯區域內
三) 儲存檔案的副檔名為 : XXX.html
四) 點擊生成的檔案即可觀看成果

<!DOCTYPE HTML>
<html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>熱身</title>
</head>
<body>
  <p id="p1">大家好</p>
  
  <script type="text/javascript">
    document.write("hello");
    document.getElementById("p1").style.color="red";
  </script>
</body>
</html>



















<script type="text/javascript">
         document.write("hello");
</script>

hello

<p id="p1">大家好</p>

<script type="text/javascript">
         document.getElement("p1").style.color="red";
</script>

大家好
script.js
document.write("hello");

Main.html
<script src="script.js">
</script>
hello
<script type="text/javascript">
         var a = "hello";
         document.write(a);
</script>
hello
<script type="text/javascript">
         function aaa(){
                var a = "hello";
                document.write(a);
          }
</script>

<script type="text/javascript">
         function aaa(){
                var a = "hello";
                alert(a);
          }
</script>
跳出提醒視窗( hello )
<script type="text/javascript">
         function aaa(){
                var a = confirm("你是帥哥嗎?");
                if(a == true){
                      document.write("真的 !!!");
                 } else{
                      document.write("要有自信!!!");
                }
          }
</script>
<input name="button" type="button" onClick="rec()"
                       value="請點我" />
點擊後會觸發aaa對話視窗
會有Yes、No選項

<script type="text/javascript">
  function rec(){
var score = prompt("請輸入您的成績 :",60) ;
if(score>=90) {
  document.write("棒!");
} else if(score>=75) {
  document.write("不錯!");
} else if(score>=60) {
  document.write("要加油!");
 } else {
       document.write("要努力了!");
}
  }
</script>
<input name="button" type="button"
onClick="rec()" value="點擊我!" />
輸入參數視窗( 60 是預設參數 )
<script type="text/javascript">
  function openWindow(){
      window.open('http://www.yahoo.com.tw');
  }
</script>
開啟新的頁面
<script type="text/javascript">
window.open('http://www.yahoo.com.tw','_blank',
'width=500,height=500,menubar=no,toolbar=no, status=no,scrollbars=yes')
</script>

空格一 :
URL

空格二 :
開啟視窗的型態
_top : 當前頁面
_blank : 新視窗
_selft : 在同頁面開啟新視窗

空格三 :

toolbar(Yes | No) : 工具列是否顯示
scrollbars(Yes | No) : 是否使用滾動卷軸
resizeable(Yes | No ) : 使用者是否可以調整視窗
location(Yes | No ) : 是否顯示網址
menubar(Yes | No) : 是否顯示目錄
status(Yes | No ) : 是否顯示狀態列
left(pixels) : 距離左邊距離
top(pixels) : 距離上方距離

開啟新的頁面
附帶條件
<script type="text/javascript">
     var mywin=window.open("http://www.yahoo.com.tw");
     mywin.close();
</script>
關閉視窗
document.getElementById("id");

<p id="s">JavaScript</p>
<script type="text/javascript">
  var str=  document.getElementById("s");
</script>

藉由ID獲取相關元素
Object.innerHTML( 大小寫有區分 )

<h2 id="s">javascript</H2>
<script type="text/javascript">
  var str= document.getElementById("s").innerHTML;
  document.write("Output : "+str.innerHTML+"<br>");
</script>

用來存/取HTML裡的元素

Output : javascript
Object.style.property

<p id="pcon">Hello World!</p>
<script>
   var mychar = document.getElementById("pcon");
   mychar.style.color="red";
   mychar.style.fontSize="20";
   mychar.style.backgroundColor ="blue";
</script>
更改HTML樣式

<style>
    body{ font-size:16px;}
    .one{
border:1px solid #eee;
width:230px;
height:50px;
background:#ccc;
color:red;
    }
    .two{
border:1px solid #ccc;
width:230px;
height:50px;
background:#9CF;
color:blue;
    }
</style>

<script type="text/javascript">
     function add(){
           var p1 = document.getElementById("p1");
           p1.className = "one";
     }
     function modify(){
           var p2 = document.getElementById("p2");
           p2.className =  "two";
     }
</script>


您好
你也好

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8" />
<title>javascript</title>
<style type="text/css">
body{font-size:12px;}
#txt{
    height:400px;
    width:600px;
border:#333 solid 1px;
padding:5px;}
p{
line-height:18px;
text-indent:2em;}
</style>
</head>
<body>
  <h2 id="con">JavaScript课程</H2>
  <div id="txt">
     <h5>JavaScript为网页添加动态效果并实现与用户交互的功能。</h5>
        <p>1. JavaScript入门篇,让不懂JS的你,快速了解JS。</p>
        <p>2. JavaScript进阶篇,让你掌握JS的基础语法、函数、数组、事件、内置对象、BOM浏览器、DOM操作。</p>
        <p>3. 学完以上两门基础课后,在深入学习JavaScript的变量作用域、事件、对象、运动、cookie、正则表达式、ajax等课程。</p>
  </div>
  <form>
    <!--当点击相应按钮,执行相应操作,为按钮添加相应事件-->
    <input type="button" value="改变颜色" onClick="changeColor()">
    <input type="button" value="改变宽高" onClick="changeWidthHigh()">
    <input type="button" value="隐藏内容" onClick="changeDisplay()">
    <input type="button" value="显示内容" onClick="changeDisplayBlock()">
    <input type="button" value="取消设置" onClick="changeReset()">
  </form>
  <script type="text/javascript">
    //定义"改变颜色"的函数
    function changeColor(){
        var color = document.getElementById("txt");
        color.style.color = "blue";
    }
    //定义"改变宽高"的函数
    function changeWidthHigh(){
        var color = document.getElementById("txt");
        color.style.width = "200px";
        color.style.height = "200px";
    }

    //定义"隐藏内容"的函数
    function changeDisplayNone(){
        var color = document.getElementById("txt");
        color.style.display = "none";
    }

    //定义"显示内容"的函数
    function changeDisplayBlock(){
        var color = document.getElementById("txt");
        color.style.display = "block";
    }

    //定义"取消设置"的函数
    function changReset(){
        var color = document.getElementById("txt");
        color.removeAttribute("style");
    }
  </script>
</body>
</html>
這是在練習DEMO所留下來
var a=document.getElementById("txt1").value;
document.getElementById("fruit").value=d;
取得文字框內容
對元件設定參數
45
12
45


參考資料 : 重新介紹 JavaScript

Android-ListView GridView Gallery 和 BaseAdapter 的列表使用

不管在我們的手機電話簿,還是其他的應用程式
幾乎都看的到列表的存在
這就來一個簡單地舉例

1 . 一定有一大筆整理好的資料
2 . 再來選擇我們要置放的大容器
3 . 容器內每個抽屜內要如何擺放

public class MainActivity extends Activity {

    private ListView listView;
    private List<String> list;

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

        //我的容器
        listView = (ListView) findViewById(R.id.listView1);
        list = new ArrayList<String>();
        
        //所有整理好資料
        for(int i=0; i<10; i++){
            list.add("王 "+i);
        }
        
        //將容器調適為我們可用格式
        Adapter adapter = new Adapter(this);
        listView.setAdapter(adapter);
        
    }

    private class Adapter extends BaseAdapter{

        private LayoutInflater mInflater = null;

        private Adapter(Context context) {  
            this.mInflater = LayoutInflater.from(context);  
        }

        public void updateResults("如果有獨立Class,請添加來源") {
            notifyDataSetChanged(); //更新列表用
        }
        
        @Override
        public int getCount() {

            return list.size();
        }

        @Override
        public Object getItem(int position) {

            return null;
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Elements elements = null;  
            
            if (convertView == null) {  
                elements = new Elements();  
                //我抽屜裡的設計圖
                convertView = mInflater.inflate(R.layout.listview_con, null);  
                //裡面有XX元件( 如果有而外需求,必須在 Elements 內添加才可以使用 )
                elements.str1 = (TextView) convertView.findViewById(R.id.textView1);   
                convertView.setTag(elements);  
            } else {  
                elements = (Elements) convertView.getTag();  
            }  
            
            //將資料依序放入我擺放的位置
            elements.str1.setText((String) list.get(position).toString());  
  
            return convertView; 
        }

    }

    //每格要擺放的元件( 如有而外需求可再添加 )
    private class Elements{
        TextView str1;
    }

}

容器.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>

抽屜.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp" />

</LinearLayout>


成果圖 :
























注意 :
listView.setOnItemClickListener(this);

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/mainBackgroundColor"
    android:descendantFocusability="blocksDescendants">
    
    .
    .
    .
</LinearLayout>

參考資訊 : ListView裡的OnItemClickListener失去作用(失效)

歡迎轉載,請註明出處。

2014年12月27日 星期六

Android-模仿FB WebView 瀏覽網頁介面

更改日期 : 20160310_WebView_JavaScript

各位大大是否有注意到 FB 瀏覽網頁的介面有更改了
好久之前是直接幫您開網頁連結
但現在是直接在WebView瀏覽

(  FB 版本 )






今天的範例就來模擬 FB 瀏覽網頁的 Activity

首先我們先設定介面位置

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <Button
            android:id="@+id/button1"
            android:layout_width="60dip"
            android:layout_height="50dip"
            android:text="返回" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="50dip"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/button2"
            android:layout_toRightOf="@+id/button1"
            android:gravity="center"
            android:text="TextView"
            android:textSize="18sp" />

        <Button
            android:id="@+id/button2"
            android:layout_width="60dip"
            android:layout_height="50dip"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="刷新" />
    </RelativeLayout>

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/relativeLayout1" />

</RelativeLayout>


接下來就是要來真的 WebView 做監聽設定

public class MainActivity extends Activity implements OnClickListener{

    WebView webView;
    private Button backBtn;
    private Button refreshBtn;
    private TextView titleView;

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

        backBtn = (Button) findViewById(R.id.button1);
        refreshBtn = (Button) findViewById(R.id.button2);
        titleView = (TextView) findViewById(R.id.textView1);
        webView = (WebView) findViewById(R.id.webView1);

        webView.loadUrl("http://www.yahoo.com.tw");

        // 是否資源 JavaScript 資源
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        
        webView.setWebChromeClient(new WebChromeClient(){

            //將網頁Title顯示到Acitity Title
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                
                titleView.setText(title);
            }
            
        });

        
        webView.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //複寫網頁視窗
                view.loadUrl(url);

                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //如果收到Error則顯示哪頁面
                view.loadUrl("file:///android_asset/error.html");
                
            }

        });

        //設置下載監聽器
        webView.setDownloadListener(new DownloadListener(){

            @Override
            public void onDownloadStart(String url, String userAgent,
                    String contentDisposition, String mimetype,
                    long contentLength) {
                //如果連結最後為APK,則執行系統下載功能
                if(url.endsWith(".apk")){
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }

            }});

        backBtn.setOnClickListener(this);
        refreshBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
        case R.id.button1:
            finish();
            break;

        case R.id.button2:
            webView.reload();
            break;
        }
    }
}

如果要有上一頁、下一頁功能
1 . 先判斷有無存在上、下一頁的暫存
2 . 執行方法
上一頁
if(webView.canGoBack())
{
    webView.goBack();
}

下一頁
if(webView.canGoForward())
{
    webView.goForward();
}


中間有Error.html的更改網路連線錯誤所要顯示的畫面
可以依照User的需求擺放( 位置 : assets/error.html )

注意 : 一定要加上網路連線權限

<uses-permission android:name="android.permission.INTERNET"/>


以下是執行出來的畫面,因該有5成相似了吧!!! OTZ

























歡迎轉載,請註明出處。

2014年12月25日 星期四

Android-用 Handler 製造出延遲( delay ) 發生的效果

今天看到 Android Sample 裡面有一些基本常用的功能
那就是  : 延遲 ( Delay  )
廢話不多說,我們就來趕緊看程式碼吧 !


方法一 :
Handler.postDelayed 
Android 才提供 ( android.os.Handler.postDelayed(Runnable r, long delayMillis) )

Handler handler = new Handler();
handler.postDelayed(new Runnable(){

    @Override
    public void run() {
                
        //過兩秒後要做的事情
        Log.d("tag","我要打掃了");
                
    }}, 2000);


方法二 :

try{
    // delay 1 second
    Thread.sleep(1000);
        
} catch(InterruptedException e){
    e.printStackTrace();
        
}


歡迎轉載,請註明出處。


2014年12月21日 星期日

Android-使用 HttpResponse 連線時 一直回應 401

不知道各位大大是否有發生過執行連線,但回應是FileNotFoundException
message : java.io.FileNotFoundException: http://XXX.XXX.XXX.XXX/XXXXX
或者回應401的情況
之後大概查詢有關401的基本意思 : 必須要使用者資訊
如下 :
















我們要做的動作就是執行連結時,也必須要把使用者資訊也一起帶進去


            BufferedReader rd = null;
            try {
                URL url = new URL(urlString);
                HttpURLConnection httpconn = (HttpURLConnection) url
                        .openConnection();
                String authCombination = "admin" + ":" + "admin";
                String accountCode = Base64.encodeToString(authCombination.getBytes(),
                        Base64.DEFAULT);
                httpconn.setRequestProperty("Authorization", "Basic "+ accountCode);
                httpconn.setConnectTimeout(4000);
                httpconn.setReadTimeout(4000);
                httpconn.connect();
                rd = new BufferedReader(new InputStreamReader(
                        httpconn.getInputStream()));
                int returnCode = httpconn.getResponseCode();
                if (returnCode == 200) {
                    
                } else {
                   
                }
            } catch (MalformedURLException e) {
                
            } catch (IOException e) {
               
            } finally {
                try {
                    if (rd != null)
                        rd.close();
                } catch (IOException e) {
                   
                }
            }

歡迎轉載,請註明出處 。

2014年12月16日 星期二

Android-Socket Server 端 接收 訊息

在上一篇有談到 Socket Client 端
以現實中的例子
如果有投手(Client)投球,那就會有捕手(Server)接球
Service以下的例子為例,是不斷地等待相關的訊息

如果有收到相關的訊息,那就會顯示在畫面上

Main.java

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView test;
    TextView test2;

    private Handler handler = new Handler();
    private ServerSocket serverSocket;
    private String line ;



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

        test = (TextView) findViewById(R.id.text1);
        test2 = (TextView) findViewById(R.id.text2);

        //建立Thread
        Thread fst = new Thread(socket_server);
        //啟動Thread
        fst.start();

    }

    //取得IP
    private String getMyIp(){
        //新增一個WifiManager物件並取得WIFI_SERVICE
        WifiManager wifi_service = (WifiManager)getSystemService(WIFI_SERVICE);
        //取得wifi資訊
        WifiInfo wifiInfo = wifi_service.getConnectionInfo();
        //取得IP,但這會是一個詭異的數字,還要再自己換算才行
        int ipAddress = wifiInfo.getIpAddress();
        //利用位移運算和AND運算計算IP
        String ip = String.format("%d.%d.%d.%d",(ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
        return ip;
    }


    private Runnable socket_server = new Runnable(){
        public void run(){
            handler.post(new Runnable() {
                public void run() {
                    test.setText("Listening...." + getMyIp());
                }
            });

            try{
                //建立serverSocket
                serverSocket = new ServerSocket(1234);

                //等待連線
                while (true) {
                    //接收連線
                    Socket client = serverSocket.accept();

                    handler.post(new Runnable() {
                        public void run() {
                            test.setText("Connected.");
                        }
                    });
                    try {
                        //接收資料
                        DataInputStream in = new DataInputStream(client.getInputStream());
                        line = in.readUTF();
                        while (line != null) {
                            handler.post(new Runnable() {
                                public void run() {
                                    test2.setText(line);
                                }
                            });
                        }
                        break;
                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            public void run() {
                                test.setText("傳送失敗");
                            }
                        });
                    }
                }
            }catch(IOException e){
                handler.post(new Runnable() {
                    public void run() {
                        test.setText("建立socket失敗");
                    }
                });
            }
        }
    };
}

最後記得要加上權限

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>

歡迎轉載,請註明出處。




Android-Socket Client 端 發送 訊息

Socket : 網路編程,兩台電腦相互通訊數據。
基本模型 : Client、Server
基本概念 : 兩個進程之間相互通訊,然後其中一個必須提供固定的位置,而另一個端
                   只需要知道這個固定的位置,並去建立兩者之間的聯繫。固定位置的被稱
                   為伺服器;建立聯繫的被稱為客戶端。

Control.java
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import javax.net.SocketFactory;

import android.util.Log;

public class Control {

    private static String host;
    private static int port;
    private static int timeout = 3000;
    private static PrintWriter mOutput;

    public Control(String host, int port){
        Control.host = host;
        Control.port = port;
    }
    
    public void send(String mess, ControlCallback controlCallback){
        new Send(mess, controlCallback).start();
    }
    
    //發送訊息
    private static class Send extends Thread {
        final String action;

        public Send(String action) {
            this.action = action;
            
        }

        public void run() {

            try{
                
                Socket socket = SocketFactory.getDefault().createSocket();
                SocketAddress remoteaddr = new InetSocketAddress(host, port);
                socket.connect(remoteaddr, timeout);  
                
                Log.d("tag","running!!!  Host : "+host+" port : "+port);
                mOutput = new PrintWriter(new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream())), true);
                mOutput.println(action);
                Log.d("tag","Link success");
                
            }catch(ConnectException e){
                Log.d("tag","Fail !! ConnectException : "+e.getMessage());

            }catch(Exception e){
                Log.d("tag","Fail !!  Exception : "+e.getMessage());

            }
        };
    }
}


記得要加入權限

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>

歡迎轉載,請註明出處。