聊一聊android.support.v7包下的AppCompat

来源:互联网 发布:广西广电网络收费 编辑:程序博客网 时间:2024/05/04 10:31

其实之前大家在用AndroidStudio创建一个新的项目的时候有没有发现谷歌爸爸自动给你继承了AppComatActivity。而且有些时候你会发现莫名其妙的报很多错。然后就开始把谷歌爸爸帮你创建的代码大把大把的全部删掉,心里会默默吐槽:哇,这是个什么鬼啊,一运行就报错,老子要全部删掉。
其实当你回头细想的时候,你就会发现,为毛老子做出来的App感觉如此之low逼?为毛在5.0以上的版本下运行还是可以的嘛,怎么到了4.4.4以下丑出了新高度呢?


其实当你仔细去研究android.supot.v7你就会发现,其实谷歌爸爸为了推广Material Design真的是良苦用心啊。说白了AppCompat就是为了解决Android碎片化而生,说到这可能有很多小伙伴不明白了什么是碎片化呢?Android和iOS不一样,Android的rom厂商太多而且所使用的版本太过分散,可能有些人依然在用Android4.4而有些人已经用Android7.0。这样就导致了同样的一个Button可能在7.0上的显示效果和4.4上的显示效果完全不一样。而使用Appcampat就可以让4.4也有Material Design的效果。我们可以打开android.suport.v7.widget的源码目录。
android.suport.v7.widget的源码目录
大家有没有发现好东西,这些控件看起来好眼熟,看起来貌似都会用。


话不多说,下面开始撸码。
首先大家在创建工程的时候要注意一下这里。
如果你想让AS自动继承AppCompat就需要把Backwards Compatibility(向后兼容)勾选上。这样初始的MainActivity是自动继承AppCompatActivity。
创建工程

package sunnyit.com.appcompatdemo;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }}

在layout文件当中呢,我们就不再使用自带的控件了,而是使用android.support.v7.widget包下的AppCompat控件。代码如下:

<?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:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="sunnyit.com.appcompatdemo.MainActivity">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!" />    <android.support.v7.widget.AppCompatTextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello AppCompat!" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="确定" />    <android.support.v7.widget.AppCompatButton        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="确定" /></LinearLayout>

这样呢,既是运行在Android4.4的机器下呢,控件也会带有MaterialDesign效果。

0 0