ラベル Android の投稿を表示しています。 すべての投稿を表示
ラベル Android の投稿を表示しています。 すべての投稿を表示

2016年11月12日土曜日

Android SharedPreferences

Android SharedPreferences

Develop > API Guides >数据存储
https://developer.android.com/guide/topics/data/data-storage.html#pref
https://www.youtube.com/watch?v=HWKcVeNcs20&index=11&list=PLHOqLxXumAI-ASmOAbuV9oD-gxHvjsjUU

文件的写入位置
System.out: /data/data/com.example.e560.m1110a/shared_prefs/xml.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <boolean name="chk" value="true" />
    <string name="key">new value</string>
    <set name="StringSet">
        <string>String1</string>
        <string>String2</string>
    </set>
    <int name="int" value="123" />
</map>




public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setinfo();
        addinfo();
        getinfo();
        File f = new File("/data/data/com.example.e560.m1110a/shared_prefs");
        System.out.println("----------");
        File[] fs = f.listFiles();
        System.out.println(fs.length);
        for (int i = 0; i < fs.length; i++) {
            File temp = fs[i];
            System.out.println(temp.getPath());
        }
    }

    protected void getinfo() {
        SharedPreferences sp = this.getSharedPreferences("xml", MODE_PRIVATE);
        LinearLayout lv = new LinearLayout(this);
        EditText et = new EditText(this);
        et.setText(sp.getAll().toString());
        lv.addView(et);
        setContentView(lv);
    }

    protected void setinfo() {
        SharedPreferences sp = this.getSharedPreferences("xml", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("key", "value");
        edit.putInt("int", 123);
        edit.putBoolean("chk", true);
        edit.commit();
    }

    protected void addinfo() {
        SharedPreferences sp = this.getSharedPreferences("xml", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("key", "new value");
        Set<String> list = new HashSet<String>();
        list.add("String1");
        list.add("String2");
        edit.putStringSet("StringSet", list);
        edit.commit();
    }
}

2016年11月9日水曜日

Android 文件保存,文件读取

Android 文件保存,文件读取
使用内部存储
https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

使用文件名称和操作模式调用 openFileOutput()。 这将返回一个 FileOutputStream。
使用 write() 写入到文件。
使用 close() 关闭流式传输。


public class MainActivity extends AppCompatActivity {

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

    protected void GetUser() {
        try {
            FileInputStream fis = new FileInputStream(new File(this.getFilesDir(), "user.csv"));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = fis.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }
            System.out.println(baos.toString());
            JSONObject jde = new JSONObject(baos.toString());
            TextView tv1 = (TextView) findViewById(R.id.textView2);
            tv1.setText(jde.getString("userName"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void Userinfo() {
        JSONObject j = new JSONObject();
        JSONObject j2 = new JSONObject();
        try {
            j.put("userName", "sun");
            j.put("password", "12345");
            j2.put("phone1", "99999");
            j2.put("Phone2", "88808880");
            j.put("Phones", j2);
            File f = new File(this.getFilesDir(), "user.csv");
            FileOutputStream fos = new FileOutputStream(f);
            fos.write((j.toString()).getBytes());
            fos.close();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2016年11月8日火曜日

Android 下载JSON文体,解析为数组,自定义Adapter显示

Android 下载JSON文体,解析为数组,自定义Adapter显示



public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt = (Button) findViewById(R.id.button2);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyasyncTask().execute("http://cdefgab.web.fc2.com/song.json");
            }
        });
    }

//   下载JSON文体,解析为数组,自定义Adapter显示。
    public class MyasyncTask extends AsyncTask<String, Integer, List<String>> {
        @Override
        protected List<String> doInBackground(String... params) {
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            List<String> data = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");
                baos = new ByteArrayOutputStream();
                if (huc.getResponseCode() == 200) {
                    is = huc.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                    JSONObject js = new JSONObject(baos.toString());
                    JSONObject js2 = js.getJSONObject("photos");
                    JSONArray ja1 = js2.getJSONArray("photo");
                    data = new ArrayList<String>();
                    for (int i = 0; i < ja1.length(); i++) {
                        JSONObject js3 = ja1.getJSONObject(i);
                        data.add(js3.getString("title"));
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return data;
        }

        @Override
        protected void onPostExecute(final List<String> strings) {
            super.onPostExecute(strings);
            ListView lv = (ListView) findViewById(R.id.listview);
//            lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,strings));
            mya m = new mya(strings);
            m.notifyDataSetChanged();
            lv.setAdapter(m);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(MainActivity.this, strings.get(position), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public class mya extends BaseAdapter {
        private List<String> temp;

        public mya(List<String> temp) {
            this.temp = temp;
        }

        @Override
        public int getCount() {
            return temp.size();
        }

        @Override
        public Object getItem(int position) {
            return temp.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;
            if (convertView == null) {
                view = LayoutInflater.from(MainActivity.this).inflate(R.layout.myadapter1, null);
            } else {
                view = convertView;
            }
            TextView tv = (TextView) view.findViewById(R.id.textView5);
            tv.setText(temp.get(position));
            return view;
        }
    }
}

2016年11月7日月曜日

字节流转换字符流

字节流转换字符流




public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new XML().execute("null");
    }

    public class XML extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            try {
//                URL u = new URL("http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip");
                URL u = new URL("http://cdefgab.web.fc2.com/song.json");
                HttpURLConnection huc = (HttpURLConnection) u.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");
//                字节流转换字符流方法
//                if(huc.getResponseCode() == 200) {
//                    BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream(),"utf-8"));
//                    InputStream is = huc.getInputStream();
//                    InputStreamReader isr = new InputStreamReader(is,"utf-8");
//                    BufferedReader br = new BufferedReader(isr);
//                    String temp = null;
//                    while((temp = br.readLine()) != null){
//                        System.out.println("--------------");
//                        System.out.println(temp);
//                    }
//                }

//                字节流缓冲方法
                if (huc.getResponseCode() == 200) {
                    System.out.println("-----Astart");
                    BufferedInputStream bis = new BufferedInputStream(huc.getInputStream());
                    int i = 0;
                    byte[] buff = new byte[1024];
                    while ((i = bis.read(buff)) != -1) {
                        System.out.println("deta.length--" + i);
                        System.out.println(new String(buff, 0, i));
                    }
                    System.out.println("-----Aend");
                }

                if (huc.getResponseCode() == 200) {
                    System.out.println("-----Bstart");
                    InputStream is = huc.getInputStream();
                    byte[] buff = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buff)) != -1) {
                        System.out.println("data.lenght" + len);
                        System.out.println(new String(buff, 0, len));
                    }
                    System.out.println("-----Bend");
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

2016年11月6日日曜日

AscnyTask 练习

AscnyTask 练习



public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ProgressDialog pd;

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

        //设置一个下载进度条
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(0);
        pd.setTitle("Downloadnow");

        //设置响应事件
        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(this);
        Button bt2 = (Button) findViewById(R.id.button2);
        bt2.setOnClickListener(this);
        Button bt3 = (Button) findViewById(R.id.button3);
        bt3.setOnClickListener(this);
        Button bt4 = (Button) findViewById(R.id.button4);
        bt4.setOnClickListener(this);
        Button bt5 = (Button) findViewById(R.id.button5);
        bt5.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Img i = new Img();
        System.out.println(v.getId());
        switch (v.getId()) {
            case R.id.button:
                i.execute("http://image.i-voce.jp/files/article/main/s8AO3sFN_1438142266.jpg");
                break;
            case R.id.button2:
                i.execute("http://pic.prepics-cdn.com/d75526b7cc13/41938040.jpeg");
                break;
            case R.id.button3:
                i.execute("http://entertainment.rakuten.co.jp/movie/interview/kiritanimirei/img/interviewimg001.jpg");
                break;
            case R.id.button4:
                i.execute("http://up.gc-img.net/post_img_web/2015/09/32f61210611d358bddc2784d875cf65e_4238.jpeg");
                break;
            case R.id.button5:
                i.execute("http://lwoyr.com/wp-content/uploads/2015/06/20150618_5.jpg");
                break;
        }
    }

    public class Img extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            byte[] reBate = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");

                //用文件长度设置进度条的最大值
                pd.setMax(huc.getContentLength());
                if (huc.getResponseCode() == 200) {
                    InputStream is = huc.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        baos.write(buf, 0, len);
                        publishProgress(baos.size());
                    }
                    reBate = baos.toByteArray();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return reBate;
        }

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

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            ImageView iv = (ImageView) findViewById(R.id.imageView2);
            iv.setImageBitmap(bitmap);
            pd.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pd.setProgress(values[0]);
        }
    }
}

Android AsyncTask 异步任务下载图片并显示咋UI线程

Android AsyncTask 异步任务下载图片并显示咋UI线程



public class MainActivity extends AppCompatActivity {
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv = (ImageView) findViewById(R.id.imageView);
                DownImg di = new DownImg(MainActivity.this, iv);
                di.execute("url");
            }
        });
    }
}



public class DownImg extends AsyncTask<String, Integer, byte[]> {
    private ImageView iv;
    private int file_length;
    private Context context;
    protected ProgressDialog pd;

    public DownImg(Context context, ImageView iv) {
        this.iv = iv;
        this.context = context;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        ByteArrayOutputStream bos = null;
        try {
            URL url = new URL("http://prw.kyodonews.jp/prwfile/release/M102245/201403149047/_prw_PI1fl_2o2KuN2D.jpg");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            file_length = httpURLConnection.getContentLength();
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = httpURLConnection.getInputStream();
                bos = new ByteArrayOutputStream();
                byte[] buff =  new byte[1024];
                int len = 0;
                while ((len = is.read(buff)) != -1) {
                    bos.write(buff, 0, len);
                    publishProgress(file_length,bos.size());
                }
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos.toByteArray();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setTitle("test");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);
        pd.setMax(100);
        pd.setProgress(0);
        pd.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        pd.setMax(values[0]);
        pd.setProgress(values[1]);
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        Bitmap bt = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        iv.setImageBitmap(bt);
        pd.dismiss();
    }
}



2016年11月4日金曜日

Android JSONObject 练习

Android JSONObject 练习

1.  JSON链接
     http://cdefgab.web.fc2.com/song.json


public class DownJson {

    public void ejson() {
        String data = jsonString();
        HashMap<String, String> hh = new HashMap<String, String>();
        HashMap<Integer, HashMap<String, String>> hl = new HashMap<Integer, HashMap<String, String>>();

        try {
            JSONObject js = new JSONObject(data);
            JSONObject js2 = js.getJSONObject("photos");
            hh.put("stat", js.getString("stat"));
            hh.put("page", js2.getString("page"));
            hh.put("pages", js2.getString("pages"));
            hh.put("perpage", js2.getString("perpage"));
            hh.put("total", js2.getString("total"));

            String ja = js2.getString("photo");
            JSONArray jaa = new JSONArray(ja);

            for (int i = 0; i < jaa.length(); i++) {
                JSONObject t1 = jaa.getJSONObject(i);
                HashMap<String, String> hmt = new HashMap<String, String>();
                hmt.put("id", t1.getString("id"));
                hmt.put("owner", t1.getString("owner"));
                hmt.put("secret", t1.getString("secret"));
                hmt.put("server", t1.getString("server"));
                hmt.put("farm", t1.getString("farm"));
                hmt.put("title", t1.getString("title"));
                hmt.put("ispublic", t1.getString("ispublic"));
                hmt.put("isfriend", t1.getString("isfriend"));
                hmt.put("isfamily", t1.getString("isfamily"));
                hl.put(i, hmt);
            }

            System.out.println("-----------------------");
            System.out.println(hl.get(0).get("title"));
            System.out.println("-----------------------");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public static String jsonString() {
        String jstring = null;
        InputStream is = null;
        try {
            URL u = new URL("http://cdefgab.web.fc2.com/song.json");
            HttpURLConnection h = (HttpURLConnection) u.openConnection();
            h.setRequestMethod("GET");
            h.setDoInput(true);
            h.setConnectTimeout(3000);
            h.setReadTimeout(3000);
            if (h.getResponseCode() == 200) {
                byte[] buff = new byte[1024];
                int len = 0;
                is = h.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((len = is.read(buff)) != -1) {
                    baos.write(buff, 0, len);
                }
                jstring = baos.toString("utf-8");
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jstring;
    }
}


2016年10月31日月曜日

Android FileWriter,FileReader

Android FileWriter,FileReader

文件的保存位置有要求
   String path ="/data/data/" + this.getPackageName() +"/demo.txt";



import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Test();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void Test() throws IOException {
        final String tag = "testFile";
        String path ="/data/data/" + this.getPackageName() +"/demo.txt";
        FileWriter fileWriter = new FileWriter(path);

        for( int i = 0; i <102; i++){
            fileWriter.write(String.valueOf(i));
        }
        fileWriter.flush();
        fileWriter.close();

        FileReader fileReader = new FileReader(path);
        char[] buf = new char[24];
        int num;
        while(((num = fileReader.read(buf)) != 0)){
            System.out.println("---" + new String(buf,0,num));
        }
        fileReader.close();
    }
}


结果
com.example.java.m1031a I/System.out: ---012345678910111213141516
com.example.java.m1031a I/System.out: ---171819202122232425262728
com.example.java.m1031a I/System.out: ---293031323334353637383940
com.example.java.m1031a I/System.out: ---414243444546474849505152
com.example.java.m1031a I/System.out: ---535455565758596061626364
com.example.java.m1031a I/System.out: ---656667686970717273747576
com.example.java.m1031a I/System.out: ---777879808182838485868788
com.example.java.m1031a I/System.out: ---899091929394959697989910
com.example.java.m1031a I/System.out: ---0101





2016年10月30日日曜日

Android應用開發視頻教程

黑马程序员 毕向东 Java基础视频教程
https://www.youtube.com/playlist?list=PLvswSo32Xlu_ctuWa-7-huGYUlsslzVhi


Android應用開發視頻教程
https://www.youtube.com/playlist?list=PLvswSo32Xlu8EVeS2RZvTg30M78WLROkT





2016年10月27日木曜日

Grid View 自定义布局

Grid View 自定义布局

1.   选择 Grid View 的布局位置
2.   自定义Adapter
3.   设置数据




public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gv = (GridView) findViewById(R.id.gv);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view.findViewById(R.id.grid_textview);
                String s = tv.getText().toString();
                Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
        imgAdapter imgadapter = new imgAdapter();
        gv.setAdapter(imgadapter);
    }

    class imgAdapter extends BaseAdapter {
        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = LayoutInflater.from(getApplication()).inflate(R.layout.gridview, null);
            ImageView iv = (ImageView) v.findViewById(R.id.grid_img);
            TextView tv = (TextView) v.findViewById(R.id.grid_textview);
            iv.setImageResource(mThumbIds[position]);
            tv.setText(getString(mThumbIds[position]));
            return v;
        }

        private Integer[] mThumbIds = {
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7
        };
    }
}


Activity 布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.e560.m1026gridview.MainActivity">

    <GridView
        android:id="@+id/gv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
        />
</RelativeLayout>


自定义布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <ImageView
            android:id="@+id/grid_img"
            android:layout_width="400dp"
            android:layout_height="140dp"
            android:background="#CCCCCC" />

        <TextView
            android:id="@+id/grid_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFCCCC"
            android:textSize="20dp" />

</RelativeLayout>





2016年10月24日月曜日

Android 生命周期

Android 生命周期



第一次启动
MainActivity: --1--onCreate
MainActivity: --2--onStart
MainActivity: --3--onResume

跳到其他Activity
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

返回键返回
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume

接电话
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState  有延迟

挂电话
MainActivity: --3--onResume

按返回键推出到Android界面
MainActivity: --4--onPause
MainActivity: --5--onStop
MainActivity: --7--onDestroy

重新启动
MainActivity: --1--onCreate
MainActivity: --2--onStart
MainActivity: --3--onResume

旋转屏幕
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop
MainActivity: --7--onDestroy
MainActivity: --1--onCreate
MainActivity: --2--onStart
MainActivity: --8--onRestoreInstanceState
MainActivity: --3--onResume

按Home键
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

按APP图标开启
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume

按Power键,关屏幕
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

按Power键,开屏幕
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume

按方块键
MainActivity: --4--onPause
MainActivity: --9--onSaveInstanceState
MainActivity: --5--onStop

按方块键,重新回到App
MainActivity: --6--onRestart
MainActivity: --2--onStart
MainActivity: --3--onResume



public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "--1--onCreate");

        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NewActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "--2--onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "--3--onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "--4--onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "--5--onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "--6--onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "--7--onDestroy");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG, "--8--onRestoreInstanceState");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(TAG,"--9--onSaveInstanceState");
    }
}

2016年10月22日土曜日

ListFragment 和自定义布局Layout

ListFragment 和自定义布局Layout

public class ListFrag extends ListFragment {

    public myadaputer adapter;
    public List<String> data;

    public void setData(List<String> data) {
        this.data = data;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new myadaputer();
        adapter.setDate(getdata());
    }

    public List<String> getdata(){
        Bundle ig = getArguments();
        int size = ig.getInt("size");
        List<String> x = new ArrayList<String>();
        for(int i=0;i< size ;i++) {
            x.add("add" + i);
        }
        return x;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.listfrag_layout, null);
        setListAdapter(adapter);
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Toast.makeText(getActivity(), "onListItemClick", Toast.LENGTH_SHORT).show();
    }

    class myadaputer extends BaseAdapter {
        private List<String> data;
        public void setDate(List<String> data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
    }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;
            if(convertView == null){
                view = LayoutInflater.from(getActivity()).inflate(R.layout.listview,null);
            }else{
                view = convertView;
            }
            TextView tv = (TextView) view.findViewById(R.id.textView);
            tv.setText(data.get(position).toString());
            return view;
        }
    }


}

2016年10月20日木曜日

在MainActivity内调用Fragment内的控件并实现方法

在MainActivity内调用Fragment内的控件,
并在MainActivity内实现Fragment内的控件的方法

MainActivety.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private xxx x;
    private vvv v;
    private EditText xet ,vet;
    private Button xbt, vbt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        x = new xxx();
        v = new vvv();
        fragmentTransaction.add(R.id.vvv, v, "fv");
        fragmentTransaction.add(R.id.xxx, x, "fx");
        fragmentTransaction.commit();
    }

    @Override
    protected void onStart() {
        super.onStart();
        xbt = (Button) x.getView().findViewById(R.id.xxxbutton);
        vbt = (Button) v.getView().findViewById(R.id.vvvbutton);
        xbt.setOnClickListener(this);
        vbt.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        vet = (EditText) v.getView().findViewById(R.id.vvveditText);
        xet = (EditText) x.getView().findViewById(R.id.xxxeditText);

        switch(view.getId()){
            case R.id.vvvbutton:
                if(vet != null) {
                    vet.setText(xet.getText().toString());
                    System.out.println(vet);
                }
                break;

            case R.id.xxxbutton:
                if(xet != null) {
                    xet.setText(vet.getText().toString());
                    System.out.println(xet);
                }
                break;
            default:
                break;
        }
    }
}



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.java.m1020a.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/xxx"
        android:orientation="vertical"
        ></LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/vvv"
        android:orientation="vertical"
        ></LinearLayout>
</LinearLayout>


vvv.java
xxx.java

public class vvv extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fvvv, null);
        return v;
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}


fvvv.xml
fxxx.xml

<?xml version="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">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="fv"
        android:ems="10"
        android:id="@+id/vvveditText" />

    <Button
        android:text="fvvv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/vvvbutton" />

</LinearLayout>


2016年10月19日水曜日

在MainActivity 调用 Fragment 的控件

在MainActivity 调用代码方式加载的 Fragment 内的控件。


public class MainActivity extends AppCompatActivity {

    private FragmentManager fm;
    private FragmentTransaction ft;
    private Button bt;
    private Fraga fa;
    @Override
//加载Fragment
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fm = getFragmentManager();
        ft = fm.beginTransaction();
        fa = new Fraga();
        ft.add(R.id.fraga, fa, "fa");
        ft.commit();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 获得Fragment的控件
        Button bt = (Button) fa.getView().findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView tv = (TextView) fa.getView().findViewById(R.id.textView);
                tv.setText("MainActivity");
            }
        });

    }
}

//如果在onCreate方法中去获取Fragment的控件,可能因Fragment
被加载之前调用 getView 方法,会出空指针错误。

2016年10月18日火曜日

Android 接口回调 和 多线程

Android 接口回调 和 多线程


Back.java

public class Back {

    private int i;

    public interface CallBack{
        public void getstring(int s);
    }

    public void demo(final CallBack callBack){
        Thread tt = new Thread(new Runnable() {
            @Override
            public void run() {
                for (i = 0; i < 999999; i++){
                }
                callBack.getstring(i);
            }
        });

        try {
            tt.sleep(5000);
        }catch (Exception e){

        }
        tt.start();
    }
}


MainActivity.java
public class MainActivity extends AppCompatActivity {

    private EditText ed;

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

        new Thread(new Runnable() {
            @Override
            public void run() {
                Back back = new Back();
                back.demo(new Back.CallBack() {
                    @Override
                    public void getstring(final int s) {
                        System.out.println(s);
                        ed = (EditText) findViewById(R.id.editText);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ed.setText("合計:" + s);
                            }
                        });
                    }
                });
            }
        }).start();
    }
}

创建对 Activity 的事件回调

创建对 Activity 的事件回调

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Fraga fraga = new Fraga();
        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment, fraga, "fragment1");
        fragmentTransaction.commit();
       
        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fraga.setcall(new Fraga.CallBack() {
                    @Override
                    public void getText(String xx) {
                        Toast.makeText(MainActivity.this, xx, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}

Fraga.java

public class Fraga extends Fragment {

    EditText editText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fraga, null);
        editText = (EditText) v.findViewById(R.id.editText2);
        return v;
    }

    public void setcall(CallBack callBack){
        callBack.getText(editText.getText().toString());
    }

    public interface CallBack{
        public void getText(String xx);
    }
}





2016年10月15日土曜日

Android 向 Activity 添加片段

管理片段

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();


Java
public class MainActivity extends AppCompatActivity {
    private Integer con = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // 方法1
        // Frag1 f1 = (Frag1) fragmentManager.findFragmentById(R.id.fragment);
        // 方法2
        Frag1 f1 = (Frag1) fragmentManager.findFragmentByTag("tag");
        Button bt = (Button) f1.getView().findViewById(R.id.button);
        bt.setText("Fragmentbut");
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                con = con + 1;
                Toast.makeText(MainActivity.this, "Count" + con, Toast.LENGTH_SHORT).show();
            }
        });
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.e560.m1014c.MainActivity">


    <fragment
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.example.e560.m1014c.Frag1"
        android:tag="tag"
        android:layout_weight="1" />
</LinearLayout>



2016年10月8日土曜日

startActivityForResult

startActivityForResult  的利用

1.  跳转新的Activity方法
     public void bt1(View view){
        Toast.makeText(this, "bu1", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, v2.class);
        startActivityForResult(intent, 99);
    }

2.  回调方法
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String ss = data.getStringExtra("a").toString();
        ((EditText) findViewById(R.id.editText1)).setText(ss);
        String b = data.getStringExtra("b").toString();
        String c = data.getStringExtra("c").toString();
        Toast.makeText(this, b, Toast.LENGTH_SHORT).show();
        this.setTitle(c);
    }

3.  从新的Activity返回值的的方法
    public void bu2(View view){
        EditText et = (EditText) findViewById(R.id.editText);
        Intent intent = new Intent();
        intent.putExtra("a", et.getText().toString());
        intent.putExtra("b", "bbbbbb");
        intent.putExtra("c", "cccccc");
        setResult(88,intent);
        this.finish();
    }

2016年10月6日木曜日

添加按键,打开或隐藏Toolbar

添加按键,打开或隐藏Toolbar






    private void toolbarButton() {
//        找到当前的Layout
        ViewGroup thislayout = (ViewGroup) findViewById(R.id.activity_main);
//        新建按键
        final Button button = new Button(this);
//        添加按键到Layout
        thislayout.addView(button);
//        检查按键状态,并改变按键标题
        if(SUPPORTBARCHK){
            button.setText(R.string.heid);
        }else{
            button.setText(R.string.show);
        }

//        按键事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                检查按键状态,并改变按键标题,并改变ActionBar的显示状态
                if(SUPPORTBARCHK) {
//                    getActionBar().hide(); //错误
                    getSupportActionBar().hide();
                    button.setText(R.string.show);
                    SUPPORTBARCHK = false;
                }else{
//                    getActionBar().show(); //错误
                    getSupportActionBar().show();
                    button.setText(R.string.heid);
                    SUPPORTBARCHK = true;
                }
            }
        });
    }

2016年10月5日水曜日

EmptyActivite 基础上添加Toolbar

EmptyActivite 基础上添加Toolbar


MainActivity.java
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

//        EmptyActivite 基础上添加Toolbar
//        step1,AppCompatActivity
//        step2,noActionBar manifest
//        step3,activitymain.xml
//        step4, new Toolbar

        Toolbar tb = (Toolbar) findViewById(R.id.my_toolbar);
        tb.setTitle("newToolbar");
        setSupportActionBar(tb);
//      背景图标 or 背景颜色
        tb.setBackgroundResource(R.drawable.firefox);
        tb.setBackgroundResource(android.R.color.holo_blue_bright);
//      添加先上导航,在ActionBar上添加
        ActionBar ab =getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

//      测试
//      ab.hide();
    }

//    添加ToolBar 的选项菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater mif = new MenuInflater(this);
        mif.inflate(R.menu.optmenu, menu);
        menu.add("addMenu1");
        menu.add("addMenu2");
        System.out.println(menu.size());
        return super.onCreateOptionsMenu(menu);
    }

//    ToolBar 选项菜单事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        System.out.println("item");
        System.out.println(item.getTitle());
        System.out.println(item.getItemId());
        System.out.println(item.getMenuInfo());
        return super.onOptionsItemSelected(item);
    }
}



AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.java.m1004c">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.example.java.m1004c.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        android:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

</RelativeLayout>



optmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu1"
        android:icon="@android:drawable/ic_dialog_email"
        android:title="menu1.title"
        android:showAsAction="ifRoom"
       />

    <item
        android:id="@+id/menu2"
        android:title="menu2.title"
        android:showAsAction="always"
        />
</menu>