设置组件在指定组件的右边
android:layout_toRightOf="@id/tv1"
设置在指定组件的下边
android:layout_below="@id/tv1"
设置右对齐父元素
android:layout_alignParentRight="true"
设置与指定组件右对齐
android:layout_alignRight="@id/tv1"
指定各个节点的排列方向
android:orientation="horizontal"
设置右对齐
android:layout_gravity="right"
当竖直布局时,只能左右对齐和水平居中,顶部底部对齐竖直居中无效
线性布局非常重要的一个属性:权重
android:layout_weight="1"
权重设置的是按比例分配剩余的空间
可以更改对齐方式
android:layout_gravity="bottom"
不能相对于其他组件布局
表格布局中的节点可以不设置宽高,因为设置了也无效
根节点中可以设置以下属性,表示让第1列拉伸填满屏幕宽度的剩余空间
android:stretchColumns="1"
直接指定组件的x、y坐标
android:layout_x="144dp"
android:layout_y="154dp"
Android提供的日志输出api
Log.v(TAG, "加油吧,童鞋们");
Log.d(TAG, "加油吧,童鞋们");
Log.i(TAG, "加油吧,童鞋们");
Log.w(TAG, "加油吧,童鞋们");
Log.e(TAG, "加油吧,童鞋们");
小例子:用户输入账号密码,勾选“记住账号密码”,点击登录按钮,登录的同时持久化保存账号和密码
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
if(cb.isChecked()){
......
}
//持久化保存数据
File file = new File("data/data/com.dimon.example/info.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write((name + "##" + pass).getBytes());
fos.close();
if(file.exists())
File file = new File("data/data/com.dimon.example/info.txt");
FileInputStream fis = new FileInputStream(file);
//把字节流转换成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
String[] s = text.split("##");
et_name.setText(s[0]);
et_pass.setText(s[1]);
getCacheDir()得到的file对象的路径是data/data/com.dimon.example/cache
系统管理应用界面的清除缓存,会清除cache文件夹下的东西,清除数据,会清除整个包名目录下的东西
storage/sdcard:4.3之后的sd卡路径
最简单的打开sd卡的方式
File file = new File("sdcard/info.txt");
写sd卡需要权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
读sd卡,在4.0之前不需要权限,4.0之后可以设置为需要
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
使用api获得sd卡的真实路径,部分手机品牌会更改sd卡的路径
Environment.getExternalStorageDirectory()
判断sd卡是否准备就绪
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize;
long totalBlocks;
long availableBlocks;
//获取当前系统版本的等级
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
blockSize = stat.getBlockSizeLong();
totalBlocks = stat.getBlockCountLong();
availableBlocks = stat.getAvailableBlocksLong();
}
else{
blockSize = stat.getBlockSize();
totalBlocks = stat.getBlockCount();
availableBlocks = stat.getAvailableBlocks();
}
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(formatSize(availableBlocks * blockSize));//剩余容量
}
private String formatSize(long size) {
return Formatter.formatFileSize(this, size);
}
用SharedPreference存储账号密码
//拿到一个SharedPreference对象
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//拿到编辑器
Editor ed = sp.edit();
//写数据
ed.putBoolean("name", name);
ed.commit();
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//从SharedPreference里取数据
String name = sp.getBoolean("name", "");
sb.append("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>");
//添加smss的开始节点
sb.append("<smss>");
.......
fos.write(sb.toString().getBytes());
XmlSerializer xs = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(), "backupsms.xml");
FileOutputStream fos = new FileOutputStream(file);
//给序列化器指定好输出流
xs.setOutput(fos, "utf-8");//enconding:指定用什么编码生成xml文件
//enconding:指定头结点中的enconding属性的值
xs.startDocument("utf-8", true);
xs.startTag(null, "smss");
......
xs.endTag(null, "smss");
//告诉序列化器,文件生成完毕
xs.endDocument();
InputStream is = getClassLoader().getResourceAsStream("weather.xml");
XmlPullParser xp = Xml.newPullParser();
int type = xp.getEventType();
事件类型主要有五种
如果获取到的事件类型不是END_DOCUMENT,就说明解析还没有完成,如果是,解析完成,while循环结束
while(type != XmlPullParser.END_DOCUMENT)
case XmlPullParser.START_TAG:
//获取当前节点的名字
if("weather".equals(xp.getName())){
citys = new ArrayList<City>();
}
else if("city".equals(xp.getName())){
city = new City();
}
else if("name".equals(xp.getName())){
//获取当前节点的下一个节点的文本
String name = xp.nextText();
city.setName(name);
}
else if("temp".equals(xp.getName())){
String temp = xp.nextText();
city.setTemp(temp);
}
else if("pm".equals(xp.getName())){
String pm = xp.nextText();
city.setPm(pm);
}
break;
case XmlPullParser.END_TAG:
if("city".equals(xp.getName())){
citys.add(city);
}
换行符也是文本节点
//arg1:数据库文件的名字
//arg2:游标工厂
//arg3:数据库版本
public MyOpenHelper(Context context, String name, CursorFactory factory, int version){}
必须定义一个构造方法:
数据库被创建时会调用:onCreate方法
数据库升级时会调用:onUpgrade方法
//创建OpenHelper对象
MyOpenHelper oh = new MyOpenHelper(getContext(), "person.db", null, 1);
//获得数据库对象,如果数据库不存在,先创建数据库,后获得,如果存在,则直接获得
SQLiteDatabase db = oh.getWritableDatabase();
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table person (_id integer primary key autoincrement, name char(10), phone char(20), money integer(20))");
}
//插入
db.execSQL("insert into person (name, phone, money) values (?, ?, ?);", new Object[]{"张三", 15987461, 75000});
//查找
Cursor cs = db.rawQuery("select _id, name, money from person where name = ?;", new String[]{"张三"});
protected void setUp() throws Exception {
super.setUp();
// 获取虚拟上下文对象
oh = new MyOpenHelper(getContext(), "people.db", null, 1);
}
//以键值对的形式保存要存入数据库的数据
ContentValues cv = new ContentValues();
cv.put("name", "王陆");
cv.put("phone", 1651646);
cv.put("money", 3500);
//返回值是改行的主键,如果出错返回-1
long i = db.insert("person", null, cv);
//返回值是删除的行数
int i = db.delete("person", "_id = ? and name = ?", new String[]{"1", "张三"});
ContentValues cv = new ContentValues();
cv.put("money", 25000);
int i = db.update("person", cv, "name = ?", new String[]{"赵四"});
//arg1:要查询的字段
//arg2:查询条件
//arg3:填充查询条件的占位符
Cursor cs = db.query("person", new String[]{"name", "money"}, "name = ?", new String[]{"张三"}, null, null, null);
while(cs.moveToNext()){
// 获取指定列的索引值
String name = cs.getString(cs.getColumnIndex("name"));
String money = cs.getString(cs.getColumnIndex("money"));
System.out.println(name + ";" + money);
}
try {
//开启事务
db.beginTransaction();
...........
//设置事务执行成功
db.setTransactionSuccessful();
} finally{
//关闭事务
//如果此时已经设置事务执行成功,则sql语句生效,否则不生效
db.endTransaction();
}
Cursor cs = db.query("person", null, null, null, null, null, null);
while(cs.moveToNext()){
String name = cs.getString(cs.getColumnIndex("name"));
String phone = cs.getString(cs.getColumnIndex("phone"));
String money = cs.getString(cs.getColumnIndex("money"));
//把读到的数据封装至Person对象
Person p = new Person(name, phone, money);
//把person对象保存至集合中
people.add(p);
}
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
for(Person p : people){
//创建TextView,每条数据用一个文本框显示
TextView tv = new TextView(this);
tv.setText(p.toString());
//把文本框设置为ll的子节点
ll.addView(tv);
}
<ScrollView>
......
</ScrollView>
Cursor cs = db.query("person", null, null, null, null, null, null, "0, 10");
第一个
//系统调用此方法,用来获知模型层有多少条数据
@Override
public int getCount() {
return people.size();
}
第二个:position:是return的View对象所对应的数据在集合中的位置
//系统调用此方法,获取要显示至ListView的View对象
//position:是return的View对象所对应的数据在集合中的位置
//position:本次getView方法调用所返回的view对象,在listView中是处于第几个条目,那么position的值就是多少
@Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("getView方法调用" + position);
TextView tv = new TextView(MainActivity.this);
//拿到集合中的元素
Person p = people.get(position);
tv.setText(p.toString());
//把TextView的对象返回出去,它会变成ListView的条目
return tv;
}
public class NewsAdapter extends ArrayAdapter<News> {
private int resourceId;
public NewsAdapter(Context context, int textViewResourceId, List<News> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
News news = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.newsTitleText = (TextView) view.findViewById(R.id.news_title);
view.setTag(viewHolder);//将ViewHolder存储在View中
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();//重新获取ViewHolder
}
//TextView newsTitleText = (TextView) view.findViewById(R.id.news_title);
viewHolder.newsTitleText.setText(news.getTitle());
return view;
}
class ViewHolder {
TextView newsTitleText;
}
}
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("警告");
builder.setMessage("愤怒香蕉更新啦!!");
builder.setPositiveButton("马上去水一贴", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "恭喜你水贴成功,现在程序退出", 0).show();
}
});
builder.setNegativeButton("下次再说", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "蕉姐这肥羊可以宰了呀", 0).show();
}
});
AlertDialog ad = builder.create();
ad.show();
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("选择你的性别");
final String[] items = new String[]{
"男", "女", "其他"
};
//-1表示没有默认选择
//点击侦听的导包要注意别导错
builder.setSingleChoiceItems(items, -1, new OnClickListener() {
//which表示点击的是哪一个选项
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "您选择了" + items[which], 0).show();
//对话框消失
dialog.dismiss();
}
});
builder.show();
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("请选择你欲修炼之功法");
final String[] items = new String[]{
"无相神功",
"仰望星空",
"千年杀",
"龙阳神功"
};
//true表示对应位置的选项被选了
final boolean[] checkedItems = new boolean[]{
true,
false,
false,
false,
};
builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() {
//点击某个选项,如果该选项之前没被选择,那么此时isChecked的值为true
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
}
});
builder.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
for(int i = 0;i < items.length; i++){
sb.append(checkedItems[i] ? items[i] + " " : "");
}
Toast.makeText(MainActivity.this, sb.toString(), 0).show();
}
});
builder.show();
将这些零碎的知识点笔记整理出来,方便以后查找翻看。(^__^) 谢谢阅读~