自用知识

1异步内部类

private Handler handler = new Handler(){

                   @Override

public void handleMessage(Message msg){

                            if(msg.obj!= null && listener != null){

                                     listener.onResult(msg.obj.toString());

                            }

                   }

         };

其中使用的正是内部类
·匿名内部类不能有构造方法。
·匿名内部类不能定义任何静态成员、静态方法。
·匿名内部类不能是public,protected,private,static。
·只能创建匿名内部类的一个实例。
·一个匿名内部类一定是在new的后面,用其隐含实现一个接口或实现一个类。
·因匿名内部类为局部内部类,所以局部内部类的所有限制都对其生效。

2字节流与字符流的区别(5.1)

java.io.Reader 和 java.io.InputStream组成了Java 输入类。

Reader 用于读入16位字符,也就是Unicode编码的字符;而 InputStream 用于读入 ASCII 字符和二进制数据。

Reader支持16位的Unicode字符输出,

InputStream支持8位的字符输出。

Reader和InputStream分别是I/O库提供的两套平行独立的等级机构,

 

1byte = 8bits

InputStream、OutputStream是用来处理8位元的流,

Reader、Writer是用来处理16位元的流。

而在JAVA语言中,byte类型是8位的,char类型是16位的,所以在处理中文的时候需要用Reader和Writer。

值得说明的是,在这两种等级机构下,还有一道桥梁InputStreamReader、OutputStreamWriter负责进行InputStream到Reader的适配和由OutputStream到Writer的适配。

 

stream结尾都是字节流,reader和writer结尾都是字符流 两者的区别就是读写的时候一个是按字节读写,一个是按字符。 实际使用通常差不多。 在读写文件需要对内容按行处理,比如比较特定字符,处理某一行数据的时候一般会选择字符流。只是读写文件,和文件内容无关的,一般选择字节流。

//服务器要获得请求,就创建一个输入流ins

         InputStream ins = client.getInputStream();

         /*

          * 1,将一个字符串转换成一个流:用StringReader;列:String string ="adkljfkaeio";

                  StringReader str=newStringReader(string);

          * 2,将一个字节流转换成一个字符流对象,通过StringReader();

          * */

         //InputStream转换成Reader

            InputStreamReader insReader=new InputStreamReader(ins);

         //ins进行封装,封装成BufferedReader

         BufferedReader reader=new BufferedReader(insReader);

         String string ="adkljfkaeio";

         StringReader str=new StringReader(string);

3 Main()方法是一个静态方法,要调用方法就要创建本类的对象

4RadioGroup与RadioButton配合完成导航设置

<FrameLayout

        android:id="@+id/contaner"

        android:layout_width="match_parent"

        android:layout_height="0dip"

        android:layout_weight="1.0"/>

   

    <RadioGroup

        android:id="@+id/nev_group"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:padding="10dip"

      android:background="@drawable/home_page_bottom_bg"

      

        >

<RadioButton

            android:id="@+id/homepage"

            android:layout_width="0dip"

            android:layout_height="wrap_content"

            android:layout_weight="1.0"

            android:text="@string/nev_homepage"

            android:textSize="@dimen/nev_textsize"

            android:button="@null"

             android:gravity="center"

             android:background="@drawable/nev_radio_bg"

             android:checked="true"

            />

         <RadioButton

            android:id="@+id/pande"

            android:layout_width="0dip"

            android:layout_height="wrap_content"

            android:layout_weight="1.0"

            android:text="@string/nev_bande"

            android:textSize="@dimen/nev_textsize"

            android:button="@null"

            android:gravity="center"

            android:background="@drawable/nev_radio_bg"/>

RadioGroup的点击选择

public void onCreate(Bundle savedInstanceState) {
                               super.onCreate(savedInstanceState);
                               setContentView(R.layout.main);
 
                               // 取得 TextView、RadioGroup、RadioButton对象
                               mTextView1 = (TextView) findViewById(R.id.myTextView);
                               mRadioGroup1 = (RadioGroup) findViewById(R.id.myRadioGroup);
                               mRadio1 = (RadioButton) findViewById(R.id.myRadioButton1);
                               mRadio2 = (RadioButton) findViewById(R.id.myRadioButton2);
 
                               // RadioGroup用OnCheckedChangeListener来运行
                               mRadioGroup1.setOnCheckedChangeListener(mChangeRadio);
               }
 
               private RadioGroup.OnCheckedChangeListener mChangeRadio = new RadioGroup.OnCheckedChangeListener() {
                               @Override
                               public void onCheckedChanged(RadioGroup group, int checkedId) {
                                              // TODO Auto-generated method stub
                                              if (checkedId == mRadio1.getId()) {
                                                             // 把mRadio1的内容传到mTextView1
                                                             mTextView1.setText(mRadio1.getText());
                                              } else if (checkedId == mRadio2.getId()) {
                                                             // 把mRadio2的内容传到mTextView1
                                                             mTextView1.setText(mRadio2.getText());
                                              }
                               }
               };

 

4 设置不同手机的文子大小  

1,建一个values-480x320的文件夹 然后配置dimens.xml文件中的<dimen name=”nev_textsize”>15sp</dimen>     就使得在480x320的手机上文字大小就是15sp了

5控件与控件

距离设置margintop(控件与控件)padding(控件与文本)\

 

 

6 5-28 页面跳转

 Handler handler = new Handler();
handler.postDelayed(new Runnable() {
// @Override
public void run() {
Intent intent = new Intent(loginpage.this,MainActivity.class);
loginpage.this.startActivity(intent);
loginpage.this.finish();
}
},3000);

注:MainActivity必须在AdroidMainfest注册

如:<activity android:name=".MainActivity"></activity>

数据传递  Fragment<-->Activaity 

 

去--》   Intent intent = newIntent(activity,Scan_OkActivity.class);

                 ScanInfoinfo=new ScanInfo();

                 info.setData_ok(data_ok);

                 info.setData_unknown(data_unknown);

                 info.setData_exception(data_exception);

                 Bundlebundle=new Bundle();

                 bundle.putSerializable("info",info);

                 intent.putExtra("bundle",bundle);

                

                 startActivityForResult(intent,11);

--》接

          info=newScanInfo();

//         info=(ScanInfo)getArguments().getSerializable("info");

           info=(ScanInfo)getIntent().getBundleExtra("bundle").getSerializable("info");

           data_ok=info.getData_ok();

回《--

           publicvoid onActivityResult(int requestCode, int resultCode, Intent data2) {

           if(resultCode== activity.RESULT_OK&&requestCode==11){ //判断回调 

                 Bundlebundle = data2.getExtras();

                 ScanInfoinfo1=new ScanInfo();

                

                 info1=(ScanInfo)data2.getBundleExtra("bundle").getSerializable("info1");

                 data_ok=info1.getData_ok();

                 data_unknown=info1.getData_unknown();

                 data_exception=info1.getData_exception();

                

           }

      }

Activity与Activity简单传递

发送

 intent.putExtra("testIntent""123");  

接受

Intent intent=getIntent();

String id=intent.getStringExtra("testIntent");

或者

String id=getIntent().getStringExtra("testIntent");

Fragment与Fragemt之间数据传递

发送-->

1.      Fragment2 fragment = new Fragment2();  

2.          Bundle args = new Bundle();  

3.         args.putString("param", text);  

4.          fragment.setArguments(args); 

5.      接收<--

 if (getArguments() != null) {  

 String mParam1 = getArguments().getString("param"); 

}

 

a、保存数据          

 
//
暂停:onStart()->onResume()->onPause()    
    @Override       
    protected void onPause(){          
        super.onPause();    
        Log.e("Lifecycle_Activity1","onPause()");    
            
        //
把数据保存到类似于Session之类的存储集合里面    
        SharedPreferences.EditorsaveData = getPreferences("userType", Context.MODE_PRIVATE).edit();    
        saveData.putString("value",et_string.getText().toString());    
        saveData.commit();    
    }  
 

 b、提取数据         

 
//
重启:onStart()->onResume()    
    @Override       
    protected void onResume(){         
        super.onResume();    
        Log.e("Lifecycle_Activity1","onResume()");    
            
        //
从共享数据存储对象中获取所需的数据    
        SharedPreferences getData =getPreferences("userType", Context.MODE_PRIVATE);    
        String value =getData.getString("value", null);    
        if(value != null){    
            et_string.setText(value);    
        }    
    } 

Handler 的多线程

     http://blog.sina.com.cn/s/blog_6afeac500100y14t.html

public classchapter8_4 extends Activity {

    
private String TAG = "chapter8_3";
    
private Button btnEnd;
    
private TextView labelTimer;
    
private Thread clockThread;
    
private boolean isRunning = true;
    
private Handler handler;
    @Override
    
public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnEnd = (Button)findViewById(R.id.btnEnd);
        btnEnd.setOnClickListener(
new OnClickListener(){
            @Override
            
public voidonClick(View v) {
                isRunning= 
false;
            }
        });
        handler = 
new Handler(){
            @Override
            
public voidhandleMessage(Message msg) {
                switch(msg.what) {
            
case 0:
            labelTimer.setText(
"逝去了 " +msg.obj + "秒");
                }
            }
        };
        labelTimer = (TextView)findViewById(R.id.labelTimer);
        clockThread = 
new Thread(new Runnable(){
            @Override
            
public voidrun() {
                
int timer = 0;
                
while (isRunning){
                    try{
                Thread.currentThread().sleep(
1000);

 timer++;
Message msg = 
new Message();
msg.obj = 
timer;
msg.what = 
0

handler.sendMessage(msg);
                               }
                }
            }
        });
        clockThread.start();

private HandlerresultHandler = new Handler() {

        @Override

        public void handleMessage(Message msg) {

            String result = "";

            if(msg !=null && msg.obj !=null){

                result = msg.obj.toString();

            }

            System.out.println("服务器返回结果:"+result);

           

            if(listener !=null){

                listener.onResult(result);

            }

        }

    };
    }

Theadthead= new Runnable() {
            @Override
            public voidrun() {
Message msg = resultHandler.obtainMessage();

            msg.obj = result;

resultHandler.sendMessage(msg);

}

});

75-28  SharedPreferences详解

我们在开发软件的时候,常需要向用户提供软件参数设置功能,Android平台给我们提供了一个SharedPreferences类,它是一个轻量级应用程序内部轻量级的存储方案,特别适合用于保存软件配置参数,比如boolean,int,float,long,String等数据.使用SharedPreferences保存数据,其实质是采用了xml文件存放数据,路径为:/data/data/<package name>/shared_prefs.

获取SharedPreferences的两种方式:

1 调用Context对象的getSharedPreferences()方法

2 调用Activity对象的getPreferences()方法

两种方式的区别:

调用Context对象的getSharedPreferences()方法获得的SharedPreferences对象可以被同一应用程序下的其他组件共享.

调用Activity对象的getPreferences()方法获得的SharedPreferences对象只能在该Activity中使用.

 

SharedPreferences的四种操作模式:

Context.MODE_PRIVATE

Context.MODE_APPEND

Context.MODE_WORLD_READABLE

Context.MODE_WORLD_WRITEABLE

 

Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容

Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.

Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.

MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.

MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入.

将数据保存至SharedPreferences:

SharedPreferencespreferences=getSharedPreferences("user",Context.MODE_PRIVATE);

Editor editor=preferences.edit();

String name="xixi";

String age="22";

editor.putString("name",name);

editor.putString("age", age);

editor.commit();

 

从SharedPreferences获取数据:

SharedPreferencespreferences=getSharedPreferences("user", Context.MODE_PRIVATE);

Stringname=preferences.getString("name", "defaultname");

Stringage=preferences.getString("age", "0");

86-11随机生成字符串

public static String getRandomKHDH() throws IOException,JSONException { // length表示生成字符串的长度

                   String base= "abcdefghijklmnopqrstuvwxyz0123456789";

                   Randomrandom = new Random();

                   StringBuffersb = new StringBuffer();

                   for (int i =0; i < 8; i++) {

                            intnumber = random.nextInt(base.length());

                            sb.append(base.charAt(number));

                   }

                   returnsb.toString();

         }

96-11检验网络连接并toast提示

/**
 * 检验网络连接 并toast提示
 * 
 * @return
 */
public static boolean note_Intent2(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = con.getActiveNetworkInfo();
if (networkinfo == null || !networkinfo.isAvailable()) {
// 当前网络不可用
Toast.makeText(context.getApplicationContext(), "请先连接Internet!",
Toast.LENGTH_SHORT).show();
return false;
}
boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting();
if (!wifi) { // 提示使用wifi
Toast.makeText(context.getApplicationContext(), "建议您使用WIFI以减少流量!",
Toast.LENGTH_SHORT).show();
}
return true;

}

/**
 * 解析 服务器 返回的带特殊符号分割的数据 (两层封装解析)
 * 
 * @param str
 * @return
 */
public static ArrayList<String[]> analysisStringTwo(String str) {
ArrayList<String[]> list = new ArrayList<String[]>();

String[] strOne = str.split("﹌");
for (int i = 0; i < strOne.length; i++) {
String[] StrTwo = strOne[i].split("§");

list.add(StrTwo);
}

return list;
}

/**
 * 验证是否为合法手机号码
 * 
 * @param mobiles
 * @return
 */
public static boolean isMobileNO(String mobiles) {
Pattern p = Pattern.compile("^(13|15|18) \\d{9}$");
Matcher m = p.matcher(mobiles);
return m.matches();
}

/**
 * 获取系统当前时间
 * 
 * @return
 */
public static String getTime() {
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String date = sDateFormat.format(new java.util.Date());
return date;
}

/**
 * 异步加载图片类
 */
public static void LoadImage(ImageView img, String path, Context context) {
// 异步加载图片资源
MyAsyncImage async = new MyAsyncImage(img, context);
// 执行异步加载,并把图片的路径传送过去
async.execute(path);
}

/**
 * 异步加载图片类
 */
public static void LoadImage(ImageView img, String path) {
// 异步加载图片资源
MyAsyncImage async = new MyAsyncImage(img);
// 执行异步加载,并把图片的路径传送过去
async.execute(path);
}

/**
 * Http GET请求获取InputStream对象
 */
public static InputStream getImageStream(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setRequestMethod("GET");
// System.out.println("有数据?");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// System.out.println("有");
return conn.getInputStream();
}
// System.out.println("没有");
return null;
}

/**
 * 获取 Bitmap 格式的图片
 * 
 * @param imagePate
 *            图片路径
 * @return Bitmap
 */
public static Bitmap getImageBitmap(String imagePate) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap bm = BitmapFactory.decodeFile(imagePate, options);
return bm;
}

 

 

 

 

android:screenOrientation="landscape"是限制此页面横屏显示,  
  
android:screenOrientation="portrait"是限制此页面数竖屏显示。

 

 

 

 

//拨打电话

         Intent intent=newIntent(Intent.ACTION_CALL,Uri.parse("tel:02828286411"));

           context.startActivity(intent);

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

10  7-28Activity完整的生命周期

Activity的作用:
起显示作用,他是用来和用户交互的。也是一个view的容器


1 完整的生命周期:
onCreate() --> onStart() --> onResume() activiyt已经正常显示
点击回退键
onPause() --> onStop() --> onDetroy()


2 可视的生命周期
onCreate() --> onStart() --> onResume() activiyt已经正常显示
打开一个activity。该activity完全覆盖上一个activity
onPause() ---> onStop()
点击回退键
onRestart() --> onStart() ---> onResume()
点击回退键
onPause() --> onStop() --> onDetroy()


3 android:theme="@android:style/Theme.Dialog"
就可以把activity变成对话框的效果
onCreate() --> onStart() --> onResume() activiyt已经正常显示
打开一个activity。该activity没有完全覆盖上一个activity
onPause()
点击回退键
onResume()

 

EditText  让其失去焦点,有焦点但不弹出输入键,内容改变监听

<EditText

 android:focusable="false"/>

   但让其失去焦点但可以输入则  在其父控件加上android:focusable="true" android:focusableInTouchMode="true"

 <LinearLayout

           android:layout_width="match_parent"

           android:layout_height="wrap_content"

           android:orientation="horizontal"

            android:focusable="true"

           android:focusableInTouchMode="true">

            <Spinner

              android:id="@+id/ciyt04"

              android:layout_width="0dip"

              android:layout_weight="1.3"

               android:layout_height="wrap_content"      

              android:entries="@array/condition4"

              android:background="@drawable/spinter_bac_img"

               />

            <TextView

               android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="金额:"

               android:layout_marginLeft="8dip"/>

            <EditText

               android:id="@+id/money"

               android:layout_width="0dip"

                android:layout_height="32dip"

               android:layout_weight="2.0"

               android:background="@drawable/edit_selector"

               android:padding="3dip"

               android:textColor="@color/login_text_color"

                android:textSize="@dimen/textSize"

               android:maxLines="1"

               android:inputType="numberDecimal"

                />

        </LinearLayout>

设置可以编辑和不可编辑状态

xml中设置Android:editable="false"

然后尝试使用editText.setFocusable(false);editText.setEnabled(false);设置不可编辑状态;editText.setFocusable(true); editText.setEnabled(true);设置可编辑状态。

发现在editText.setFocusable(false);editText.setEnabled(false);时不可编辑,但是editText.setFocusable(true); editText.setEnabled(true);也是不可编辑的,感觉这个时候EditText控件高亮度了,但是没有焦点

3、最后尝试使用editText.setFocusable(false);editText.setFocusableInTouchMode(false);设置不可编辑状态;editText.setFocusableInTouchMode(true);editText.setFocusable(true);editText.requestFocus();设置可编辑状态

(有焦点但不显示输入盘)

Androidmianfest.xml中加<Activity  android:windowSoftInputMode="stateHidden|adjustResize"

EditeView的内容改变监听) .

et=(EditText) findViewById(R.id.et);

et.addTextChangedListener(watcher);

TextWatcher watcher=new TextWatcher() {

       

        @Override

        public void onTextChanged(CharSequence s, int start,int before, int count) {

            System.out.println("onTextChanged   s="+s+" start="+start+" before="+before+" count="+count);

           

        }

       

        @Override

        public void beforeTextChanged(CharSequence s, int start,int count,

                int after) {

            System.out.println("beforeTextChanged   s="+s+" start="+start+" count="+count);

           

           

        }

       

        @Override

        public void afterTextChanged(Editable s) {

            System.out.println("afterTextChanged   s="+s);

           

        }

    };

(光标显示)

光标移到编辑框最后一行

 tvNum.setSelection(tvNum.getText().length());

EditText自定义输入内容

其实有两种方案:

1.xml:EditText设置属性----
Android:digis="ABCDE555555&&&&&"
ABCDE555555&&&&&"
是你的限制规则。
例如:android:digits="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
规则是只能输入英文字母(小写)和数字

2.EditText,TextView只能输入字母加数字,可在View空间后面加上监听器,如下

tvPassword.addTextChangedListener(newTextWatcher() {

@Override

public voidonTextChanged(CharSequence s, int start, int before, int count) {

}

 

@Override

public voidbeforeTextChanged(CharSequence s, int start, int count,

int after) {

}

@Override

public voidafterTextChanged(Editable edt) {

try {

String temp = edt.toString();

String tem =temp.substring(temp.length()-1, temp.length());

char[] temC =tem.toCharArray();

int mid = temC[0];

if(mid>=48&&mid<=57){//数字

return;

}

if(mid>=65&&mid<=90){//大写字母

return;

}

if(mid>97&&mid<=122){//小写字母

return;

}

edt.delete(temp.length()-1,temp.length());

} catch (Exception e) {

// TODO: handle exception

}

}

});

1.EditText,TextView只能输入两位小数,先在XML文件里加上输入性:android:numeric="integer"//设置只能输入整数,如果是小数则是:decimal

然后在View空间后面加上监听器,如下

EditText txtInput = (EditText)findViewById(R.id.txtInput);

txtInput.addTextChangedListener(newTextWatcher()

{

public voidafterTextChanged(Editable edt)

{

String temp = edt.toString();

int posDot =temp.indexOf(".");

if (posDot <= 0) return;

if (temp.length() - posDot - 1> 2)

{

edt.delete(posDot + 3, posDot +4);

}

}

public voidbeforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

public voidonTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

});

android:layout_gravity="center_vertical"//设置控件显示的位置:默认top,这里居中显示,还有bottom

android:hint="请输入数字!"//设置显示在空间上的提示信息

android:numeric="integer"//设置只能输入整数,如果是小数则是:decimal

android:maxLength="8" //限制输入长度为8

设置光标的颜色    android:textCursorDrawable="@null"

修改RadioButton的图片

                 Resources res = TabTest.this.getResources();

                 Drawable myImage =res.getDrawable(R.drawable.home);

                myImage.setBounds(1, 1, 100, 100);

                button.setCompoundDrawables(null, myImage, null, null);

 

 

 MyEclipse修改项目名称后,部署到tomcat问题   http://blog.csdn.net/dr_lf/article/details/7533563

 

要在eclipse里面改下,光把项目重命名是不成的。

工程名--右键--Properties--MyEclipse--Web--

把Web Context-root的名字给改了

 

 

ExpandableListView

 

但值得简单说下的是 android:cacheColorHint="#00000000",这个设置可以去除拖动view时背景变成黑色的效果

 

android:listSelector="#00000000" ,可以去除选中时的黄色底色

 

 

Style的Diogl样式

 

 <!-- 透明 无边框 对话框 -->

    <stylename="Translucent_NoTitle"parent="android:style/Theme.Dialog">

        <itemname="android:windowNoTitle">true</item>//对话框无标题

        <itemname="android:windowBackground">@android:color/transparent</item>//此对话框的背景

         <itemname="android:windowFrame">@null</item>Dialog的windowFrame框为无

        <itemname="android:windowIsFloating">true</item>//对话框是否浮动在Activity上

        <itemname="android:windowContentOverlay">@null</item>//对话框是否有遮盖

        <itemname="android:backgroundDimEnabled">false</item>: 背景是否模糊显示

    </style>

 

字符串剪切

 

                        JSONObjectitem =new JSONObject(message);

                 Stringabc=item.getString("description");

                   Utils.orderid=abc.substring(0,abc.indexOf("$"));

                 Stringaaa=abc.substring(abc.indexOf("$")+1);

                 Utils.description=aaa.substring(0,aaa.indexOf("$"));

 

requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏,必须加到setContext()之前

 

 

数据传递同上  Fragment<-->Activaity 

 

去--》   Intent intent = newIntent(activity,Scan_OkActivity.class);

                 ScanInfo info=newScanInfo();

                 info.setData_ok(data_ok);

                 info.setData_unknown(data_unknown);

                 info.setData_exception(data_exception);

                 Bundle bundle=newBundle();

                 bundle.putSerializable("info",info);

                 intent.putExtra("bundle",bundle);

                

                 startActivityForResult(intent,11);

--》接

          info=new ScanInfo();

///         info=(ScanInfo)getArguments().getSerializable("info");

           info=(ScanInfo)getIntent().getBundleExtra("bundle").getSerializable("info");

           data_ok=info.getData_ok();

回《--

           public voidonActivityResult(int requestCode, int resultCode, Intent data2) {

           if(resultCode ==activity.RESULT_OK&&requestCode==11){ //判断回调 

                 Bundle bundle =data2.getExtras();

                 ScanInfo info1=newScanInfo();

                

                 info1=(ScanInfo)data2.getBundleExtra("bundle").getSerializable("info1");

                 data_ok=info1.getData_ok();

                 data_unknown=info1.getData_unknown();

                 data_exception=info1.getData_exception();

                

           }

      }

Activity跳转后数据返回

private void jump2Activiy2() {

02. 

03.Bundle bundle = new Bundle();

04.bundle.putString("strSex", strSex);

05.bundle.putDouble("douHeight", douHeight);

06.Intent intent = new Intent();

07.intent.setClass(MainActivity.this, TwoActivity.class);

08.intent.putExtra("bundle", bundle);

09.startActivityForResult(intent, 0);

10.}

 

 

 

private void jump2Activiy1() {

02. 

03.Intent intent2 = new Intent();

04.intent2.setClass(TwoActivity.this, MainActivity.class);

05.Bundle bundle2 = new Bundle();

06.bundle2.putString("strResult", strResult);

07.intent2.putExtra("bundle2", bundle2);

08.setResult(0, intent2);

09.TwoActivity.this.finish();

10.}

 

 

 

 

@Override

02.protected void onActivityResult(int requestCode, int resultCode, Intentdata) {

03.if (0 == requestCode) {

04.if (0 == resultCode) {

05. 

06.Bundle bundle2 = data.getBundleExtra("bundle2");

07.String strFromAct2 = bundle2.getString("strResult");

08.txtFromAct2.setText(strFromAct2);

09.}

10. 

11.}

12.super.onActivityResult(requestCode,resultCode, data);

13.}

 

Spinner的应用

Spinner abc=(Spinner) findViewById(R.id.ciyt);

           String text02=(String)abc.getSelectedItem();

final String arr[]=new String[]{ "1","2", "3" };

         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arr);

         spinner.setAdapter(arrayAdapter);

 spinner.setSelection(2,true);//设置spinner被选择的位置

         spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 

             

                @Override 

                publicvoid onItemSelected(AdapterView<?> parent, View view, 

                        int position,long id) { 

                    Spinner spinner=(Spinner)parent; 

                    String getStr=(String)spinner.getItemAtPosition(position); 

                   

                    SharedPreferences preference = activity.getSharedPreferences(

                         "userType", Context.MODE_PRIVATE);

                 Editoreditor = preference.edit();

                 editor.putString("usertype", getStr);

                

                 editor.commit();// 把数据提交会文件

                

                }

 

                @Override

                publicvoid onNothingSelected(AdapterView<?> parent) {

                    // TODO Auto-generated method stub

                   

                }

 

            });

//给字加下划线

//         l_register.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

//         l_findpwd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

//         settexttype();//设置字体

设置整体无标题和无信息栏

 android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen"

设置信息栏的去掉

this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏

 

获取随机数字                        

Random random = newRandom();

longlon =random.nextInt(10000);

Android4.0以上AlertDialog在触摸对话框边缘外部,对话框消失

可以设置这么一条属性,当然必须先AlertDialog.Builder.create()之后才能调用这两个方法

方法一:

setCanceledOnTouchOutside(false);调用这个方法时,按对话框以外的地方不起作用。按返回键还起作用

方法二:

setCanceleable(false);调用这个方法时,按对话框以外的地方不起作用。按返回键也不起作用

listView的属性

<ListView

        android:id="@+id/list_driver_negotiateroom"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:divider="@color/text_gray"

        android:scrollbars="none">

    </ListView>

listview如何显示最后一行数据

listView.setSelection(adapter.getCount());

listview去掉分割线

设置android:divider="@null" 

android:divider="#00000000"

#00000000后面两个零表示透明

.setDividerHeight(0)高度设为0

返回键的监听

 /**

     *监听Back键按下事件,方法1:

     *注意:

     *super.onBackPressed()会自动调用finish()方法,关闭

     *当前Activity.

     *若要屏蔽Back键盘,注释该行代码即可

     */ 

    @Override 

    publicvoid onBackPressed() { 

        super.onBackPressed(); 

        System.out.println("按下了back  onBackPressed()");        

    } 

       

       

   /**

    *监听Back键按下事件,方法2:

    *注意:

    *返回值表示:是否能完全处理该事件

    *在此处返回false,所以会继续传播该事件.

    *在具体项目中此处的返回值视情况而定.

    */ 

    @Override 

    publicboolean onKeyDown(int keyCode, KeyEvent event) { 

        if((keyCode == KeyEvent.KEYCODE_BACK)) { 

             System.out.println("按下了back   onKeyDown()");  

             returnfalse; 

        }else{ 

            returnsuper.onKeyDown(keyCode, event); 

        } 

           

    } 

       

    @Override 

    protectedvoid onDestroy() { 

        super.onDestroy(); 

        System.out.println("执行 onDestroy()"); 

    }    

获取sdcar的路径

   public static String getSDPath() {

              File sdDir = null;

              boolean sdCardExist =Environment.getExternalStorageState().equals(

                            android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在

              if (sdCardExist) {

                     sdDir =Environment.getExternalStorageDirectory();//获取跟目录

              }

              return sdDir.toString();

 

       }

 

获取Bitmap格式的图片

   public static Bitmap getImageBitmap(StringimagePate) {

              BitmapFactory.Options options =new BitmapFactory.Options();

              options.inSampleSize = 5;///图片宽高都为原来的五分之一,即图片为原来的二十五分之一

              Bitmap bm =BitmapFactory.decodeFile(imagePate, options);

              return bm;

       }

BitMap  获取本地BitMap图片对象

第一种

1.  //得到Resources对象  

2.  Resources r = this.getContext().getResources();  

3.  //以数据流的方式读取资源  

4.  Inputstream is = r.openRawResource(R.drawable.my_background_image);  

5.  BitmapDrawable  bmpDraw = new BitmapDrawable(is);  

6.  Bitmap bmp = bmpDraw.getBitmap();  

第二种

1.  InputStream is = getResources().openRawResource(R.drawable.icon);    

2.           Bitmap mBitmap = BitmapFactory.decodeStream(is);    

3.           Paint mPaint = new Paint();    

4.           canvas.drawBitmap(mBitmap, 4040, mPaint);  

ivInfo.setImageBitmapmBitmap;

获取本地时间

  SimpleDateFormat dataformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

         String mTime=dataformat.format(new Date());

 

简析分解数据

    public static ArrayList<String[]>analysisStringTwo(String str) {

              ArrayList<String[]> list =new ArrayList<String[]>();

 

              String[] strOne = str.split("");

              for (int i = 0; i <strOne.length; i++) {

                     String[] StrTwo =strOne[i].split("§");

 

                     list.add(StrTwo);

              }

 

              return list;

       }

 检验网络连接 并toast提示     

  public static boolean note_Intent(Contextcontext) {

       ConnectivityManager con = (ConnectivityManager) context

              .getSystemService(Context.CONNECTIVITY_SERVICE);

       NetworkInfo networkinfo = con.getActiveNetworkInfo();

       if (networkinfo == null || !networkinfo.isAvailable()) {

 

           return false;

       }

       return true;

 

    }

 

 MyEclipse修改项目名称后,部署到tomcat问题   http://blog.csdn.net/dr_lf/article/details/7533563

 

要在eclipse里面改下,光把项目重命名是不成的。

工程名--右键--Properties--MyEclipse--Web--

把WebContext-root的名字给改了

修改RadioButton的图片

 Resources res = TabTest.this.getResources();

 Drawable myImage =res.getDrawable(R.drawable.home);

 myImage.setBounds(1, 1, 100, 100);

 button.setCompoundDrawables(null, myImage,null, null);

//给字加下划线

//     l_register.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

//     l_findpwd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

//     settexttype();//设置字体

字符串剪切

 

                        JSONObject item =newJSONObject(message);

           String abc=item.getString("description");

              Utils.orderid=abc.substring(0, abc.indexOf("$"));

           String aaa=abc.substring(abc.indexOf("$")+1);

           Utils.description=aaa.substring(0,aaa.indexOf("$"));

JSON解析

JSONObject item =new JSONObject(message);

设置ListView的高度

private void setListHight(){

      if(mListView ==null) return;

//     ListAdapter listAdapter =listView.getAdapter();

       if (adapter ==null) {

           // pre-condition

           return;

       }

       //设置ListView的高度

       int totalHeight = 0;

       for (inti = 0; i < adapter.getCount(); i++) {

           View listItem = adapter.getView(i, null,mListView);

           listItem.measure(0, 0);

           totalHeight += listItem.getMeasuredHeight();

       }

       ViewGroup.LayoutParams params =mListView.getLayoutParams();

       params.height =totalHeight + (mListView.getDividerHeight()* (adapter.getCount() - 1));

       mListView.setLayoutParams(params);

   }

 

设置地图缩放的大小

maxZoomLevel = mBaiduMap.getMaxZoomLevel();

mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(maxZoomLevel));

得到屏幕的高宽

WindowManager wm = (WindowManager)getSystemService(context.WINDOW_SERVICE);

              intwidth = wm.getDefaultDisplay().getWidth();

              int height =wm.getDefaultDisplay().getHeight();

得到屏幕的像素,以便调整控件的大小

//要调整的控件

RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout);

    //new一个DissplayMetrics对象  

 DisplayMetricsoutMetrics = new DisplayMetrics();

//将屏幕的像素等放进DissplayMetrics对象里

context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

//得到一个LayoutParams 参数对象

       FrameLayout.LayoutParams params = newFrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);

//将参数对象的宽度设为屏幕像素-40像素

        params.width= outMetrics.widthPixels - 40;

//将参数对象赋值给控件

       layout.setLayoutParams(params);

设置Dialog显示位置

//获取dialog窗口对象

      Window mwindow = dialog.getWindow();

      LayoutParams attributes =mwindow.getAttributes();//获取dialog的窗口特征,属性

//    attributes.alpha=0.35f;// 透明度的范围为:0.0f-1.0f;0.0f表示完全透明,1.0f表示完全不透明(系统默认的就是这个)

      //设置对话框在屏幕的底部显示,当然还有上下左右,任意位置  

      //mWindow.setGravity(Gravity.LEFT);  

//    mWindow.setGravity(Gravity.BOTTOM);  

//    这里是设置偏移量,这里的x,y并不是相对于屏幕的绝对坐标,而是相对于对话框在中心位置(默认的对话框一般显示在屏幕的中心)而言的 

      attributes.x=-30;

      attributes.y=-150;

//    设置Window的属性  

      mwindow.setAttributes(attributes); 

      dialog.show();

设置按钮点击改变背景图片

<?xmlversion="1.0"encoding="utf-8"?>

<selectorxmlns:android="http://schemas.android.com/apk/res/android">

 

    <itemandroid:drawable="@drawable/task_p"android:state_checked="true"></item>

    <itemandroid:drawable="@drawable/task"android:state_checked="false"></item>

 

</selector>

下载显示图片

ImageView picture_title=(ImageView) convertView.findViewById(R.id.picture_title);

ImageLoader.getInstance().displayImage(data.get(position).get("URL"),

              picture_title);

 

(横屏或竖屏)Android强制设置横屏或竖屏

来源   http://2960629.blog.51cto.com/2950629/701227

全屏 requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题

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

 WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏

横屏

按照下面代码示例修改Activity的onResume方法

@Override

protected voidonResume() {

 /**

  * 设置为横屏

  */

 if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

 }

 super.onResume();

}

或者在配置文件中对Activity节点添加android:screenOrientation属性(landscape是横向,portrait是纵向)

android:launchMode="singleTask"android:screenOrientation="portrait">

要设置成竖屏设置成SCREEN_ORIENTATION_PORTRAIT

常亮

view.setKeepScreenOn(true)

 

 

SQL语句(增删改查)

  INSERT INTO tab_comp VALUES(item1, price1, qty1),
(item2, price2, qty2),
(item3, price3, qty3);

 

INSERT INTO tab_comp(item1, price1, qty1) SELECT item1, price1,qty1 FROM tab_cc;

 

删  DELETE FROM 表名称 WHERE 列名称 = 值

DELETE FROM tb_move_data WHEREid >100

 

改  update tb_move_station set s_spare1 ='2025-2-2', s_lon ='130.22222', s_lat ='30.0000' where s_code = '8888'

 

查 select s_code as code,s_name as name fromtb_move_station where s_code = '"+userName+"'"

 

CREATE TABLE users(idINT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), ageINT);

4INSERTINTO users(NAME, age) VALUES('孤傲苍狼',27);

5INSERTINTO users(NAME, age) VALUES('白虎神皇',27);

 

Web ProjectWeb Service Project和Java Project的区别?

1、当你是web应用时,比如说要建个网站,需要发布到服务器时,应该要建Web Project
2、当你是做分布式系统时,也就是你做的只是一个服务,对外发布也只是一个服务的时候,需要建立Web Services Project(不理解可以先研究下webservices)
3、当你仅仅是需要JDK来运行一些本地代码的时候,只需要建Java Project就可以啦饿

 

Dialog创建简述

1android系统自带的Dialog 

http://blog.csdn.net/z1395129433/article/details/21016601/

通过new一个AlertDialog.Builder对象,构造一个具有TitlesetTitle)、messagesetMessage)和确认按钮PositiveButtonsetPositiveButton)的对话窗口。

其中方法的定义为:

setTitle设置标题
 setIcon
设置对话框图标
 setMessage
简单消息框
 setItems
设置要在对话框中显示的项目列表
 setView
设置自定义的对话框样式
 setSingleChoiceItems
设置对话框显示一个单选框
 setMultiChoiceItems
设置对话框显示一系列的复选框
 setPositiveButton
设置对话框显示一个确定的按钮
 setNeutralButton
设置对话框显示一个退出按钮
 setNegativeButton
设置对话框显示一个取消按钮
 create
创建一个AlertDialog对话框
 show
显示对话框

 

  1显示单个按钮

AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)

                .setTitle("提示信息")

                .setMessage("无法连接到摄像头,请确保手机已经连接到摄像头所在的wifi热点")

                .setNegativeButton("知道了",

                        new DialogInterface.OnClickListener() {

 

                            @Override

                            publicvoid onClick(DialogInterface dialog,

                                    int which) {

                            }

                        }).create();

        dialog.setCanceledOnTouchOutside(false);

        dialog.show();

 

2 两个按钮

  1. new AlertDialog.Builder(activity).setTitle("离开")  
  2.         .setMessage("真要啊").setNegativeButton("取消", new DialogInterface.OnClickListener() {  
  3.               +
  4.             @Override  
  5.             public void onClick(DialogInterface dialog, int which) {  
  6.                 // TODO Auto-generated method stub  
  7.                   
  8.             }  
  9.         }).setPositiveButton("确定", new DialogInterface.OnClickListener(){  
  10.             @Override  
  11.             public void onClick(DialogInterface dialog, int which) {  
  12.                 // TODO Auto-generated method stub  
  13.                 finish();  
  14.             }  
  15.         }).show();  

2 自定义Dialog

  先创建一个类(MyDialog)继承 Dialog ,创建空的构造函数和含有(Activity context,inttheme等参数)  然后重写OnCteat();方法 ,setContentView(R.Layout.**)将布局View放进去,在改类中就可以对按键进行监听,也可以写个方法,让Activity 对象来重写过去。

 

maplocationDialog = new MapLocationDialog(context, R.style.Translucent_NoTitle){

 

            @Override

            public void locationTimeClick(String time) {

                if (maplocationDialog !=null && maplocationDialog.isShowing()) {

                    maplocationDialog.dismiss();

                }

                ((MainPage)getActivity()).openService(time);

                location_start.setText("定位/");

                LoginInfo.locationState =location_start.getText().toString();

            }

           

        };

       

        maplocationDialog.show();

 

 

public class MapLocationDialog extends Dialog{

    private Activitycontext;

    private EditTextlocationtime;

    /**

     * @param context

     */

    public MapLocationDialog(Activity context) {

        super(context);

        this.context=context;

    }

    public MapLocationDialog(Activity context,int theme) {

        super(context,theme);

        this.context=context;

    }

    @Override

    protected void onCreate(Bundle savedInstanceState) {

       

        super.onCreate(savedInstanceState);

        setContentView(R.layout.maplocationdialog);

        DisplayMetricsoutMetrics = new DisplayMetrics();

       context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

       View view = findViewById(R.id.maplayout);

       FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(-1,-2);

       params.width = outMetrics.widthPixels - 40;

       view.setLayoutParams(params);

        init();

    }

    private void init(){

        locationtime=(EditText) findViewById(R.id.locationtime);

        findViewById(R.id.conmit).setOnClickListener(new View.OnClickListener() {

           

            @Override

            public void onClick(View v) {

                Stringtime=locationtime.getText().toString().trim();

                if(time==null||"".equals(time)){

                    Toast.makeText(context,"请输入定位间隔时间", 1500).show();

                    return;

                }

                locationTimeClick(time);

               

            }

        });

      findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {

           

            @Override

            public void onClick(View v) {

                dismiss();

               

            }

        });

    }

   

    public void locationTimeClick(String time){

       

    }

}

 

获取当前时间(time)

SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

Stringdate=sDateFormat.format(new Date()) ;

 

 

动态设置控件居中

1. FrameLayout下动态设置子控件居中,动态用JAVA代码要这样实现:

FrameLayout.LayoutParamslytp =new FrameLayout.LayoutParams(80,LayoutParams.WRAP_CONTENT);

lytp .gravity =Gravity.CENTER;

btn.setLayoutParams(lytp);

2. RelativeLayout下动态设置子控件居中:

RelativeLayout.LayoutParamslp=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);

lp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);

btn1.setLayoutParams(lp);

 

progressbar设置颜色

 android:indeterminateDrawable="@drawable/progressbar"  

<?xmlversion="1.0"encoding="utf-8"?> 

<animated-rotate 

   xmlns:android="http://schemas.android.com/apk/res/android" 

 android:pivotX="50%"android:pivotY="50%"     

 android:fromDegrees="0"   

 android:toDegrees="360"> 

     

    <shape  

     android:shape="ring"  

     android:innerRadiusRatio="3"   

  android:thicknessRatio="8"  

  android:useLevel="false">   

  <gradient  

   android:type="sweep"  

   android:useLevel="false"   

   android:startColor="#6BD3FF"          

    android:centerColor="#FF7121"   

   android:centerY="0.50"  

   android:endColor="#FFFF00"/>   

 </shape>   

     

</animated-rotate>

 

设置水平进度条的颜色:

1. <LinearLayout android:gravity="center"  

2.     android:orientation="horizontal"  

3.     android:padding="10dp"   

4.     android:layout_width="fill_parent"  

5.     android:layout_height="wrap_content">  

6.     <SeekBar android:layout_gravity="center" android:id="@android:id/progress"  

7.         android:paddingLeft="8.0dip" android:paddingRight="8.0dip"  

8.         android:paddingBottom="4.0dip" android:layout_width="fill_parent"  

9.         android:layout_height="wrap_content" android:maxHeight="2.0px"  

10.        android:progressDrawable="@drawable/progressbar_drawable" android:minHeight="2.0px"  

11.         android:thumb="@drawable/seekbar_thumb" style="?android:attr/progressBarStyleHorizontal" />  

12.</LinearLayout>  


progressbar_drawable.xml
如下:

[html] view plain copy

1. <?xml version="1.0" encoding="utf-8"?>  

2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android">  

3.     <item android:id="@android:id/background">  

4.         <shape>  

5.             <corners android:radius="2.0dip" />  

6.             <gradient android:startColor="#ff000000" android:centerColor="#ff000000" android:endColor="#ff000000" android:angle="270.0" android:centerY="2.0"  />  

7.         </shape>  

8.     </item>  

9.     <item android:id="@android:id/progress">  

10.        <clip>  

11.             <shape>  

12.                <corners android:radius="2.0dip" />  

13.                 <gradient android:startColor="#ff33b5e5" android:centerColor="#ff33b5e5" android:endColor="#ff33b5e5" android:angle="270.0" android:centerY="2.0"  />  

14.            </shape>  

15.         </clip>  

16.    </item>  

17. </layer-list>  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值