Android 開發技巧總結(二)

來源:互聯網
上載者:User

標籤:android   des   style   http   color   使用   

1.喜好設定的存取資料

寫一個類,裡面放入存取方法,然後在外面進行調用

public class PrefsUtils {

private static final String PREFS_NAME="com.yomoto.util.OtherPrefs";

//這裡放入的名字存入的地址是:data/data/項目包名/shared_prefs/PREFS_NAME

//得到喜好設定中的資料

public static String getValue(Context context,String key,String defaultvalue){

SharedPreferences prefs=context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

if(prefs==null) return "Unknow";

return prefs.getString(key, defaultvalue);

}

//向喜好設定中存入資料

public static void setValue(Context context,String key,String value){

SharedPreferences prefs=context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

Editor editor=prefs.edit();

if(editor==null) return;

editor.putString(key, value);

editor.commit();

}}

在外面對喜好設定中的方法進行調用:

拿資料:

//0是拿欄位為intro1的值的時,沒有值情況下的預設值

PrefsUtils.getValue(BaseApplication.this, "intro1", "0");

存資料:

PrefsUtils.setValue(LogoActivity.this, "intor1", "1");

2.連網情況的判斷,可以放入工具類中的方法

Public static Boolean isNetworkAvailable(Contextcontext){

try{

ConnectivityManager cm = (ConnectivityManager)context

.getSystemService(Context.CONNECTIVITY_SERVICE);

//擷取網路資訊

NetworkInfo info = cm.getActiveNetworkInfo();

//返回檢測的網路狀態

return(info!=null&&info.isConnected());

}catch(Exceptione){

e.printStackTrace();

returnfalse;

}

}

3.判斷SD卡是否存在,可以放入工具類中的方法

Public static Boolean hasSdcard(){

String state = Environment.getExternalStorageState();

if(state.equals(Environment.MEDIA_MOUNTED)){

return true;

}else{

return false;

}}

 

 

4.在activity中的幾個常用設定

//預設不彈出軟鍵盤,在setContentView之前

1)getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

//設定介面全屏,在setContentView之前

2)getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

或者在manifest中進行設定,android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"

5.在ScrollView中嵌入GridView和ListView

public class NavigationGridview extends GridView{

 

public NavigationGridview(Contextcontext,AttributeSetattrs){

super(context,attrs);

}

 

publicNavigationGridview(Contextcontext){

super(context);

}

 

publicNavigationGridview(Contextcontext,AttributeSetattrs,intdefStyle){

super(context,attrs,defStyle);

}

 

@Override

publicvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){

int expandSpec = MeasureSpec.makeMeasureSpec(

Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec,expandSpec);

}}

 

ListView與GridView一樣,重寫的方法一樣。

6.Android生命週期的問題

1)軟體啟動後,第一次會執行baseapplication和啟動的activity,按返回鍵退出的再開啟的時候不執行baseapplication,只有將進程殺死,才會執行baseapplication和activity.

7.文法問題

1. 設定日期格式的文法

private SimpleDateFormat format;

format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

Date current = new Date(System.currentTimeMillis());

String str = format.format(current);

2.設定在手機中控制字的斷行符號

在需要斷行符號的地方加上\n

例如:在strings.xml中設定的效果為:

<string name="vip_content_small11">比普通使用者享受更低的價格\n更多種類的優惠券比團\n購更優惠,更方便</string>

8.額外知識點總結

1)手機螢幕

小米1s的手機螢幕 高度:854 寬度:480

三星5.8寸手機螢幕 高度:960 寬度:540

9.問題解決和處理

1)在ScrollView中的Listview有時候添加完資料後,listview會擷取焦點,導致介面顯示從listview開始,此時在listView.setAdapter(adapter);後加上

listView.setFocusable(false);來解決焦點的問題。

10.手機直接跳轉到網頁

Uriuri=Uri.parse("http://appadmin.ibinggo.com/adm_program/modules/downloads/get_file.php?file_id=7");

Intentintent=newIntent(Intent.ACTION_VIEW,uri);

startActivity(intent);

11. message配合handler的使用

Messagemessage=mHandler.obtainMessage();//資料下載完畢後,向handler發送一個資料,進行介面ui的更新。

message.what=1;

message.sendToTarget();

 

Handler mHandler = new Handler(){

@Override

Public void handleMessage(Messagemsg){

super.handleMessage(msg);

if(msg.what==1){}

}}

12. Android基礎知識點

1)Android UI更新是在主線程中進行的。

2)<application

android:allowBackup="true"

android:icon="@drawable/ic_donga"

//這裡一定要寫上它的名字

android:name="com.qianxunnt.xinlife.activity.BaseApplication"

android:label="@string/app_name"

android:theme="@style/Theme.Sherlock"

>

3)根據條件分割字串

String[] s = t.split("sess_id="); //拆分欄位

4) Gson gson =new Gson(); //解析json到localCouponsList

//處理集合資料

mCoupons = gson.fromJson(t, new TypeToken<List<CouponsInfo>>(){}.getType());

//處理單獨的類資料

updateTime = gson.fromJson(t, UpdateTimeInfo.class);

5) NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

 // 建立一個Notification

Notification notification = new Notification();

 // 設定顯示在手機最上邊的狀態列的表徵圖

notification.icon = R.drawable.ic_donga;

// 噹噹前的notification被放到狀態列上的時候,提示內容

notification.tickerText = "您已成功升級為VIP使用者!";

//添加聲音提示

notification.defaults = Notification.DEFAULT_SOUND;

//讓通知點擊消失的按鈕

notification.flags |= Notification.FLAG_AUTO_CANCEL;

Intent intent = new Intent(NewCouponsDetailActivity.this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(NewCouponsDetailActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

 // 點擊狀態列的表徵圖出現的提示資訊設定

notification.setLatestEventInfo(NewCouponsDetailActivity.this, "繽購提示", "您已經成功升級為VIP使用者,使用到期日"+useTime+"天!", pendingIntent);

manager.notify(1,notification);

6)String sDest=URLDecoder.decode(couponsContent.getContent(), "utf-8");

//沒有執行baseapplication所以無值

kuaicanWebview.getSettings().setDefaultTextEncodingName("UTF-8") ;

kuaicanWebview.loadDataWithBaseURL(null,sDest,"text/html","UTF-8",null);

7)代碼中為控制項設定一段簡單的動畫

Animation animation = new TranslateAnimation(one*currIndex, one*arg0, 0, 0);//顯然這個比較簡潔,只有一行代碼。

animation.setFillAfter(true);// True:圖片停在動畫結束位置

animation.setDuration(300);

imageView.startAnimation(animation);

8)列表dialog的設定

new AlertDialog.Builder(this).setTitle("報錯選擇")

.setItems(

new String[] {"電話報錯","地址報錯","地圖位置報錯" }, //列表內容

new DialogInterface.OnClickListener() {//點擊監聽

@Override

public void onClick(

DialogInterface dialog, int which) {//點擊位置

}})

 .setNegativeButton("確定", null)

 .show();

9)根據經緯度算距離

public static double distanceByLngLat(double lng1, double lat1, double lng2,double lat2) {

    double radLat1 = lat1 * Math.PI / 180;

    double radLat2 = lat2 * Math.PI / 180;

    double a = radLat1 - radLat2;

    double b = lng1 * Math.PI / 180 - lng2 * Math.PI / 180;

    double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)

                    + Math.cos(radLat1) * Math.cos(radLat2)

                    * Math.pow(Math.sin(b / 2), 2)));

    s = s * 6378137.0;

    s = Math.round(s * 10000) / 10000;

    return s;

}

 

 

 

 

 

10)對返回按鈕的兩種監聽方式

(1) @Override

public void onBackPressed() {

// TODO Auto-generated method stub

super.onBackPressed();

}

(2) public boolean onKeyDown(int keyCode, KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_BACK) 

            {}}

11)

 XActivitiesListView listView = (XActivitiesListView)parent;  NotificationInfo coupon =(NotificationInfo)listView.getItemAtPosition(postion);//主要方法

12)設定activity的橫屏和豎屏 

android:screenOrientation=”landscape”屬性即可(landscape是橫向,portrait是縱向)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.