TextView tv = new TextView(this);
SpannableStringBuilder style=new SpannableStringBuilder("这是测试111");
style.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.YELLOW), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.BLUE), 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(style);
如android:text=“test_ singleLine “,android:singleLine=”true” android:layout_width=“20dp”将只显示“t…”。如果不设置singleLine或者设置为false,文本将自动换行
45:android:text 设置显示文本.
46:android:textAppearance
设置文字外观。如 “?android:attr/textAppearanceLargeInverse”这里引用的是系统自带的一个外观,?表示系统是否有这种外观,否则使用默认的外观。可设置的值如下: textAppearanceButton/textAppearanceInverse/textAppearanceLarge/textAppearanceLargeInverse/textAppearanceMedium/textAppearanceMediumInverse/textAppearanceSmall/textAppearanceSmallInverse
47:android:textColor
设置文本颜色
48:android:textColorHighlight
被选中文字的底色,默认为蓝色
49:android:textColorHint
设置提示信息文字的颜色,默认为灰色。与hint一起使用。
50:android:textColorLink
文字链接的颜色.
51:android:textScaleX
设置文字之间间隔,默认为1.0f。
52:android:textSize
设置文字大小,推荐度量单位”sp”,如”15sp”
53:android:textStyle
设置字形[bold(粗体) 0, italic(斜体) 1, bolditalic(又粗又斜) 2] 可以设置一个或多个,用“|”隔开
54:android:typeface
设置文本字体,必须是以下常量值之一:normal 0, sans 1, serif 2, monospace(等宽字体) 3]
55:android:height
设置文本区域的高度,支持度量单位:px(像素)/dp/sp/in/mm(毫米)
56:android:maxHeight
设置文本区域的最大高度
57:android:minHeight
设置文本区域的最小高度
58:android:width
设置文本区域的宽度,支持度量单位:px(像素)/dp/sp/in/mm(毫米),与layout_width 的区别看这里。
59:android:maxWidth
设置文本区域的最大宽度
60:android:minWidth
设置文本区域的最小宽度
在程序里面可以通过isChecked方法来判断当前是否选中的状态。
准备数据,如果是固定的数据,可以在string下面新建一个arrays.xml。
在程序里面把数据设置到Spinner,示例代码如下:
final Spinner sp = (Spinner)this.findViewById(R.id.spinner);
//准备数据
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.colors, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//把数据设置到spinner
sp.setAdapter(adapter);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item);
adapter.add("red");
adapter.add("blue");
sp.getSelectedItem().toString()
可以通过设置incrementProgressBy()方法来增加进度,incrementProgressBy()方法来减少进度;当然对应的也有incrementSecondaryProgressBy()方法和incrementSecondaryProgressBy()方法。 增加设置正数,减少设置负数。
当然也可以直接使用setProgress和setSecondaryProgress方法来改变进度。
可以通过修改style来显示不同的进度样式,具体的Style可以从文档得到。
在创建Dialog的回调方法中,去真正创建DatePickerDialog,示例代码如下:
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
在创建Dialog的回调方法中,去真正创建TimePickerDialog,示例代码如下:
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
}
return null;
}
class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] mImageIds = {R.drawable.icon,R.drawable.icon,
R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon,
R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon};
public ImageAdapter(Context c) { mContext = c; }
public int getCount() { return mImageIds.length; }
public Object getItem(int position) { return position; }
public long getItemId(int position) { return position; }
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
}
如果要给Gallery设置风格的话,需要在res/values文件夹下面创建一个attrs.xml
然后在自定义的适配器里面,在构造方法里面,添加如下的代码:
TypedArray attr = mContext.obtainStyledAttributes(R.styleable.MyGallery);
mGalleryItemBackground = attr.getResourceId(
R.styleable.MyGallery_android_galleryItemBackground, 0);
imageView.setBackgroundResource(mGalleryItemBackground);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.autoc_item, new String[]{"abc","abd","abcd","bcd","bef"});
textView.setAdapter(adapter);
当然也可使用系统提供的布局,比如:android.R.layout.simple_dropdown_item_1line
上面的示例是输入单个值的,要想一次输入多个值,而且每个都想要有自动完成的功能该怎么办呢?可以使用MultiAutoCompleteTextView
首先在布局文件设置使用MultiAutoCompleteTextView。
然后在程序中,为他设置值,示例代码如下:
MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete);
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.autoc_item, new String[]{"abc","abd","abcd","bcd","bef"});
textView.setAdapter(adapter);
textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
TableLayout的常用属性如下:
android:stretchColumns :拉伸指定的列来填充一行的空白
android:collapseColumns :隐藏指定的列,隐藏多列用逗号分开,如“1,2”
android:shrinkColumns :收缩指定的列
android:layout_column :widget在一行里面所在的column的索引
android:layout_span :widget跨越的列数,也就是合并的列数
首先在布局文件里面配置使用GridView,
然后在程序里面,为它设置值,示例代码如下:
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) { mContext = c; }
public int getCount() {return mThumbIds.length; }
public Object getItem(int position) { return null;}
public long getItemId(int position) { return 0; }
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(0, 0,0,0);
imageView.setBackgroundColor(Color.RED);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
private Integer[] mThumbIds = {
R.drawable.icon, R.drawable.icon,
R.drawable.icon, R.drawable.icon,
R.drawable.icon, R.drawable.icon,
R.drawable.icon, R.drawable.icon
};
}
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,
int position, long id) {
Toast.makeText(TestWidgets.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
有了布局过后,就可以直接在程序里面设置Tab了,示例如下:
1:不再继承Activity,而是继承TabActivity,对于Tab布局的实现,现在已经不推荐使用了,建议改用Fragment来实现,但为了学习这个知识,还是沿用。
2:得到TabHost,示例代码如下:
TabHost tabHost = getTabHost();
Intent intent = new Intent().setClass(this, MyActivity.class);
intent.putExtra("showStr", "第一个tab");
Intent设置的Class就是点击tab,内容页显示出来的Activity。
4:创建一个TabSpec,也就是一个Tab的描述,包含一个tab加上下面的显示内容。简单点说,TabSpec就是一个完整的Tab页。示例代码如下:
TabHost.TabSpec spec = tabHost.newTabSpec("FirstTag")
.setIndicator("第一个Tab").setContent(intent);
tabHost.addTab(spec);
2:在res/drawable/ 下面,为每个tab增加一个选择器文件,用来告诉tab如何选择使用这些图片,比如my_tab1_selector.xml、 my_tab2_selector.xml,
3:在程序中,得到Resources对象,可以通过它来获取资源,示例代码如下:
Resources res = getResources();
spec = tabHost.newTabSpec("FirstTag").setIndicator(
"第一个Tab",res.getDrawable(R.drawable.my_tab1_selector))
.setContent(intent);
public class TestList extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this.setContentView(R.layout.TestList);
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, new String[]{"111","222","333"}));
}
protected void onListItemClick(ListView l,View v,int position,long id){
super.onListItemClick(l, v, position, id);
String s = ""+l.getItemAtPosition(position);
System.out.println("now click="+s);
}
}
setListAdapter(new ArrayAdapter(this,
android.R.layout. simple_list_item_single_choice, new String[]{"111","222","333}));
this.getListView().setItemsCanFocus(false);
this.getListView().setChoiceMode(ListView. CHOICE_MODE_SINGLE);
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_multiple_choice, new String[]{"111","222","333}));
this.getListView().setItemsCanFocus(false);
this.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
在ListView的Item的布局文件中
在java程序中
1:要继承ListActivity
2:使用Adapter来为List设置值
List list = new ArrayList();
Map map1 = new HashMap();
map1.put("userId","11");
map1.put("userName","11N");
map1.put("age","11");
list.add(map1);
Map map2 = new HashMap();
map2.put("userId","22");
map2.put("userName","22N");
map2.put("age","22");
list.add(map2);
setListAdapter(new SimpleAdapter(this, list,R.layout.list,new String[]{"userId","userName","age"}, new int[]{R.id.userId,R.id.userName,R.id.userAge}));
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
System.out.println("sssssssss===="+l.getItemAtPosition(position));
2:在代码里面使用菜单资源文件,示例如下:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.test_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.to_add:
Log.i("javass","now to add"); break;
case R.id.to_update:
Log.i("javass","now to update"); break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
public void myToAdd(MenuItem item) {
Log.i("javass","now in myToAdd");
}
this.registerForContextMenu(btnRun);
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo info) {
super.onCreateContextMenu(menu, v, info);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.test_menu, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id. new_file:
Log.i("onContextItemSelected", "now ruuuuuuuuuuu");
return true;
default: return super.onContextItemSelected(item);
}
}
菜单的事件处理跟前面的做法是一样的。
子菜单可以配合Option菜单或Content菜单使用。
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem mi = menu.findItem(R.id.create_new);
mi.setChecked(flag);
return true;
}
2:也可以在程序中设置,示例如下:
ActionBar actionBar = getActionBar();
actionBar.hide();
或者把android:actionLayout=“@layout/searchview” 换成:
android:actionViewClass="android.widget.SearchView"
示例如下:
ActionBar actionBar = getActionBar();
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setLogo(R.drawable.app_sample_code);
actionBar.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.app_sample_code));
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("确定要删除吗?")
.setCancelable(false)
.setPositiveButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(HelloWorldActivity.this, “dialog取消", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) { Toast.makeText(HelloWorldActivity.this,“dialog确定", Toast.LENGTH_LONG).show();
}
});
AlertDialog alert = builder.create();
final CharSequence[] items = { "红色", "绿色", "蓝色" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请选择颜色");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item],
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
final CharSequence[] items = { "红色", "绿色", "蓝色" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请选择颜色");
builder.setSingleChoiceItems(items, -1,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item],
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
final CharSequence[] items = { "红色", "绿色", "蓝色" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请选择颜色");
builder.setMultiChoiceItems(items, new boolean[]{false,false,false},new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getApplicationContext(), items[which], Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(HelloWorldActivity.this, "dialog确定", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}
);
AlertDialog alert = builder.create();
HandlerThread ht = new HandlerThread("MyThread");
Handler h = null;
if(!ht.isAlive()){
ht.start();
h = new Handler(ht.getLooper()){
public void handleMessage(Message msg) {
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
HelloWorldActivity.this.dismissDialog(1);
super.handleMessage(msg);
}
};
}
Message msg = h.obtainMessage();
msg.sendToTarget();
dialog = new ProgressDialog(HelloWorldActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("装载中...");
dialog.setCancelable(false);
dialog.setMax(10);
Handler h = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.arg1 < dialog.getMax()){dialog.setProgress(msg.arg1);}
else{dialog.dismiss();}}};
int num = 0;
Runnable r = new Runnable() {
public void run() {
Message msg = h.obtainMessage();
msg.arg1 = num++;
h.sendMessage(msg);
h.postDelayed(r, 1000L);
}};
2:在程序中启动Progress Bar,示例如下:
pb = (ProgressBar)HelloWorldActivity.this.findViewById(R.id.progress_bar);
pb.setMax(10);
pb.setVisibility(View.VISIBLE);
h.post(r);
在程序中获取这些对象,然后设置相应的属性,再显示出来,示例如下:
Context mContext = HelloWorldActivity.this;
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.my_dialog);
dialog.setTitle("自己订制的Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("欢迎使用本系统");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
//最后显示出来
dialog.show();
Handler h = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
//使用what来区分是什么样的消息
switch (msg.what){
case 1 :
//这里进行消息的处理
break;
default :
//这里进行消息的处理
}
}};
int what = 0;
Runnable r = new Runnable() {
public void run() {
Message msg = h.obtainMessage();
msg.obj = "1234567";//传递的参数
msg.what = what;
what++;
h.sendMessage(msg);
h.postDelayed(r, 1000L);
}};
HandlerThread ht = new HandlerThread("MyThread");
Handler h = null;
ht.start();
h = new Handler(ht.getLooper()){
public void handleMessage(Message msg) {
super.handleMessage(msg);
//这里真正处理消息
Toast.makeText(getApplicationContext(),"msg="+msg.obj,Toast.LENGTH_LONG).show();
}
};
Message msg = h.obtainMessage();
msg.obj="test message";
msg.sendToTarget();
Toast t = Toast.makeText(HelloWorldActivity.this,"okok", Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP|Gravity.LEFT, 5,10);
t.show();
订制Toast,需订制布局文件,这里使用上一个示例的布局文件来示例,程序写法如下:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.my_dialog,
(ViewGroup) findViewById(R.id.layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("欢迎您的到来!");
Toast t = new Toast(HelloWorldActivity.this);
t.setView(layout);
t.setGravity(Gravity.CENTER|Gravity.LEFT, 5,10);
t.show();
//获取NotificationManager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
//设置在status bar上显示的信息条
int icon = R.drawable.app_sample_code;
CharSequence tickerText = "请注意";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
//设置在status 列表里面显示的信息,以及点击的事件
CharSequence contentTitle = "重要通知";
CharSequence contentText = "测试";
Intent notificationIntent = new Intent(HelloWorldActivity.this, T2.class);
PendingIntent contentIntent = PendingIntent.getActivity(HelloWorldActivity.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(HelloWorldActivity.this, contentTitle, contentText, contentIntent);
//发出通知
mNotificationManager.notify(1, notification);
mNotificationManager.cancel(1);//1就是前面notity时传递的id值,必须唯一
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification. FLAG_SHOW_LIGHTS;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.my_dialog);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, "重要通知");//这个前面的layout里面没有,可以注掉,也可以自己去layout里面添加上
contentView.setTextViewText(R.id.text, "测试");
//设置在通知信息列表里面显示的视图
otification.contentView = contentView;
//设置点击通知信息时触发的事件
notification.contentIntent = contentIntent;