Android 开发技巧总结(二)

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.设置在手机中控制字的回车

在需要回车的地方加上

例如:在strings.xml中设置的效果为:

<string name="vip_content_small11">比普通用户享受更低的价格 更多种类的优惠券比团 购更优惠,更方便</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是纵向)

原文地址:https://www.cnblogs.com/kuaileyuyi/p/3852862.html