Android開發中15條小經驗

來源:互聯網
上載者:User

標籤:android開發   經驗總結   

Android開發中15條小經驗

1. TextView中的getTextSize返回值是以像素(px)為單位的,而setTextSize()是以sp為單位的.
所以如果直接用返回的值來設定會出錯,解決辦法是用setTextSize()的另外一種形式,可以指定單位:
setTextSize(intunit,intsize) TypedValue.COMPLEX_UNIT_PX:Pixels TypedValue.COMPLEX_UNIT_SP:ScaledPixels TypedValue.COMPLEX_UNIT_DIP:DeviceIndependentPixels
2. 在繼承自View時,繪製bitmap時,需要將圖片放到建立的drawable-xdpi中,否則容易出現繪製大小發生改變
3. 在文字中加底線: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
4. scrollView是繼承自frameLayout,所以在使用LayoutParams時需要用frameLayout的
5.在Android中幾種網路編程的方式:

(1)針對TCP/IP的Socket、ServerSocket

(2)針對UDP的DatagramSocket、DatagramPackage。這裡需要注意的是,考慮到Android裝置通常是手持終端,IP都是隨著上網進行分配的。不是固定的。因此開發也是有 一點與普通互連網應用有所差異的。

(3)針對直接URL的HttpURLConnection

(4)Google整合了Apache HTTP用戶端,可使用HTTP進行網路編程。針對HTTP,Google整合了Appache Http core和httpclient 4版本,因此特別注意Android不支援 httpclient 3.x系列,而且目前並不支援Multipart(MIME),需要自行添加httpmime.jar

(5)使用Web Service。Android可以通過開源包如Jackson去支援Xmlrpc和Jsonrpc,另外也可以用Ksoap2去實現Webservice

(6) 直接使用WebView視圖組件顯示網頁。基於WebView 進行開發,Google已經提供了一個基於chrome-lite的Web瀏覽器,直接就可以進行上網瀏覽網頁。

6. TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
這個是我們最常用的一個構造方法,
float fromXDelta:這個參數表示動畫開始的點離當前View X座標上的差值;
float toXDelta:這個參數表示動畫結束的點離當前View X座標上的差值;
float fromYDelta: 這個參數表示動畫開始的點離當前View Y座標上的差值;
float toYDelta:這個參數表示動畫開始的點離當前View Y座標上的差值;

如果view在A(x,y)點 那麼動畫就是從B點(x+fromXDelta, y+fromYDelta)點移動到C 點 (x+toXDelta,y+toYDelta)點.

7.android提供了幾種在其他線程中訪問UI線程的方法。

Activity.runOnUiThread( Runnable )

View.post( Runnable )

View.postDelayed( Runnable, long )

從網上擷取一個網頁,在一個TextView中將其原始碼顯示出來

packageorg.unique.async; importjava.io.ByteArrayOutputStream; importjava.io.InputStream; importjava.util.ArrayList; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.client.HttpClient; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.impl.client.DefaultHttpClient; importandroid.app.Activity; importandroid.app.ProgressDialog; importandroid.content.Context; importandroid.content.DialogInterface; importandroid.os.AsyncTask; importandroid.os.Bundle; importandroid.os.Handler; importandroid.os.Message; importandroid.view.View; importandroid.widget.Button; importandroid.widget.EditText; importandroid.widget.TextView; publicclassNetworkActivityextendsActivity{   privateTextViewmessage;   privateButtonopen;   privateEditTexturl;   @Override   publicvoidonCreate(BundlesavedInstanceState){    super.onCreate(savedInstanceState);    setContentView(R.layout.network);    message=(TextView)findViewById(R.id.message);    url=(EditText)findViewById(R.id.url);    open=(Button)findViewById(R.id.open);    open.setOnClickListener(newView.OnClickListener(){      publicvoidonClick(Viewarg0){        connect();      }    });   }   privatevoidconnect(){     PageTasktask=newPageTask(this);     task.execute(url.getText().toString());   }   classPageTaskextendsAsyncTask<String,Integer,String>{     //可變長的輸入參數,與AsyncTask.exucute()對應     ProgressDialogpdialog;     publicPageTask(Contextcontext){       pdialog=newProgressDialog(context,0);         pdialog.setButton("cancel",newDialogInterface.OnClickListener(){       publicvoidonClick(DialogInterfacedialog,inti){        dialog.cancel();       }       });       pdialog.setOnCancelListener(newDialogInterface.OnCancelListener(){       publicvoidonCancel(DialogInterfacedialog){        finish();       }       });       pdialog.setCancelable(true);       pdialog.setMax(100);       pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);       pdialog.show();     }     @Override     protectedStringdoInBackground(String...params){       try{        HttpClientclient=newDefaultHttpClient();        //params[0]代表串連的url        HttpGetget=newHttpGet(params[0]);        HttpResponseresponse=client.execute(get);        HttpEntityentity=response.getEntity();        longlength=entity.getContentLength();        InputStreamis=entity.getContent();        Strings=null;        if(is!=null){          ByteArrayOutputStreambaos=newByteArrayOutputStream();          byte[]buf=newbyte[128];          intch=-1;          intcount=0;          while((ch=is.read(buf))!=-1){            baos.write(buf,0,ch);            count+=ch;            if(length>0){              //如果知道響應的長度,調用publishProgress()更新進度              publishProgress((int)((count/(float)length)*100));            }            //讓線程休眠100ms            Thread.sleep(100);          }          s=newString(baos.toByteArray());}        //返回結果        returns;       }catch(Exceptione){        e.printStackTrace();       }       returnnull;     }     @Override     protectedvoidonCancelled(){       super.onCancelled();     }     @Override     protectedvoidonPostExecute(Stringresult){       //返回HTML頁面的內容       message.setText(result);       pdialog.dismiss();      }     @Override     protectedvoidonPreExecute(){       //任務啟動,可以在這裡顯示一個對話方塊,這裡簡單處理       message.setText(R.string.task_started);     }     @Override     protectedvoidonProgressUpdate(Integer...values){       //更新進度        System.out.println(""+values[0]);        message.setText(""+values[0]);        pdialog.setProgress(values[0]);     }   } }


8.Spinner不能用在dialog 和 tabhost中的解決辦法


9. Unable to open sync connection!
把設定裡的USB調試重啟

10.EditText設定游標位置問題

EditText中有一些預置文本的時候,想把游標調到最前面,一開始是使用的setSelection(0),結果發現在三星P1000上面有問題。經過研究發現需要先調用EditText.requestFocus(),再調用setSelection(0)。否則的話,在2.x的機器上有問題,但3.x上面是好著的。

11.Android中Home鍵被系統保留,無法象監聽回退鍵一樣用onKeyDown,但是可以根據按下home鍵時會觸發的activity和view的一些事件來添加自己的處理代碼.網上有人說可以用onAttachWindow來攔截Home鍵,遇到可以試試。

12.在用surfaceView渲染時,如果要想在需要時其中出現其他View,可以將surfaceView和其他View放在layout中,平常時可以將其他view隱藏


13.使用android:imeOptinos可對Android內建的軟鍵盤進行一些介面上的設定:

android:imeOptions="flagNoExtractUi"//使軟鍵盤不全螢幕顯示,只佔用一部分螢幕  同時,這個屬性還能控制項軟鍵盤右下角按鍵的顯示內容,預設情況下為斷行符號鍵  android:imeOptions="actionNone"//輸入框右側不帶任何提示  android:imeOptions="actionGo"//右下角按鍵內容為'開始'  android:imeOptions="actionSearch"//右下角按鍵為放大鏡圖片,搜尋  android:imeOptions="actionSend"//右下角按鍵內容為'發送'  android:imeOptions="actionNext"//右下角按鍵內容為'下一步'  android:imeOptions="actionDone"//右下角按鍵內容為'完成'


14.為TextView添加陰影
<stylename="Overlay">     <itemname="android:paddingLeft">2dip</item>     <itemname="android:paddingBottom">2dip</item>     <itemname="android:textColor">#ffffff</item>     <itemname="android:textSize">12sp</item>     <itemname="android:shadowColor">#00ff00</item>     <itemname="android:shadowDx">5</item>     <itemname="android:shadowDy">3</item>     <itemname="android:shadowRadius">6</item>  </style>  <TextViewandroid:id="@+id/test"      android:layout_width="fill_parent"      android:layout_height="wrap_content"      style="@style/<spanstyle="background-color:rgb(250,250,250);font-family:Helvetica,Tahoma,Arial,sans-serif;">Overlay</span>"      android:text="test"      android:gravity="center"/>


15.如何將TextView中的中文設定成粗體?
在xml檔案中使用android:textStyle=”bold” 可以將英文設定成粗體,但是不能將中文設定成粗體,將中文設定成粗體的方法是:

TextView tv = (TextView)findViewById(R.id.TextView01);TextPaint tp = tv.getPaint();tp.setFakeBoldText(true);


Android開發中15條小經驗

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.