暴走吧小草莓

导航

Android中的几个基本常用控件

Android 中常用的几大UI控件

1. TextView : 用于在界面中显示一段文本信息
<TextView
android:id="@+id/text_view" //给这个textview定义一个唯一标识符
android:layout_width="match_parent"
android:layout_height="wrap_parent" //所有的控件都有layout_width和layout_height属性
android:text="This is a text"
android:gravity="center" //修改文字的对齐方式(默认为左对齐).top.bottom,left,right,center等
/>

其他属性:android:textSize(单位为sp), android:textColor等 (了解更多属性,可查阅文档)

2. Button
activity_main.xml中:
<Button
android:id="@_+id/button1"
android:layout_height="wrap_parent"
android:layout_width="match_parent"
android:text="Button"
android:textAllCaps="false"
/>

Main_activity.java中:
Button b1 = (Button)findViewById(R.id.button1)
b1.setOnClickListener(new View.onClickListener()){
@Override
public void onClick(View v){
}
}

3. EditText:允许用户在EditText中输入和编辑内容,并可以在程序中对这些内容(findViewById(),getText())进行处理。
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

其他常用属性:android:hint用于指定一段提示性文本

4. ImageView:用于在UI中展示图片
<ImageView
android:id = "@+id/image_view"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:src="@drawable/image_1"
/>
如果想在程序中修改image,可使用setImageResource(R.drawable.image_2)方法

5.ProgressBar:用于在UI显示一个进度条
getVisibility()
setVisibility()
值:View.VISIBLE View.INVISIBLE View.GONE
View.INVISIBLE与View.GONE的区别:
都是进度条不可见,但View.INVISIBLE表示控件仍然存在,仍然占据着屏幕的空间,相当于透明;
View.GONE表示控件不再占用任何屏幕控件

6. AlertDialog: above the UI layout,屏蔽其他控件的交互能力.
用于显示一些很重要的信息,比如用户删除一些重要数据时出现。
AlertDialog不需要在layout中定义,只需要在java文件中声明。
举例如下:当用户点击按钮时,会弹出一个AlertDialog

public void onClick(View view) {
//定义一个AlertDialog的实例
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Alert");
alertDialog.setMessage("This is an important Msg");
//是否可以用Back键关闭对话框
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
});
alertDialog.show();
}
});


7. ProgressDialog: 与AlertDialog相似,above the UI, 屏蔽其他控件的交互。
但ProgressDialog会在对话框中显示一个进度条,用于表示当前操作比较耗时,让用户耐心等待。
ProgressDialog.Builder progressDialog = new ProgressDialog.Builder(MainActivity.this);
progressDialog.setTitle("ProgressDialog");
progressDialog.setMessage("This is a progressDialog");
progressDialog.setCancelable(true);
progressDialog.show();
注意,如果在setCancelable() 中传入了false ,表示ProgressDialog是不能通过Back键取消掉的,
这时你就一定要在代码中做好控制,当数据加载完成后必须要调用ProgressDialog的dismiss() 方法来关闭对话框,
否则ProgressDialog将会一直存在。

posted on 2018-01-21 12:59  暴走吧小草莓  阅读(647)  评论(0编辑  收藏  举报