六、Android UI组件的使用

6.1常用UI组件
布局文件里可以用属性设置相应组件的属性值;Java端也可以使用组件的方法设置。
①dp(dip): device independent pixels(设备独立像素). 不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA 推荐使用这个,不依赖像素。
②px: pixels(像素). 不同设备显示效果相同,一般我们HVGA代表320x480像素,这个用的比较多。
③pt: point,是一个标准的长度单位,1pt=1/72英寸,用于印刷业,非常简单易用.
④sp: scaled pixels(放大像素). 主要用于字体显示best for textsize。

6.1.1 TextView (文本标签)
作用:显示文本内容;很少使用交互
代码如下:

<TextView
        android:id="@+id/one"                      //指定id
        android:layout_width="wrap_content"        //宽度
        android:layout_height="wrap_content"       //高度
        android:text="Hello World!"                //文本
        android:textColor="@color/colorPrimary"    //文本颜色
        android:textSize="50dp"/>            

6.1.2 EditText (编辑框)
Android页面内容输入(类似于web中的表单)
代码如下:

<EditText
Android:id="@+id/et_test1_number"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:hint=’“请输入手机号”
Android:inputType=“phone”>

6.1.3 Button(普通按钮)
代码如下:

<Android:id="@+id/btu"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“按钮”

6.1.4 ImageView(图片视图)
显示图片(HTML img)
代码如下:

<android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:src="@drawable/ic_launcher_forground"//设置前景图片
android:background_height="@drawable/ic_launcher_background"//设置背景图片

6.1.5 CheckBox (多选框)
页面多选按钮,:题选择;爱好。多个选项使用。
代码如下:

<checkBox
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="篮球"
        android:checked="true"/>        //默认是否勾选

//判断当前是否勾选
Boolean isChecked()
//设置CheckBox 是否勾选
void setChecked(boolean checked)
//设置选中状态改变的监听
void setOnCheckedChangeListener(OnCheckChangeLister listener)

6.1.6 RadioButton (单选按钮)
必须放到一个按钮组中
代码如下:

<RadioButton
        android:layout_width="wrap_parent"
        android:layout_height="wrap_content"
        android:cheached="true"
        android:text="男" />
</RadioButton>    

6.1.7 OptionMenu (选项菜单)
1)List itemoptionmenu在点击手机的menu键触发
2)List itemactivity:onCreateOptionsMenu(Menu menu)
3)添加menuItem 的两种方式:
①纯编码方式:menu.add(…)
②加载menu文件的方式:
MenuInflater menuInflater=getMenuInflater();
menuInfater.inflate(R.menu.main_option,menu);
4)Activity:onOptionsItemSelected(Menuitem item)
当选择某个菜单项的回调方法

6.1.8 ContextMenu (上下文菜单)
1)View: setOnCreateContextMenuListener(listener)//滚动窗口,为某个视图添加创建
ContextMenu的监听(需要长按触发)。
2)Activity: onCreateContextMenu(menu, view, menuInfo)//显示菜单的回调方法。
3)Activity: onContextItemSelected(MenuItem item)//当选择某个菜单项的回调。
4)Activity:registerForContextMenu()//将上下文菜单注册到某个组件上。

6.1.9 PopMenu (弹出菜单)
用于在某个组件上:
PopupMenu men=new PopupMenu(MainActivity.this,btn);
//创建一个菜单选项文件
在res文件下创建菜单文件夹/菜单选项文件
//加载菜单文件 men.getMenuInflater().inflate(R.menu.pop_menu,men.getMenu()); //给弹出添加事件
men.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() )
//显示弹出菜单
men.show();

猜你喜欢

转载自blog.csdn.net/weixin_45802395/article/details/113587952