天天看點

Android04Android04

Android04

學生管理系統界面的顯示

  1. findAll()查到所有學生資料;
    cursor.getString(cursor.getColumnIndex(columnName));

2.顯示是一個LinearLayout

資料太多了,用滾動布局 (隻能有一個子控件)

豎向滾動布局<ScrollView ></ScrollView>
橫向滾動布局<HorizontalScrollView ></HorizontalScrollView>
           
<ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:id="@+id/ll_result"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>
           

3.顯示資料邏輯 > 1. 建立文本TextView 2. 内容是查出的學生資訊 3. 得到要顯示的LinearLayout,添加進文本 4.清除原來資料

LinearLayout.removeAllView();

listview引入

是系統給我們提供的一個可以顯示很多個item的控件

這個控件合理的控制了界面的顯示,即使有1000000萬個item要顯示他也能扛的住

MVC

M:model 資料模型
V:view 界面展現
C:controller 控制器
           

listview的使用

使用步驟
  1. 在布局xml檔案聲明listview控件
  2. 在java代碼找到listview控件,設定資料擴充卡setAapter();
  3. 可以設定ListView條目的點選事件,listview.setOnItemClickListener();

擴充卡的操作

  1. 寫一個類,繼承BaseAdapter
  2. 重寫四個方法
    getCount()确定listview裡面有多少個條目
    getView(int positon)傳回某個位置要顯示的view對象

    positon是目前的位置,位置從0開始

    converView表示的是複用的視圖,用于優化ListView處理

學生管理系統的更新

<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>

/**
* 擷取資料庫的全部記錄,重新整理顯示資料
*/
private void refreshData() {
final List<Student> students = dao.findAll();
//      ll_result.removeAllViews();// 把原來的資料給清除
//      for (Student student : students) {
//          TextView tv = new TextView(this);
//          tv.setText(student.toString());
//          ll_result.addView(tv);
//      }
lv.setAdapter(new BaseAdapter() {

@Override
public int getCount() {//擷取一共有多少個條目
    return students.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LinearLayout ll = new LinearLayout(MainActivity.this);
    ll.setOrientation(LinearLayout.HORIZONTAL);
    ll.setGravity(Gravity.CENTER_VERTICAL);
    ImageView iv = new ImageView(MainActivity.this);
    String sex = students.get(position).getSex();
    if("male".equals(sex)){
        iv.setImageResource(R.drawable.nan);
    }else {
        iv.setImageResource(R.drawable.nv);
    }
    TextView tv = new TextView(MainActivity.this);
    tv.setText( students.get(position).getName());
    ll.addView(iv, 30, 30);
    ll.addView(tv);
    return ll;
}
           

listview的優化的原理

就是講變成gc垃圾的Item,在放到最後使用

public View getView(int position, View convertView, ViewGroup parent) 
           

listview的優化

view view = null;
if(convertView == null){
    view = new TextView(MainActivity.this);
}else{
    view = convertView;
}
           

采用打氣筒建立view對象

View view = null;
if (convertView == null) {
    // 把一個布局xml檔案轉化成view對象
    view = View.inflate(MainActivity.this, R.layout.item, null);
} else {
    view = convertView;
}
           

通知資料擴充卡重新整理資料

/**
 * 擷取資料庫的全部記錄,重新整理顯示資料
 */
private void refreshData() {
    students = dao.findAll();
    if (adapter == null) {
        adapter = new MyAdapter();
        lv.setAdapter(adapter);
    }else{
        //通知資料擴充卡更新資料,而不是new出來新的資料擴充卡
        adapter.notifyDataSetChanged();
    }
}
           

常見對話框

确定取消對話框

public void click01(View view) {
    AlertDialog.Builder builder = new Builder(this);
    builder.setTitle("警告:");
    builder.setMessage("若練此功,必先自宮,是否繼續?");
    builder.setPositiveButton("确定自宮", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "啊....", 0).show();
        }
    });
    builder.setNegativeButton("想想再說", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "如不自宮,一定不成功", 0).show();
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();
}
           

單選對話框

public void click02(View view) {
    AlertDialog.Builder builder = new Builder(this);
    builder.setTitle("請選擇您的性别:");
    final String[] items = { "男", "女", "中性" };
    builder.setSingleChoiceItems(items, -1, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "您的性别:" + items[which], 0)
                    .show();
        }
    });
    builder.setNegativeButton("取消選擇", null);
    builder.show();
}
           

多選對花框

public void click03(View view) {
    AlertDialog.Builder builder = new Builder(this);
    builder.setTitle("請選擇您愛吃的水果");
    final String[] items = new String[] { "黃瓜", "蘋果", "香蕉", "鳳梨鳳梨蜜" };
    final boolean[] checkedItems = new boolean[] { true, true, false, false };
    builder.setMultiChoiceItems(items, checkedItems,
            new OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which,
                        boolean isChecked) {
                    Toast.makeText(MainActivity.this,
                            items[which] + isChecked, 0).show();
                    checkedItems[which] = isChecked;
                }
            });
    builder.setNegativeButton("取消選擇", null);
    builder.show();
}
           

進度對話框

public void click04(View view) {
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setTitle("提醒");
    pd.setMessage("正在加載資料...請稍後");
    pd.show();
    new Thread() {
        public void run() {
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            pd.dismiss();
        };
    }.start();
}
           

進度條對話框

public void click05(View view) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMax(100);
        pd.setTitle("提醒");
        pd.setMessage("正在加載資料...請稍後");
        pd.show();
        new Thread() {
            public void run() {
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    pd.setProgress(i);
                }
                pd.dismiss();
            };
        }.start();
    }
}
           

删除學生資訊的對話框

view.findViewById(R.id.iv_delete).setOnClickListener(
    new OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new Builder(MainActivity.this);
            builder.setTitle("提醒");
            builder.setMessage("是否删除這條學生資訊?");
            builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Student student = students.get(position);
                    String name = student.getName();
                    // 從資料庫删除資料.
                    dao.delete(name);
                    Toast.makeText(MainActivity.this, "資料被删除了", 0)
                            .show();
                    // 更新ui界面.
                    refreshData();
                }
            });
            builder.setNegativeButton("取消", null);
            builder.show();
        }
    });
return view;
}
           

快速拖動

android:fastScrollEnabled="true"
           

資料庫的另外一種增删改查的方法

用API進行增删改查

1.增

ContentValues values = new ContentValues();
values.put(columnName, value);
db.insert(tableName,null,values);
2.删

db.delete(tableName, "name=?", new String[]{value});
3.改

ContentValues values = new ContentValues();
values.put(columnName, value);
db.update(tableName, values, "name=?", new String[] { value });
4.查

Cursor cursor = db.query(tableName, 需要查詢的列, "name=?", new String[]{value},null,null, 排序);
           

資料庫的事物

db.beginTransaction(); // 開啟事務
    try {
        // 模拟轉賬的操作
        db.execSQL("update account set money=money-100 where name='zhangsan'");
        s.endsWith("haha");
        db.execSQL("update account set money=money+100 where name='lisi'");
        db.setTransactionSuccessful();// 設定事務執行成功
    } finally {
        db.endTransaction();
    }
           

常見資料擴充卡-simple和arrayAdapter

simpleAdapter

<!--TextView不是LinearLayout-->
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:textSize="20sp"
    android:textColor="#66ff0000"
    android:layout_height="wrap_content" >
</TextView>

public class MainActivity extends Activity {
    private ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
        String[] objects = new String[]{"Animation","App","content","Media","NFC","OS"};
        lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item, objects));
    }
}
           

arrayAdapter

public class MainActivity extends Activity {
    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
        List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("icon", R.drawable.ic_menu_preferences);
        map1.put("name", "功能設定");
        data.add(map1);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("icon", R.drawable.ic_menu_recent_history);
        map2.put("name", "時鐘設定");
        data.add(map2);
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("icon", R.drawable.ic_menu_refresh);
        map3.put("name", "同步設定");
        data.add(map3);
        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("icon", R.drawable.ic_menu_report_image);
        map4.put("name", "圖檔設定");
        data.add(map4);
        lv.setAdapter(new SimpleAdapter(this, data, R.layout.item, new String[]{"icon","name"}, new int[]{R.id.iv,R.id.tv}));
    }
           

Android下的圖形動畫

log.xml

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false" >

    <item
        android:drawable="@drawable/logo1"
        android:duration="850">
    </item>
    <item
        android:drawable="@drawable/logo2"
        android:duration="850">
    </item>
    <item
        android:drawable="@drawable/logo3"
        android:duration="850">
    </item>

</animation-list>
           

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".MainActivity" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/iv" />

</RelativeLayout>


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView iv = (ImageView) findViewById(R.id.iv);
    iv.setBackgroundResource(R.drawable.logo);
    AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
    anim.start();//開始播放動畫
}
           

應用程式的國際化

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

    <string name="app_name">13_i18n</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">hello world!</string>

</resources>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/flag" />

</RelativeLayout>
           

樣式和主題

<resources>
    <style name="text_content_style">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#0000ff</item>
        <item name="android:textSize">20sp</item>
    </style>
    <style name="text_title_style" parent="@style/text_content_style">
         <item name="android:textSize">25sp</item>
    </style>

    <style name="text_content_style.sub">
        <item name="android:textSize">28sp</item>
    </style>       

</resources>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        style="@style/text_title_style"
        android:text="@string/hello_world" />

    <TextView
        style="@style/text_content_style"
        android:text="@string/hello_world" />

    <TextView
        style="@style/text_content_style.sub"
        android:text="@string/hello_world" />

    <TextView
        style="@style/text_content_style"
        android:text="@string/hello_world" />

    <TextView
        style="@style/text_content_style"
        android:text="@string/hello_world" />

    <TextView
        style="@style/text_content_style"
        android:text="@string/hello_world" />

</LinearLayout>