01、 UI基础入门

189 阅读4分钟

1 UI基础入门

1.1 详解HelloWorld

  • Activity
    MainActivity
    onCreate()
    setContentView(R.layout.activity_main):设置内容视图
    R:为每一个资源文件按类别分配一个索引,使程序员可以通过R.类名.资源名去操作对应的资源
  • 布局文件
    activity_main.xml
  • 清单文件
    AndroidManifest.xml

1.2 布局基础

  • 常用布局
    • 线性布局(LinearLayout)
    • 相对布局(RelativeLayout)
    • 帧布局(FrameLayout)
    • 表格布局(TableLayout)
    • 网格布局(GridLayout)
    • 约束布局(ConstraintLayout )
  • 添加布局
    1.利用xml文件设计
    2.使用Java代码添加

1.3 线性布局

  • 布局重要属性
    • android:layout_width="match_parent"     宽度
      android:layout_height="match_parent"    高度
      android:layout_padding="2dp"            内边距
      android:layout_margin="2dp"             外边距
      
  • 线性布局重要属性
    • android:orientation="vertical"      方向, vertical(竖直)、horizontal(水平)
      android:layout_weight="2"           权重
      android:layout_gravity="center"     相对于父容器的摆放位置
      

1.4 相对布局

  • 相对布局重要属性
    • 相对于父容器(取值:true、false)如:
      android:layout_centerInParent 相对父容器上下左右居中
      android:layout_alignParentLeft 在父容器的左边
      android:layout_alignParentRight 在父容器的右边
      android:layout_alignParentTop 在父容器的上边
      android:layout_alignParentBottom 在父容器的下边
      android:layout_centerHorizontal 相对父容器水平居中
      android:layout_centerVertical 相对父容器垂直居中
    • 相对于其他控件(取值:其他控件id)如:
      1.在参照物的某边
      android:layout_toLeftOf
      android:layout_toRightOf
      android:layout_above
      android:layout_below
      2.和参照物的某边线对齐
      android:layout_alignTop
      android:layout_alignBottom
      android:layout_alignLeft
      android:layout_alignRight

2 UI基础控件

2.1 View

  • 处理文本内容的view(TextView)
  • 被点击的view(Button)
  • 处理图片内容的view(ImageView)
  • 接收用户信息输入的view(EditText)
  • 进度条类的view(ProgressBar)

2.2 TextView

  • 重要属性
        android:text="@string/long_text"            文本
        android:textSize="22sp"                     字体大小
        android:textColor="@color/teal_200"         字体颜色
        android:lineSpacingExtra="15dp"             行间距(具体大小)
        android:lineSpacingMultiplier="1"           行间距(倍数)
        ​
        android:lines="1"                           设置行数
        android:single="true"                       设置单行
        android:ellipsize="start"                   设置省略号的位置(start、middle、end、                                              marquee)
        android:focusable="true"                    设置可以获取焦点
        android:focusableInTouchMode="true"         设置在触摸时获取焦点
        android:marqueeRepeatLimit="marquee_forever" 设置跑马灯持续运行
        ```
    
  • 能完成的效果
    • 对长文本进行显示处理
      • 处理方式1:使用ScrollView(滚动条)
        <?xml version="1.0" encoding="utf-8"?>
        <ScrollView 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"
            tools:context=".TextActivity">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/long_text"
                android:textSize="22sp"
                android:textColor="@color/teal_200"
                android:lineSpacingMultiplier="1.5"/>
        </ScrollView>
        
      • 处理方式2:跑马灯
        <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"
            tools:context=".TextActivity">
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/long_text"
                
                android:singleLine="true"
                android:ellipsize="marquee"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:marqueeRepeatLimit="marquee_forever"/>
        </LinearLayout>
        ​
        注:需要设置textView.setSelected(true);否则字体不会开始滚动
        
    • 支持HTML代码
    • 内容有样式、链接效果

2.3 EditText

  • 重要属性
     android:inputType="phone"           文本属性
     android:hint="Email Address"        提示文字,一般显示灰色
     android:textColorHint="#FF03DAC5"   提示文字的颜色
     android:maxLength="12"              文本输入的最长长度
    

2.4 Button

  • 自定义内部类实现点击事件

     public class ButtonActivity extends AppCompatActivity {
         private static final String TAG = "ButtonActivity";
         private Button btn1;
         
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_button);
     
             MyButtonClick myButtonClick = new MyButtonClick();
             btn1 = findViewById(R.id.btn1);
             btn1.setOnClickListener(myButtonClick);
         }
    
         class MyButtonClick implements View.OnClickListener{
             @Override
             public void onClick(View v) {
                 Log.e(TAG, "onClick: 自定义内部类实现点击事件");
             }
         }
     }
    
  • 匿名内部类实现点击事件(适用于有唯一操作的按钮)

     public class ButtonActivity extends AppCompatActivity {
     
         private static final String TAG = "ButtonActivity";
         private Button btn2;
     
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_button);
     
             btn2 = findViewById(R.id.btn2);
             btn2.setOnClickListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View v) {
                     Log.e(TAG, "匿名内部类实现点击事件");
                 }
             });
         }
     }
    
  • 通过当前Activity(类)去实现点击事件接口

     public class ButtonActivity extends AppCompatActivity implements View.OnClickListener {
     
         private static final String TAG = "ButtonActivity";
         private Button btn3;
     
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_button);
     
             btn3 = findViewById(R.id.btn3);
             btn3.setOnClickListener(this);
         }
     
         @Override
         public void onClick(View v) {
             Log.e(TAG, "通过当前Activity(类)去实现点击事件接口");
         }
     }
    
  • 在xml文件中绑定(已弃用)

     public class ButtonActivity extends AppCompatActivity {
     
         private static final String TAG = "ButtonActivity";
     
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_button);
         }
     
         public void myClick(View view){
             switch (view.getId()){
                 case R.id.btn4:
                     Log.e(TAG, "在xml文件中绑定btn4");
                     break;
                 case R.id.btn5:
                     Log.e(TAG, "在xml文件中绑定btn5");
                     break;
             }
         }
     }
    
     <?xml version="1.0" encoding="utf-8"?>
     <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=".ButtonActivity">
     
         <Button
             android:id="@+id/btn4"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="在xml文件中绑定"
             android:onClick="myClick"/>
     
         <Button
             android:id="@+id/btn5"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="在xml文件中绑定2"
             android:onClick="myClick"/>
     </LinearLayout>
    

2.5 ImageView、ImageButton

  • 常用属性
       android:src="@mipmap/add_photo"             指定前景图片资源
       android:background="@mipmap/bg"             设置背景
    

2.6 ProgressBar

  • 进度条:默认样式是转圈,修改样式需设置风格
        style="?android:attr/progressBarStyleHorizontal"        风格
        android:progress="30"           设置进度值
        android:max="200"               设置最大值,默认100
        android:indeterminate="true"    设置进度条一直滚动
    
  • 进度条模拟下载
     <?xml version="1.0" encoding="utf-8"?>
     <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"
         tools:context=".ProgressBarActivity"
         android:orientation="vertical">
     ​
         设置进度条一直滚动
         <ProgressBar
             android:layout_width="300dp"
             android:layout_height="wrap_content"
             style="@style/Widget.AppCompat.ProgressBar.Horizontal"
             android:progress="20"
             android:max="100"
             android:indeterminate="true"/>
     ​
         <ProgressBar
             android:id="@+id/progress"
             android:layout_width="300dp"
             android:layout_height="wrap_content"
             style="@style/Widget.AppCompat.ProgressBar.Horizontal"
             android:max="100"/>
     </LinearLayout>
    
     public class ProgressBarActivity extends AppCompatActivity {
     ​
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_progress_bar);
             ProgressBar progressBar = findViewById(R.id.progress);
             
             //在Android中,4.0以后是不允许在非UI线程中进行UI操作(UI线程也叫主线程)
             //进度条是个例外
             new Thread(){
                 @Override
                 public void run() {
                     for(int i = 1; i <= 100; i++) {
                         progressBar.setProgress(i);
                         try {
                             Thread.sleep(100);
                         } catch (InterruptedException e) {
                             e.printStackTrace();
                         }
                     }
                 }
             }.start();
         }
     }
    

2.7 案例完善

  • Toast(吐司,无焦点提示)

    • Toast.makeText(MainActivity.this,"用户名或密码为null",Toast.LENGTH_SHORT).show();
      参数1:环境 上下文      参数2:提示性文本       参数3:提示持续时间
      
  • 案例

    • public class MainActivity extends AppCompatActivity {
      ​
          private EditText etName;
          private EditText etPassword;
          private Button button;
          private ProgressBar progress;
      ​
          @SuppressLint("WrongViewCast")
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      ​
              etName = findViewById(R.id.etName);
              etPassword = findViewById(R.id.etPassword);
              button = findViewById(R.id.btn);
              progress = findViewById(R.id.progress);
      ​
              button.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      if (etName.getText().toString().equals("") || etPassword.getText().toString().equals("")){
                          Toast.makeText(MainActivity.this,"用户名或密码为null",Toast.LENGTH_SHORT).show();
                      } else {
                          new Thread(){
                              @Override
                              public void run() {
                                  for(int i = 0; i <= 100; i++){
                                      progress.setProgress(i);
                                      try {
                                          Thread.sleep(30);
                                      } catch (InterruptedException e) {
                                          e.printStackTrace();
                                      }
                                  }
                              }
                          }.start();
                      }
                  }
              });
          }
      }
      

2.8 CheckBox(复选框控件)

  • 系统封装的复选框控件
  • 两种状态:选中、未选中
  • 常用方法:
    • 设置状态:setChecked(Boolean b)
    • 获取状态:isChecked()
    • 状态监听:setOnCheckedChangeListener()
       checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               //可以根据状态改变,做很多事情
               Log.e(TAG, "onCheckedChanged: isChecked = "+isChecked);
           }
       });
      

2.9 RadioButton(单选控件)

  • 可以和RadioGroup一起使用,只能选择一个
  • 与CheckBox区别
    • 通过点击无法变为未选中
    • 一组RadioButton,只能选择一个
    • 在大部分UI框架中默认都已圆形表示

2.10 SeekBar(拖动条)

  • 常用方法
    • 设置进度:setProgress()
    • 监听事件:seekBar.setOnSeekBarChangeListener()
       seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
           @Override
           public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
               //进度值发生改变时触发
           }
       ​
           @Override
           public void onStartTrackingTouch(SeekBar seekBar) {
               //按住SeekBar时会触发
           }
       ​
           @Override
           public void onStopTrackingTouch(SeekBar seekBar) {
               //放开SeekBar时触发
           }
       });
      

2.11 ToggleButton(开关按钮)和Switch(开关)

  • ToggleButton(开关按钮)
     android:disabledAlpha       设置按钮在禁用时的透明度
     android:textOff             按钮没有被选中时显示的文字
     android:textOn              按钮被选中时显示的文字 另外,除了这个我们还可以自己写个selector,然后设置下Background属性即
    
  • Switch(开关)
     android:showText            设置on/off的时候是否显示文字,boolean
     android:splitTrack          是否设置一个间隙,让滑块与底部图片分隔,boolean
     android:switchMinWidth      设置开关的最小宽度
     android:switchPadding       设置滑块内文字的间隔
     android:switchTextAppearance设置开关的文字外观,暂时没发现有什么用...
     android:textOff             按钮没有被选中时显示的文字
     android:textOn              按钮被选中时显示的文字
     android:textStyle           文字风格,粗体,斜体写划线那些
     android:track               底部的图片
     android:thumb               滑块的图片
     android:typeface            设置字体,默认支持这三种:sans, serif, monospace;除此以外还可以使用 其他字体文件(*.ttf),
                                 首先要将字体文件保存在assets/fonts/目录下,不过需要在Java代码中设置: 
     Typeface typeFace =Typeface.createFromAsset(getAssets(),"fonts/HandmadeTypewriter.ttf"); textView.setTypeface(typeFace);
    

3 Android基本布局

3.1 帧布局(FrameLayout)

  • 重要属性
     android:layout_gravity="center"             控件重力
     android:foreground="@color/teal_200"        前景
     android:foregroundGravity="center"          前景重力
     ​
     注:foreground需要和foregroundGravity一起使用
    
     <FrameLayout 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"
         tools:context=".layout.FrameLayoutActivity"
         android:foreground="@mipmap/ic_launcher" 
         android:foregroundGravity="left|bottom">
     ​
         <TextView
             android:layout_width="400dp"
             android:layout_height="400dp"
             android:background="#ff0000"
             android:layout_gravity="center"/>
     ​
         <TextView
             android:layout_width="300dp"
             android:layout_height="300dp"
             android:background="#00ff00"
             android:layout_gravity="center"/>
     ​
         <TextView
             android:layout_width="200dp"
             android:layout_height="200dp"
             android:background="#0000ff"
             android:layout_gravity="center"/>
     ​
     </FrameLayout>
    

3.2 表格布局(TableLayout)

  • 重要属性
     android:stretchColumns="1,2"        设置可伸展的列(索引,所有可用*)
     android:shrinkColumns="1,2"         设置可收缩的列
     android:collapseColumns="0,1"       设置可隐藏的列
     注:
         如果直接在TableLayout中添加控件,那么控件将和父容器等宽
         如果想让控件出现在同一行,那么这些控件的外层一定要加一对<TableRow>
         在TableRow中的控件,宽度都是默认wrap_content
    
    • 案例(计算器)
      <TableLayout 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"
          tools:context=".layout.TableLayoutActivity"
          android:stretchColumns="*"
          android:shrinkColumns="*">
          <EditText
              android:layout_width="match_parent"
              android:layout_height="50dp"
              android:background="@color/teal_200"/>
          <TableRow>
              <Button android:text="7"/>
              <Button android:text="8"/>
              <Button android:text="9"/>
              <Button android:text="/"/>
          </TableRow>
          <TableRow>
              <Button android:text="4"/>
              <Button android:text="5"/>
              <Button android:text="6"/>
              <Button android:text="*"/>
          </TableRow>
          <TableRow>
              <Button android:text="1"/>
              <Button android:text="2"/>
              <Button android:text="3"/>
              <Button android:text="-"/>
          </TableRow>
          <TableRow>
              <Button android:text="0"/>
              <Button android:text="."/>
              <Button android:text="+"/>
              <Button android:text="="/>
          </TableRow>
          <Button android:text="clear"/>
      </TableLayout>
      

3.3 网格布局(GridLayout)

  • 常用属性

     android:orientation="horizontal"            设置排列方式
     android:layout_gravity="center"             设置对齐方式
     android:rowCount="6"                        设置网格布局有6行
     android:columnCount="4"                     设置网格布局有4列
     android:layout_row="4"                      设置组件在第4行
     android:layout_column="4"                   设置组件在第4列
     android:layout_rowSpan="2"2行
     android:layout_columnSpan="2"2列
     注:
         使用layout_rowSpanlayout_rowSpan和layout_columnSpan属性时,需要设置android:layout_gravity="fill"才可生效
    
  • 案例(计算器)

     <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:rowCount="6"
         android:columnCount="4"
         android:layout_gravity="center"
         tools:context=".layout.GridLayoutActivity">
     ​
         <EditText
             android:layout_height="50dp"
             android:layout_columnSpan="4"
             android:layout_gravity="fill"
             android:background="@color/teal_200" />
         <Button android:text="1"/>
         <Button android:text="2"/>
         <Button android:text="3"/>
         <Button android:text="/"/>
         <Button android:text="4"/>
         <Button android:text="5"/>
         <Button android:text="6"/>
         <Button android:text="*"/>
         <Button android:text="7"/>
         <Button android:text="8"/>
         <Button android:text="9"/>
         <Button android:text="-"/>
         <Button
             android:text="0"
             android:layout_columnSpan="2"
             android:layout_gravity="fill"/>
         <Button android:text="."/>
         <Button
             android:text="+"
             android:layout_rowSpan="2"
             android:layout_gravity="fill"/>
         <Button
             android:text="="
             android:layout_columnSpan="3"
             android:layout_gravity="fill"/>
     </GridLayout>
    

4 综合案例:选餐

gitee.com/maojiu0825/…