×

android学习系列-控件用法(2)2

Kalet Kalet 发表于2013-12-20 11:07:32 浏览201 评论0

抢沙发发表评论

6.MediaProvider

6.        MediaProvider

效果

 

JAVA代码

package tjuci.edu.dl;

 

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.net.Uri;

import android.os.Bundle;

import android.provider.MediaStore.Images.Media;

import android.view.View;

import android.widget.Button;

import android.widget.ListView;

import android.widget.SimpleAdapter;

import android.widget.Toast;

 

publicclass MediaProviderSampleActivityextends Activity{

    /** Called  when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Button seeBtn,addBtn;

        final ListView listView;

        final ArrayList<String> names =new  ArrayList<String>();

        final ArrayList<String> desc =new  ArrayList<String>();

        final ArrayList<String> fileNames  =new ArrayList<String>();

        seeBtn = (Button)findViewById(R.id.see);

        addBtn = (Button)findViewById(R.id.add);

        listView =  (ListView)findViewById(R.id.listView);

        seeBtn.setOnClickListener(new  View.OnClickListener() {

            @Override

            publicvoid onClick(View v) {

                //TODO Auto-generated method stub

                Cursor cursor =  getContentResolver().query(Media.EXTERNAL_CONTENT_URI,null,null,null,null);

                while(cursor.moveToNext()){

                    names.add(cursor.getString(cursor.getColumnIndex(Media.DISPLAY_NAME)));

                    desc.add(cursor.getString(cursor.getColumnIndex(Media.DESCRIPTION)));

                    byte[] data = cursor.getBlob(cursor.getColumnIndex(Media.DATA));

                    fileNames.add(new String(data,0,data.length-1));

                }

                List<Map<String,Object>>  list =new ArrayList<Map<String,Object>>();

if(names.size() == 0 || names ==null){

    Toast.makeText(MediaProviderSampleActivity.this,"暂时没有图片", Toast.LENGTH_SHORT).show();

}

                for(int i = 0; i < names.size(); i ++ ){

                    Map<String,Object>  map =new HashMap<String,Object>();

                    map.put("name", names.get(i));

                    map.put("desc", desc.get(i));

                    list.add(map);

                }

                SimpleAdapter sa =new  SimpleAdapter(MediaProviderSampleActivity.this, list, R.layout.line,new String[]{"name","desc"},newint[]{R.id.name,R.id.desc});

                listView.setAdapter(sa);

            }

        });

        addBtn.setOnClickListener(new View.OnClickListener()  {

            @Override

            publicvoid onClick(View v) {

                //TODO Auto-generated method stub

                ContentValues values =new ContentValues();

                values.put(Media.DISPLAY_NAME,"jinta");

                values.put(Media.DESCRIPTION,"金塔");

                values.put(Media.MIME_TYPE,"image/jpeg");

                Uri uri =  getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);

                Bitmap bitmap = BitmapFactory.decodeResource(MediaProviderSampleActivity.this.getResources(),  R.drawable.jinta);

                OutputStream os =null;

                try {

                    os =  getContentResolver().openOutputStream(uri);

                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100,os);

                    os.close();

                catch (Exception e) {

                    //TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        });

    }

}

XML代码

Ø  Main.xml

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

<LinearLayout

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="horizontal"

     android:gravity="center_horizontal">

     <Button

         android:id="@+id/see"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="查看"/>

     <Button

         android:id="@+id/add"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="添加"/>

</LinearLayout>

   <ListView

       android:id="@+id/listView"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        />

 

</LinearLayout>

Ø  line.xml

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

   <TextView

       android:id="@+id/name"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        />

 <TextView

       android:id="@+id/desc"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        />

</LinearLayout>

 

 

7.SqlLite

7.        SqlLite

效果

 

JAVA代码

package tjuci.edu.dl;

 

import android.app.Activity;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

import android.widget.SimpleCursorAdapter;

 

publicclassSQLiteSampleActivity  extends Activity {

    EditText titlecontent;

    ListView listView;

    Button btn;

    SQLiteDatabase db = null;

 

    /** Called  when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

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

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

        listView = (ListView) findViewById(R.id.listView);

        btn = (Button) findViewById(R.id.btn);

        db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/my.db3",

                null);

        btn.setOnClickListener(new  View.OnClickListener() {

            @Override

            publicvoid onClick(View v) {

                try {

                    //TODO Auto-generated method stub

                    insertData(db,title.getText().toString(), content

                            .getText().toString());

                    Cursor cursor =db.rawQuery("select * from mydb",null);//查询的结果集

                                                                           // ---类似ResultSet

                    inflateCursor(cursor);

                catch (Exception e) {

                    db.execSQL("create table mydb(_id integer primary key autoincrement,title  varchar(255),content varchar(255))");

                    insertData(db,title.getText().toString(), content

                            .getText().toString());

                    Cursor cursor =db.rawQuery("select * from mydb",null);//查询的结果集

                                                                           // ---类似ResultSet

                    inflateCursor(cursor);

                }

            }

        });

    }

 

    publicvoid insertData(SQLiteDatabase db,  String title, String content) {

        db.execSQL("insert into mydb(_id,title,content) values(null,?,?)",

                new String[] { title, content });

    }

 

    publicvoid inflateCursor(Cursor cursor) {

        SimpleCursorAdapter sca =new SimpleCursorAdapter(this, R.layout.line,

                cursor, new String[] {"title""content" }, newint[] {

                        R.id.tv1, R.id.tv2 });

        listView.setAdapter(sca);

    }

    @Override

    protectedvoid onDestroy() {

        super.onDestroy();

        if(db !=null &&db.isOpen()){

            db.close();

        }

    }

}

XML代码

Ø  Main.xml

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

<!-- 标题 -->

    <EditText

        android:id="@+id/title"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

         />

<!-- 内容 -->

<EditText

        android:id="@+id/content"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

         />

<!-- 插入 -->

<Button

     android:id="@+id/btn"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="插入"/>

<!-- 显示 -->

<ListView

     android:id="@+id/listView"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_gravity="center"/>

</LinearLayout>

Ø  Line.xml

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

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

     android:layout_width="match_parent"

     android:layout_height="match_parent" 

    >   

<TableRow>

    <TextView

        android:id="@+id/tv1"

        android:layout_width="100dp"

        android:layout_height="wrap_content"/>

     <TextView

        android:id="@+id/tv2"

        android:layout_width="200dp"

        android:layout_height="wrap_content"/>

</TableRow>

</TableLayout>

 

8.ProgressBar

8.        ProgressBar

效果

 

JAVA代码

package tjuci.edu.dl;

 

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.widget.ProgressBar;

 

publicclassProgressBarSampleActivity  extends Activity {

    /** Called  when the activity is first created. */

    //模拟任务大小为100个数组

    privateint[]data = newint[100];

    //任务完成度--默认为0

    privateinthasdata = 0;

    //状态完成度

    intstatus = 0;

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

 

        final Handler h =new Handler() {

            @Override

            publicvoid handleMessage(Message msg) {

                //TODO Auto-generated method stub

                if(msg.what == 0x11){

                    ProgressBar pb =  (ProgressBar)findViewById(R.id.pb);

                    pb.setProgress(status);

                }

            }

        };

 

        // 构造一个线程

        new Thread() {

            @Override

            publicvoid run() {

                while (status < 100) {

                    status = dowork();

                    Message m = new Message();

                    m.what = 0x11;

                    h.handleMessage(m);

                }

            }

        }.start();

    }

 

    publicint dowork() {

        //完成1001

        data[hasdata++] = 1;

        try {

            Thread.sleep(100);

        catch (InterruptedException e) {

            e.printStackTrace();

        }

        returnhasdata;

    }

}

XML代码

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

 

   <ProgressBar

       android:id="@+id/pb"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       style="@android:style/Widget.ProgressBar.Horizontal"/>

</LinearLayout>

 

9.ProgressDialog

9.        ProgressDialog

效果

 

JAVA代码

package tjuci.edu.dl;

 

import android.app.Activity;

import android.app.Dialog;

import android.app.ProgressDialog;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.widget.Button;

 

publicclass ProgressDialogSampleActivityextends Activity {

   

    /** Called  when the activity is first created. */

    //任务大小

    privateint[]data = newint[100];

    //已经完成数据

    privateinthasdata = 0;

    //完成程度

    privateintstatus = 0;

    //设置标记

    finalintSIGN = 0x11;

    Handler h;

    //定义一个ProgressDialog

    ProgressDialog pd ;

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Button btn =  (Button)findViewById(R.id.btn);

        btn.setOnClickListener(new  View.OnClickListener() {

            @Override

            publicvoid onClick(View v) {

                //TODO Auto-generated method stub

                showDialog(SIGN);

            }

        });

        h =new Handler(){

            @Override

            publicvoid handleMessage(Message msg) {

                switch (msg.what) {

                case 0x1111:

                    pd.setProgress(status);

                    break;

                default:

                    break;

                }

                pd.setProgress(status);

            }

       

        };

       

    }

    //调用onPrepareDialog()方法之后

    @Override

    protected Dialog onCreateDialog(int id, Bundle args) {

        //TODO Auto-generated method stub

    pd =new ProgressDialog(this);

    pd.setMax(100);

    pd.setMessage("任务百分比");

    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    pd.setCancelable(false);

    returnpd;

    }

    //调用showDialog()之后和调用onCreateDialog之前

    @Override

    protectedvoid onPrepareDialog(int id, Dialog dialog,  Bundle args) {

        //TODO Auto-generated method stub

        switch (id) {

        caseSIGN:

            pd.incrementProgressBy(-pd.getProgress());

            new Thread(){

                @Override

                publicvoid run() {

                    while(status < 100){

                        status = dowork();

                        Message msg =new Message();

                        msg.what = 0x1111;

                        h.sendMessage(msg);

                    }

                    if(status >= 100){

                        pd.dismiss();

                    }

                }  

            }.start();

            break;

        }

    }

    publicint dowork(){

        data[hasdata ++] = (int)(Math.random()*100);

        try {

            Thread.sleep(100);

        catch (InterruptedException e) {

            e.printStackTrace();

        }

        returnhasdata;

    }

   

}

XML代码

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical"

     android:layout_gravity="center_horizontal" >

 

    <Button

        android:id="@+id/btn"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="ProgressDialog"/>

 

</LinearLayout>

 

10.   RadioButtonAndChechBox

10.  RadioButtonAndChechBox

效果

 

JAVA代码

package tjuci.edu.dl;

import android.app.Activity;

import android.os.Bundle;

 

publicclass RadioButtonAndCheckBoxActivityextends Activity {

    /** Called  when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

    }

}

XML代码

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

<TableRow>

    <TextView

        android:id="@+id/gender"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="性别"

        android:textSize="10pt"

        /> 

        <RadioGroup

            android:id="@+id/rg"

            android:orientation="horizontal"

            android:gravity="center_horizontal">

             <RadioButton

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:checked="true"

                android:text="男"/>

             <RadioButton

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="女"/>

        </RadioGroup> 

    </TableRow>

    <TableRow>

        <TextView

            android:id="@+id/color"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="喜欢的颜色"

            android:textSize="10pt"/>

        <LinearLayout

            android:id="@+id/ll"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:orientation="vertical"

            android:gravity="center_vertical">

            <CheckBox

                android:id="@+id/cb1"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="红色"

                android:checked="true"/>

             <CheckBox

                android:id="@+id/cb1"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="绿色"

                android:checked="true"/>

              <CheckBox

                android:id="@+id/cb1"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="黑色"

                android:checked="false"/>

            </LinearLayout>

        </TableRow>

   

</TableLayout>

 

11.   RatingBar

11.  RatingBar

效果

 

JAVA代码

package tjuci.edu.dl;

 

import android.app.Activity;

import android.os.Bundle;

 

publicclass RatingBarSampleActivityextends Activity {

    /** Called  when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

    }

}

XML代码

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

 

   <RatingBar

       android:id="@+id/ratingbar"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:numStars="5"

       android:max="255"

       android:progress="255"

       android:stepSize="0.5"/>

 

</LinearLayout>

 

12.    RelativeLayout

12.   RelativeLayout

效果

 

JAVA代码

package tjuci.edu.dl;

import android.app.Activity;

import android.os.Bundle;

 

publicclass RelativeLayoutSampleActivityextends Activity {

    /** Called  when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

    }

}

XML代码

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" 

     android:gravity="center">

    <Button

        android:id="@+id/btn1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="中间的按钮,很长很长很长"

        android:layout_centerInParent="true"/>

   <Button

        android:id="@+id/btn2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="上边的按钮"

        android:layout_above="@id/btn1"

        android:layout_alignLeft="@+id/btn1"/>

 <Button

        android:id="@+id/btn3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="下边的按钮"

        android:layout_below="@id/btn1"

        android:layout_alignRight="@+id/btn1"/>

</RelativeLayout>

13.   Nenu

13.  Menu

效果

 

JAVA代码

package tjuci.edu.dl;

 

import android.app.Activity;

import android.graphics.Color;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.SubMenu;

import android.widget.EditText;

import android.widget.Toast;

 

publicclass MenuSampleActivityextends Activity {

 

    //定义字体大小标示符

    finalintFONT_2 = 0x112;

    finalintFONT_4 = 0x113;

    finalintFONT_10 = 0x114;

    finalintFONT_12 = 0x115;

    finalintFONT_16 = 0x116;

    //定义普通菜单标示符

    finalintNORMAL = 0x111b;

    //定义颜色的标示符

    finalintFONT_RED = 0x123;

    finalintFONT_GREEN = 0x124;

    finalintFONT_YELLOW = 0x125;

    EditText edit;

 

    /** Called  when the activity is first created. */

    @Override

    publicvoid onCreate(Bundle  savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        edit = (EditText) findViewById(R.id.editText);

    }

 

    @Override

    publicboolean onCreateOptionsMenu(Menu menu) {

        //添加字体大小的子菜单

        SubMenu sub = menu.addSubMenu("字体大小");

        sub.setIcon(R.drawable.q1);

        sub.setHeaderIcon(R.drawable.q1);

        sub.setHeaderTitle("选择字体大小");

        sub.add(0, FONT_2, 0, "2号字体");

        sub.add(0, FONT_4, 1, "4号字体");

        sub.add(0, FONT_10, 2, "10号字体");

        sub.add(0, FONT_16, 3, "16号字体");

        sub.add(0, FONT_12, 4, "12号字体");

 

        //添加谱图菜单

        menu.add(0, NORMAL, 0, "普通菜单");

 

        //添加字体颜色的菜单

        SubMenu sub2 = menu.addSubMenu("字体颜色");

        sub2.setIcon(R.drawable.q2);

        sub2.setHeaderIcon(R.drawable.q2);

        sub2.setHeaderTitle("选择字体颜色");

        sub2.add(0, FONT_GREEN, 0, "绿色");

        sub2.add(0, FONT_RED, 1, "红色");

        sub2.add(0, FONT_YELLOW, 2, "黄色");

        returntrue;

    }

 

    @Override

    publicboolean onOptionsItemSelected(MenuItem  item) {

        switch (item.getItemId()) {

        caseFONT_2:

            edit.setTextSize(2 * 2);

            break;

        caseFONT_4:

            edit.setTextSize(4 * 2);

            break;

        caseFONT_10:

            edit.setTextSize(10 * 2);

            break;

        caseFONT_12:

            edit.setTextSize(12 * 2);

            break;

        caseFONT_16:

            edit.setTextSize(16 * 2);

            break;

        caseNORMAL:

            Toast.makeText(MenuSampleActivity.this,"选择了普通菜单",

                    Toast.LENGTH_SHORT).show();

            break;

        caseFONT_GREEN:

            edit.setTextColor(Color.GREEN);

            break;

        caseFONT_RED:

            edit.setTextColor(Color.RED);

            break;

        caseFONT_YELLOW:

            edit.setTextColor(Color.YELLOW);

            break;

        }

        returntrue;

    }

 

}

XML代码

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

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

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:orientation="vertical" >

 

    <EditText

        android:id="@+id/editText"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="请输入"/>

       

</LinearLayout>

群贤毕至

访客