Android开发的基础技能总结(1)

引言

在基础的时候很多懂东西都会去实践一遍有的时候甚至是实现不止一遍,但是在工作中有些东西用不到,久而久之就忘记了,虽然再看的时候会有印象,但总是记不扎实。虽然有些东西很简单,但是不能做到信手捏来,再简单的东西也不是自己的,所以今天把自己以前写过的基础知识整理分类一下。


网络图片请求

  • 开启子线程请求

public class MainActivity extends AppCompatActivity {
    String url = "http://picm.photophoto.cn/005/008/007/0080073258.jpg";
    ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView) findViewById(R.id.imgs);
            new Thread(){
                @Override
                public void run() {
                    try {
                    getDaraMethod();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                }
            }.start();
    }

       private void getDaraMethod() throws IOException {
        URL Url=new URL(url);
        HttpURLConnection http= (HttpURLConnection) Url.openConnection();
        InputStream is=http.getInputStream();
        bitmap= BitmapFactory.decodeStream(is);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                img.setImageBitmap(bitmap);
            }
        });

    }
  • 利用AsyncTask异步消息处理任务请求图片
public class MainActivity extends AppCompatActivity {
    String url = "http://picm.photophoto.cn/005/008/007/0080073258.jpg";
    ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView) findViewById(R.id.imgs);
        new MyAsycTask().execute();
    }


        class MyAsycTask extends AsyncTask {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        //费时的炒作
        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap    bitmap = null;
            try {
                URL Url = new URL(url);
                HttpURLConnection http = (HttpURLConnection) Url.openConnection();
                InputStream is = http.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            img.setImageBitmap(bitmap);
        }
    }
}    
  • 利用AsyncTask异步消息处理任务和Handle请求图片
public class MainActivity extends AppCompatActivity {
    String url = "http://picm.photophoto.cn/005/008/007/0080073258.jpg";
    ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView) findViewById(R.id.imgs);
        new MyTask(url,handler).execute();
    }
    Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case 1:
                Bitmap bitmap= (Bitmap) msg.obj;
                img.setImageBitmap(bitmap);
                break;
        }
    }
};
}


public class MyTask extends AsyncTask<Void,Void,Bitmap> {
    private  String mUrl;
    Handler handler;
    public MyTask(String url,Handler handler) {
        mUrl=url;
        this.handler=handler;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }



    @Override
    protected Bitmap doInBackground(Void... params) {
        Bitmap    bitmap = null;
        try {
            URL Url = new URL(mUrl);
            HttpURLConnection http = (HttpURLConnection) Url.openConnection();
            InputStream is = http.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        Message message=handler.obtainMessage();
        message.what=1;
        message.obj=bitmap;
        handler.sendMessage(message);
    }
}
  • 利用Volley 请求图片的三种方式
public class MainActivity extends Activity {
    private String url = "http://image20.it168.com/201604_800x800/2502/f4afc28a07a8a151.jpg";
    ImageView img;
    ImageLoader loader;
    NetworkImageView netimg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView) findViewById(R.id.img);
        netimg = (NetworkImageView) findViewById(R.id.netimg);
        //  -->ImageLoader
        loader = new ImageLoader(MyApplication.getQueue(), new BitmapCache());
    }

    public void onBtn(View view) {
        switch (view.getId()) {
        case R.id.btn1:
            getImageData();
            break;
        case R.id.btn2:
            getImageCache();
            break;
        case R.id.btn3:
            getImageNet();
            break;
        default:
            break;
        }
    }

    private void getImageData() {
        ImageRequest request = new ImageRequest(url, new Listener() {

            @Override
            public void onResponse(Bitmap response) {
                img.setImageBitmap(response);
            }
        }, 0, 0, Config.RGB_565, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub

            }
        });
        MyApplication.getQueue().add(request);
    }

    private void getImageCache() {
        ImageListener listener = loader.getImageListener(img,
                R.drawable.ic_launcher, R.drawable.ic_launcher);
        loader.get(url, listener);
    }

    private void getImageNet() {
        netimg.setDefaultImageResId(R.drawable.ic_launcher);
        netimg.setImageUrl(url, loader);
    }
}

public class MyApplication extends Application {
    private static RequestQueue queue;

    @Override
    public void onCreate() {
        super.onCreate();
        queue = Volley.newRequestQueue(getApplicationContext());
    }

    public static RequestQueue getQueue() {
        return queue;
    }
}

public class BitmapCache implements ImageCache {
    private LruCache cache;

    // 10M的 图片缓存空间
    private int maxSize = 10 * 1024 * 1024;

    public BitmapCache() {
        cache = new LruCache(maxSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };

    }

    @Override
    public Bitmap getBitmap(String url) {
        return cache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        cache.put(url, bitmap);
    }

}

以上的图片加载技术都是在我学习过程中用到的,可能会有些老,不过用到的话就直接用,这里我也是分享更多的是当作自己的一个笔记。在我用到的图片加载中还有Glide框架,也是当下比较流行的框架,内部不管是对线程还是缓存都做了很好的优化,帮我们做了很多的工作,用法很简单这里就不过多介绍了,想了解更多的Gilde源码的,可以访问郭霖的博客 分了4步由浅入深的讲解Glide,有兴趣的可以自己了解。


PopupWindow,PopupMenu,Menu的简单使用

  • Menu是最常见的所以这里就简单介绍用法。
    首先要在res下创建menu文件并创建main.xml布局
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android">
    "@+id/add_item"
        android:title="Add"/>
    "@+id/remove_item"
        android:title="Remove"/>

接下里分两步:加载布局,点击事件

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_item:
                Toast.makeText(this, "You clicked Add", Toast.LENGTH_SHORT).show();
                break;
            case R.id.remove_item:
                Toast.makeText(this, "You clicked Remove", Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }
  • PopupWindow,PopupMenu

menu通常是在ActionBar中在布局中的话就用到了PopupWindow,PopupMenu。如下

Android开发的基础技能总结(1)_第1张图片

首先我们也是要创建2个布局,不同的是PopupWindow创建layout布局popup.xml:

"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" >

    <Button
        android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="QQ分享" />

    <Button
        android:id="@+id/btn4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="微信分享" />

    <Button
        android:id="@+id/btn5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="微博分享" />

    <Button
        android:id="@+id/btn6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="人人分享" />

</LinearLayout>

PopupMenu属于Menu所以床架menu布局main.xml:

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

    android:id="@+id/item2"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="我顶"/>
    android:id="@+id/item1"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="我踩"/>

</menu>

具体使用代码如下:

public class MainActivity extends Activity {
    Button bt1, bt2, bt3, bt4;
    PopupWindow popupWindow;

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

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn1:
            showPopupWindon();
            break;
        case R.id.btn2:
            showPopupMenu(v);
            break;
        }
    }

    private void showPopupWindon() {
        View v = getLayoutInflater().inflate(R.layout.popup, null);
        View v1 = getLayoutInflater().inflate(R.layout.activity_main, null);
        popupWindow = new PopupWindow(v, LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);//设置焦点,通常设置为true
        popupWindow.setBackgroundDrawable(new BitmapDrawable());//点击空白处的时候让PopupWindow消失,默认是只有点击了才会消失
        popupWindow.showAtLocation(v1, Gravity.BOTTOM, 0, 0);//设置在父布局显示的位置和偏移量
        bt1 = (Button) v.findViewById(R.id.btn3);
        bt2 = (Button) v.findViewById(R.id.btn4);
        bt3 = (Button) v.findViewById(R.id.btn5);
        bt4 = (Button) v.findViewById(R.id.btn6);
        bt1.setOnClickListener(popup);
        bt2.setOnClickListener(popup);
        bt3.setOnClickListener(popup);
        bt4.setOnClickListener(popup);

    }

    private void showPopupMenu(View view) {
        PopupMenu menu = new PopupMenu(MainActivity.this, view);
        getMenuInflater().inflate(R.menu.main, menu.getMenu());
        menu.show();
        menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                case R.id.item1:
                    Toast.makeText(MainActivity.this, "顶成功", Toast.LENGTH_SHORT)
                            .show();
                    break;

                case R.id.item2:
                    Toast.makeText(MainActivity.this, "踩成功", Toast.LENGTH_SHORT)
                            .show();

                    break;
                }
                return false;
            }
        });
    }

    OnClickListener popup = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btn3:
                Toast.makeText(MainActivity.this, "QQ分享成功", Toast.LENGTH_LONG)
                        .show();
                break;

            case R.id.btn4:
                Toast.makeText(MainActivity.this, "微信分享成功", Toast.LENGTH_LONG)
                        .show();

                break;
            case R.id.btn5:
                Toast.makeText(MainActivity.this, "微博分享成功", Toast.LENGTH_LONG)
                        .show();

                break;
            case R.id.btn6:
                Toast.makeText(MainActivity.this, "人人分享成功", Toast.LENGTH_LONG)
                        .show();

                break;
            }
            popupWindow.dismiss();
        }
    };

}

这里需要多点讲解的就是 PopupWindow显示的位置:

  • showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移

  • showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移

  • showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移

  • -

另一个就是可以比较Menu和PopupMenu的区别:初始化方法和点击事件的方法不同。


常用基础控件集合(1)

  • 基础原生控件

Android开发的基础技能总结(1)_第2张图片

代码参考github地址 。

还有一些我看第一行代码的项目。这里我就不发了。今天先写到这里。等下次我在分类继续写关于基础的使用。

你可能感兴趣的:(基础)