Android炫酷應用300例讀書筆記一

在圖書館看到這本書,實例比較多父晶,但是代碼沒有隨書附贈,需要發(fā)郵件才能索取弄跌,大概是因為本書的代碼占了書的一半版面左右的原因吧甲喝。因此簡單手動過了一遍,我的命名習慣跟書中不一樣铛只,所以都是按自己的習慣去命名的埠胖。這本書最大的好處就是實例夠多吧糠溜,做了總比較全面結(jié)。部分內(nèi)容由于應用廣泛并且博客解釋更詳細所以沒有用書上的例子而是貼出我覺得寫得還不錯的鏈接直撤,另诵冒,部分代碼由于android studio提示廢棄,因此修改了部分代碼谊惭。還有汽馋,書中部分代碼只有參考意義,實際使用中還是會有問題圈盔,待優(yōu)化豹芯。
代碼運行環(huán)境為android7真機。
第1章UI布局
1.使用純java代碼創(chuàng)建應用UI界面

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        setContentView(linearLayout);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        final TextView textView = new TextView(this);
        textView.setText("Hello World");
        textView.setTextSize(20);
        Button button = new Button(this);
        button.setText("刷新內(nèi)容");
        button.setTextSize(20);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setText("Hello,Android 炫酷應用實例驱敲!\n當前日期: " + new Date());
            }
        });
        linearLayout.addView(textView);
        linearLayout.addView(button);
    }
}

2.使用自定義View代替布局文件

public class MainActivity extends AppCompatActivity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(new MyView(this));
        super.onCreate(savedInstanceState);

    }
    class MyView extends View{
        private Paint mPaint;
        EmbossMaskFilter mEmbossMaskFilter;

        public MyView(Context context) {
            super(context);
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setColor(Color.RED);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(64);
            mPaint.setTextSize(800);

            float[] direction = new float[]{1,1,1};
            float light = 0.05f;
            float specular = 5;
            float blur = 13;
            mEmbossMaskFilter = new EmbossMaskFilter(direction,light,specular,blur);
            mPaint.setMaskFilter(mEmbossMaskFilter);

        }
        @Override
        protected void onDraw(Canvas canvas){
            super.onDraw(canvas);
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;
            int height = dm.heightPixels;
           canvas.drawText("炫",width/10,height/2+70,mPaint);
        }
    }
}

另在manifest中加入如下代碼铁蹈,否則字無法顯示。

 android:hardwareAccelerated="false"

具體位置如下所示众眨。


image.png

另外握牧,這段代碼在我的小米手機上可以正常顯示,但是在魅族手機上無法顯示文字娩梨,猜測是因為魅族手機上需要設置hardware相關部分才可以正常顯示沿腰。

深入學習可稍微看下這篇:
Canvas的drawText方法詳解
https://blog.csdn.net/u011118524/article/details/78128737

3.使用TableLayout布局多個輸入框
java代碼

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

xml代碼

<?xml version="1.0" encoding="utf-8"?>
<TableLayout
    android:id="@+id/table_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingStart="20dp"
    android:paddingEnd="20dp"
    android:paddingTop="20dp"
    android:paddingBottom="20dp"
   >
    <TableRow>
        <TextView
            android:text="用戶名 :"
            android:textSize="20dp"/>
        <EditText
            android:layout_width="300dp"
            android:hint="請輸入用戶名"
            android:inputType="textPersonName"
            android:textSize="20dp"/>
    </TableRow>

    <TableRow>
        <TextView
            android:text="密碼 :"
            android:textSize="20dp"/>
        <EditText
            android:layout_width="300dp"
            android:hint="請輸入密碼"
            android:inputType="textPassword"
            android:textSize="20dp"/>
    </TableRow>
    <TableRow>
        <TextView
            android:text="確認密碼 :"
            android:textSize="20dp"/>
        <EditText
            android:layout_width="300dp"
            android:hint="請再次輸入密碼"
            android:inputType="textPassword"
            android:textSize="20dp"/>
    </TableRow>
    <TableRow>
        <TextView
            android:text="電話號碼 :"
            android:textSize="20dp"/>
        <EditText
            android:layout_width="300dp"
            android:hint="請輸入電話號碼"
            android:inputType="phone"
            android:textSize="20dp"/>
    </TableRow>
    <TableRow>
        <TextView
            android:text="郵箱地址 :"
            android:textSize="20dp"/>
        <EditText
            android:layout_width="300dp"
            android:hint="請輸入郵箱地址"
            android:inputType="textEmailAddress"
            android:textSize="20dp"/>
    </TableRow>

</TableLayout>

4.使用TextInputLayout管理輸入框提示
首先,在gradle中添加依賴support:design狈定。由于目前手上電腦android studio版本較老還是2.x版本颂龙,這里使用的是

compile 'com.android.support:design:26.0.0-alpha1'

比較省心的添加方法是File->Project Structure->dependencies,然后找design。


image.png

xml代碼

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_centerInParent="true"
    android:orientation="vertical">
  <android.support.design.widget.TextInputLayout
      android:id="@+id/account_wrapper"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="4dp">
      <EditText
          android:id="@+id/account_edit_text"
          android:layout_width="match_parent"
          android:layout_height="45dp"
          android:layout_marginStart="16dp"
          android:layout_marginEnd="16dp"
          android:layout_marginTop="20dp"
          android:paddingStart="12dp"
          android:paddingEnd="12dp"
          android:gravity="center_vertical"/>
  </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/pw_wrapper"
        app:passwordToggleEnabled="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp">
        <EditText
            android:id="@+id/password_edit_text"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:layout_marginTop="20dp"
            android:paddingStart="12dp"
            android:paddingEnd="12dp"
            android:gravity="center_vertical"
            android:inputType="textPassword"/>
    </android.support.design.widget.TextInputLayout>
    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="30dp"
        android:background="@color/colorPrimary"
        android:onClick="onClickBtn"
        android:text="登錄"
        android:textColor="#fff"
        android:textSize="20dp"/>
</LinearLayout>

注意:這里書上的代碼少了一句導致小眼睛圖標無法顯示纽什。

app:passwordToggleEnabled="true"

java代碼

public class MainActivity extends AppCompatActivity {
    private EditText mAccountEditText,mPasswordEditText;
    private TextInputLayout mAccountTextInputLayout,mPasswordTextInputLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAccountEditText = (EditText) findViewById(R.id.account_edit_text);
        mPasswordEditText = (EditText) findViewById(R.id.password_edit_text);
        mAccountTextInputLayout = (TextInputLayout) findViewById(R.id.account_wrapper);
        mPasswordTextInputLayout = (TextInputLayout) findViewById(R.id.pw_wrapper);

        mAccountTextInputLayout.setHint("請輸入用戶名稱");
        mPasswordTextInputLayout.setHint("請輸入用戶密碼");
    }

    public void onClickBtn(View view){
        String account = mAccountEditText.getText().toString();
        String pw = mPasswordEditText.getText().toString();
        if (account.length() < 1){
            mAccountTextInputLayout.setError("用戶名不能為空");
        }else if (pw.length() < 1){
            mPasswordTextInputLayout.setError("用戶密碼不能為空");
        }else {
            mAccountTextInputLayout.setErrorEnabled(false);
            mPasswordTextInputLayout.setErrorEnabled(false);
            // to do
            //登錄
        }
    }
}

更多參考鏈接:
3分鐘學會TextInputLayout
http://www.reibang.com/p/a9b48dee86e0

這應該是最夠用的TextInputLayout了
http://www.reibang.com/p/2b0cd9e9a4d9

TextInputLayout詳解
http://www.reibang.com/p/4c99e4c0fe90

5.GridLayout創(chuàng)建計算器按鍵布局

java代碼

public class MainActivity extends AppCompatActivity {
    private GridLayout mGridLayout;
    private String[] mTitleString = new String[]{"7","8","9","÷",  "4","5","6","x",  "1","2","3","-",
    ".","0",",","+"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mGridLayout = (GridLayout) findViewById(R.id.grid_layout);
        for (int i = 0;i<mTitleString.length;i++){
            Button button = new Button(this);
            button.setText(mTitleString[i]);
            button.setTextSize(36);
            //指定該按鈕所在行號 2表示從第3行開始計算
            GridLayout.Spec row = GridLayout.spec(i / 4 + 2);
            //指定按鈕所在列號
            GridLayout.Spec column = GridLayout.spec(i % 4);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(row,column);
            mGridLayout.addView(button,layoutParams);
        }
    }


}

xml

<GridLayout
    android:id="@+id/grid_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnCount="4"
    android:rowCount="6">
    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:layout_columnSpan="4"
        android:layout_marginStart="2pt"
        android:layout_marginEnd="2pt"
        android:background="#fff"
        android:padding="3pt"
        android:text="12 + 56 = 68"
        android:textColor="#000"
        android:textSize="48dp"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_columnSpan="4"
        android:text="清除"
        android:textSize="28dp"/>
    
</GridLayout>

6.使用RelativeLayout按相鄰關系布局

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <TextView
        android:id="@+id/center_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@mipmap/center"/>
    <TextView
        android:id="@+id/top_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/center_view"
        android:layout_alignStart="@id/center_view"
        android:background="@mipmap/top"/>
    <TextView
        android:id="@+id/bottom_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/center_view"
        android:layout_alignStart="@id/center_view"
        android:background="@mipmap/bottom"/>
    <TextView
        android:id="@+id/left_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toStartOf="@id/center_view"
        android:layout_alignTop="@id/center_view"
        android:background="@mipmap/left"/>
    <TextView
        android:id="@+id/right_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/center_view"
        android:layout_alignTop="@id/center_view"
        android:background="@mipmap/right"/>
</RelativeLayout>

圖片是隨便截圖做的措嵌。


bottom.png
center.png
left.png
right.png
top.png

7.使用ConstraintLayout在右下角布局

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/top"/>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/left"
        app:layout_constraintLeft_toRightOf="@id/imageView"
        app:layout_constraintTop_toBottomOf="@id/imageView"/>
</android.support.constraint.ConstraintLayout>

關鍵點是這句話

app:layout_constraintLeft_toRightOf="@id/imageView"
app:layout_constraintTop_toBottomOf="@id/imageView"

8.使用TableLayout拉伸控件填充容器

<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:stretchColumns="1">
    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="500dp"
            android:background="#eee0a0"
            android:gravity="center"
            android:text="A(默認)"
            android:textAlignment="center"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#00aa00"
            android:gravity="center"
            android:text="B(拉伸)"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#00FFFF"
            android:gravity="center"
            android:text="C(默認)"/>
    </TableRow>

</TableLayout>

9.使用TableLayout縮小控件適應容器

<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:collapseColumns="1,2"
    android:stretchColumns="0">
    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="500dp"
            android:background="#eee0a0"
            android:gravity="center"
            android:text="A(默認)"
           />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#00aa00"
            android:gravity="center"
            android:text="B(默認)"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#00AAFF"
            android:gravity="center"
            android:text="C(默認)"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#CCFFFF"
            android:gravity="center"
            android:text="D(默認)"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#BB00FF"
            android:gravity="center"
            android:text="E(默認)"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#FFFF00"
            android:gravity="center"
            android:text="F(默認)"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#00FFFF"
            android:gravity="center"
            android:text="G(默認)"/>
    </TableRow>

</TableLayout>

B和C實際是被隱藏了。


image.png

10.使用LinearLayout縱向居中對齊控件

public class MainActivity extends AppCompatActivity {
    private Button mButton1,mButton2,mButton3;
    private LinearLayout mLinearLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLinearLayout = (LinearLayout) findViewById(R.id.linear_layout);
        mButton1 = (Button) findViewById(R.id.button1);
        mButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLinearLayout.setGravity(Gravity.START |Gravity.CENTER_VERTICAL);
            }
        });
        mButton2 =  (Button) findViewById(R.id.button2);
        mButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLinearLayout.setGravity(Gravity.CENTER |Gravity.CENTER_VERTICAL);
            }
        });
        mButton3 =  (Button) findViewById(R.id.button3);
        mButton3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLinearLayout.setGravity(Gravity.END |Gravity.CENTER_VERTICAL);
            }
        });
    }
}

xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="靠左對齊"/>
        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="居中對齊"/>
        <Button
            android:id="@+id/button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="靠右對齊"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="start|center_vertical">
        <ImageView
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:src="@mipmap/left"/>
        <ImageView
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:src="@mipmap/center"/>
        <ImageView
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:src="@mipmap/right"/>
    </LinearLayout>
</LinearLayout>

11.使用LinearLayout按權(quán)重分配控件空間芦缰。
這個懶得打了企巢,就是10中的3個button的寫法,就是android:layout_weight的分配让蕾。

12.使用ConstraintLayout平分剩余空間

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="200dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="84dp"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/top"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/imageView2"/>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/left"
        app:layout_constraintLeft_toRightOf="@+id/imageView"
        app:layout_constraintRight_toLeftOf="@+id/imageView3"/>

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/center"
        app:layout_constraintLeft_toRightOf="@+id/imageView2"
        app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>

默認情況下浪规,3個控件會形成一個水平方向上的鏈式布局,因此會平分空間涕俗。
13.使用ConstraintLayout無間隙布局控件
ImageView節(jié)點下加入一句代碼即可罗丰。

app:layout_constraintHorizontal_chainStyle="packed"
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="200dp">

    <ImageView
        app:layout_constraintHorizontal_chainStyle="packed"
        android:id="@+id/imageView"
        android:layout_width="84dp"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/top"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/imageView2"/>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/left"
        app:layout_constraintLeft_toRightOf="@+id/imageView"
        app:layout_constraintRight_toLeftOf="@+id/imageView3"/>

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/center"
        app:layout_constraintLeft_toRightOf="@+id/imageView2"
        app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>

14.使用TableLayout和適配器創(chuàng)建選項卡

public class MainActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private LayoutInflater mLayoutInflater;
    private List<String> mTitleList = new ArrayList<>();
    private List<View> mViewList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) findViewById(R.id.view_paper);
        initView();
        mTitleList.add("京東");
        mTitleList.add("天貓");
        mTitleList.add("360");
        mTitleList.add("搜狐");
        mTitleList.add("百度");

        MyAdapter myAdapter = new MyAdapter(mViewList,mTitleList);
        mViewPager.setAdapter(myAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    private class MyWebViewClient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){
           view.loadUrl(request.getUrl().toString());
            return true;
        }
    }


    private void initView(){
        mLayoutInflater = LayoutInflater.from(this);
        String[] webSites = {"https://www.jd.com","https://www.tmall.com","https://www.#","https://www.sohu.com","https://www.baidu.com"};
        for (int i= 1;i <= webSites.length ; i ++){
            View view = mLayoutInflater.inflate(R.layout.item_layout,null);
            WebView webView = (WebView) view.findViewById(R.id.web_view);
            webView.loadUrl(webSites[i-1]);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebViewClient(new MyWebViewClient());
            mViewList.add(view);
        }
    }
}
public class MyAdapter extends PagerAdapter {
    private List<View> mViewList;
    private List<String> mTitleList;

    public MyAdapter(List<View> viewList ,List<String> titleList){
        mViewList = viewList;
        mTitleList = titleList;
    }

    @Override
    public int getCount() {
        return mViewList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(mViewList.get(position));
        return mViewList.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(mViewList.get(position));
    }
    @Override
    public CharSequence getPageTitle(int position) {
        return mTitleList.get(position);
    }
}

activity_main

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <android.support.v4.view.ViewPager
        android:id="@+id/view_paper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

item_layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

最后,manifest中加上權(quán)限

 <uses-permission android:name="android.permission.INTERNET"/>

15.使用TabLayout和Fragment創(chuàng)建選項卡

public class TabFragment extends Fragment {
    private String mTitle;
    private String[] mMovies = {"親密的陌生人","善意的謊言","光榮歲月"};

    public void setTitle(String title){
        mTitle = title;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                              Bundle savedInstanceState) {
        ImageView imageView = new ImageView(getContext());
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        if (mTitle.contains(mMovies[0])){
            imageView.setImageResource(R.mipmap.image1);
        }else if (mTitle.contains(mMovies[1])){
            imageView.setImageResource(R.mipmap.image2);
        }else  if (mTitle.contains(mMovies[2])){
            imageView.setImageResource(R.mipmap.image3);
        }
        return imageView;
    }
}
public class MainActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private String[] mTitle = {"親密的陌生人","善意的謊言","光榮歲月"};
    private String[] mData = {"親密的陌生人","善意的謊言","光榮歲月"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView(){
        mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) findViewById(R.id.view_paper);
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public CharSequence getPageTitle(int position) {
                return mTitle[position % mTitle.length];
            }

            @Override
            public Fragment getItem(int position) {
                TabFragment tabFragment = new TabFragment();
                tabFragment.setTitle(mData[position % mTitle.length]);
                return tabFragment;
            }

            @Override
            public int getCount() {
                return mTitle.length;
            }
        });
        //ViewPager關聯(lián)TabLayout
        mTabLayout.setupWithViewPager(mViewPager);
        //setOnTabSelectedListener 廢棄 因此使用 addOnTabSelectedListener
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //切換ViewPaper
                mViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        app:tabGravity="center"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@color/colorPrimaryDark"
        app:tabTextColor="@color/colorPrimary"/>
    <android.support.v4.view.ViewPager
        android:id="@+id/view_paper"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
image1.png
image2.png
image3.png

16.使用FrameLayout創(chuàng)建縱向選項卡
java代碼如下再姑。


import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Created by Administrator on 2019/9/23.
 */

public class WebFragment extends Fragment {
    private WebView mWebView;
    private String mUrl = "https://www.baidu.com";

    @Override
    public void setArguments(Bundle arguments){
        mUrl = arguments.getString("url");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mWebView =new WebView(inflater.getContext());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(mUrl);
        mWebView.setWebViewClient(new WebViewClient());
        return mWebView;
    }

    public void reloadView(){
        mWebView.loadUrl(mUrl);
    }
}
public class TitleFragment extends Fragment {
    private String[] mTitles = {"百度","京東","天貓","搜狗","微軟","新浪","淘寶"};
    private String[] mUrl = {"https://www.baidu.com","https://www.jd.com","https://www.tmall.com",
            "https://www.sogou.com", "https://www.microsoft.com","https://www.sina.com.cn",
    "https://www.taobao.com"};
    private String mTitle;
    private TextView mTextView;
    private List<String> mTitleList = new ArrayList<>();
    private List<String> mUrlList = new ArrayList<>();

    @Override
    public void setArguments(Bundle arguments){
        mTitle = arguments.getString("title");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mTextView = new TextView(inflater.getContext());
        mTextView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        mTextView.setText(mTitle);
        mTextView.setTextSize(18);
        mTextView.setPadding(0,25,0,25);
        mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
        return mTextView;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        for (int i= 0;i<mTitles.length;i++){
            mTitleList.add(mTitles[i]);
            mUrlList.add(mUrl[i]);
        }
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WebFragment webFragment = (WebFragment) getFragmentManager().
                        findFragmentById(R.id.web_fragment_container);
                Bundle bundle = new Bundle();
                bundle.putString("url",mUrlList.get(mTitleList.indexOf(mTextView.getText())));
                webFragment.setArguments(bundle);
                webFragment.reloadView();
            }
        });
    }
}
public class MainActivity extends AppCompatActivity {
    private String[] mTitles = {"百度","京東","天貓","搜狗","微軟","新浪","淘寶"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getFragmentManager().beginTransaction().add(R.id.web_fragment_container,new WebFragment()).commit();
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
        for (int i= 0;i<mTitles.length;i++){
            FrameLayout frameLayout = new FrameLayout(this);
            frameLayout.setLayoutParams(new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            frameLayout.setId(View.generateViewId());
            linearLayout.addView(frameLayout);
            TitleFragment titleFragment = new TitleFragment();
            Bundle bundle = new Bundle();
            bundle.putString("title",mTitles[i]);
            titleFragment.setArguments(bundle);
            getFragmentManager().beginTransaction().add(frameLayout.getId(),titleFragment).commit();
        }
    }


}

xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="80dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"/>

    <FrameLayout
        android:id="@+id/web_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

17.使用TabHost創(chuàng)建橫向選項卡
由于TabActivity 廢棄萌抵,所以跳過。

18.使用AbsoluteLayout實現(xiàn)平移控件
由于AbsoluteLayout廢棄,所以跳過绍填。

19.使用FrameLayout實現(xiàn)閃爍控件
FrameLayout子視圖的位置排列取決于它們各自的android:layout_gravity屬性霎桅。

注意,本書中的Handle的用法是會引起內(nèi)存泄漏的讨永,但是目前學習目的只是學習ui相關滔驶,因此我的代碼也沒有對這一部分進行修改。

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/text_view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:width="300dp"
        android:height="300dp"
        android:background="#f00"/>
    <TextView
        android:id="@+id/text_view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:width="260dp"
        android:height="260dp"
        android:background="#0f0"/>
    <TextView
        android:id="@+id/text_view3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:width="220dp"
        android:height="220dp"
        android:background="#00f"/>
    <TextView
        android:id="@+id/text_view4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:width="180dp"
        android:height="180dp"
        android:background="#ff0"/>
    <TextView
        android:id="@+id/text_view5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:width="140dp"
        android:height="140dp"
        android:background="#f0f"/>
    <TextView
        android:id="@+id/text_view6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:width="100dp"
        android:height="100dp"
        android:background="#0ff"/>
</FrameLayout>
public class MainActivity extends AppCompatActivity {
    private static final int MESSAGE = 0x123;
    private int mCurrentColor =0;
    private final int[] mColors = new int[]{
            Color.rgb(122,122,0),Color.rgb(0,122,122),Color.rgb(122,0,0),
            Color.rgb(255,255,0),Color.rgb(0,255,255),Color.rgb(255,0,0)
    };
    final int[] mIds = new int[]{R.id.text_view1,R.id.text_view2,R.id.text_view3,
            R.id.text_view4,R.id.text_view5,R.id.text_view6};
    private TextView[] mTextViews = new TextView[mIds.length];
    private Handler mHandler = new Handler(){
      public void handleMessage(Message msg){
          if (msg.what == MESSAGE){
              for (int i = 0; i < mIds.length; i++){
                  mTextViews[i].setBackgroundColor(mColors[(i+ mCurrentColor) % mIds.length]);
              }
              mCurrentColor++;
          }
          super.handleMessage(msg);
      }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        for (int i = 0; i < mIds.length; i++){
            mTextViews[i] = (TextView) findViewById(mIds[i]);
        }
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(MESSAGE);
            }
        },0,300);
    }

}

20.自定義FrameLayout創(chuàng)建翻頁卷邊動畫
由于代碼不全卿闹,因此使用網(wǎng)上的鏈接去學習揭糕。關鍵是使用貝塞爾曲線quadTo實現(xiàn)翻頁卷邊。
Android自定義View——從零開始實現(xiàn)書籍翻頁效果(一)
http://www.reibang.com/p/d02362fbd9f2

自定義View基礎 - 最易懂的自定義View原理系列(1)
http://www.reibang.com/p/146e5cec4863
淺談安卓自定義view(一):制作一個最最最簡單的自定義view
https://blog.csdn.net/wsyizmao/article/details/78491422
貝塞爾曲線學習總結(jié)
http://www.reibang.com/p/f9c15dc9c38d
自定義view系列之——Android貝塞爾曲線--基礎篇
http://www.reibang.com/p/3b2ac05ae3c7

第2章常用控件
21.在TextView中創(chuàng)建空心文字

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:shadowColor="@color/colorAccent"
        android:shadowDx="0"
        android:shadowDy="0"
        android:shadowRadius="15"
        android:text="炫酷應用實例"
        android:textColor="#fff"
        android:textSize="52sp"/>
</LinearLayout>

22.在TextView中實現(xiàn)上文下圖的布局

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableBottom="@drawable/image"
        android:text="重慶市人民大禮堂锻霎,位于重慶市渝中區(qū)人民路173號著角,于1951年6月破土興建,1954年4月竣工旋恼,是一座仿古民族建筑群吏口,是重慶十大文化符號,是中國傳統(tǒng)宮殿建筑風格與西方建筑的大跨度結(jié)構(gòu)巧妙結(jié)合的杰作冰更,也是重慶的標志建筑物之一产徊。"
        android:textSize="20sp"/>
</LinearLayout>
image.png
image.png

23.在TextView中為文本添加超鏈接

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autoLink="all"
        android:text="百度官網(wǎng): https://www.baidu.com/"
        android:textSize="20sp"/>
</LinearLayout>

24.在自定義View中實現(xiàn)垂直滾動文本

public class ScrollTextView extends AppCompatTextView {
    private int mCurLines;
    private int mLines;
    private int mPerLines = 10;
    private int mLineHeight;
    private int mHeight;
    private int i;
    private boolean bScroll = true;

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            scrollTo(0,mLineHeight * mCurLines);
        }
    };
    public ScrollTextView(Context context) {
        super(context);
        init();
    }
    public ScrollTextView(Context context,AttributeSet attrs) {
        super(context,attrs);
        init();
    }

    public void init(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if (!bScroll) {
                        continue;
                    }
                    if (mHeight != 0){
                        mCurLines = mCurLines + 1;
                        if (mCurLines == (mLines - 3) * mPerLines){
                            mCurLines = 0;
                        }
                        Message message = mHandler.obtainMessage();
                        message.arg1 = mCurLines;
                        message.sendToTarget();
                        try {
                            if (mCurLines == 0){
                                Thread.sleep(1000);
                            }else {
                                Thread.sleep(150);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onSizeChanged(int w,int h,int oldw,int oldh){
        super.onSizeChanged(w, h, oldw, oldh);
        mCurLines = 0;
        postInvalidate();
        mLineHeight = getLineHeight() / mPerLines;
        mLines = getLineCount() -1;
        mHeight = getLineCount() *mLineHeight *mPerLines;
        int height = getMeasuredHeight();
        i = (int) (height /getTextSize());
        if (mLines <= i){
            bScroll = false;
        }else {
            bScroll = true;
        }
    }
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

}
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <com.cc.uisample.ScrollTextView
        android:padding="10dp"
        android:background="#DEFFAC"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:text="AAAAAAAAAAA\nBBBBBBBBBBB\nCCCCCCCCCCC\nDDDDDDDDDDDD\nEEEEEEEEEEEE\nFFFFFFFFFFFF\nGGGGGGGGGGGG\nHHHHHHHHHHHH\n"
        android:textSize="20sp"/>
</LinearLayout>
image.png

參考鏈接:
Android ScrollTo()、ScrollBy()用法
http://www.reibang.com/p/31635550aabb
Android scrollTo蜀细,scrollBy 正數(shù)卻相反方向移動理解
https://blog.csdn.net/pmslrxe/article/details/83016058
坐標跟android屏幕坐標相反的原因關鍵在于scroll是滾動不是移動舟铜。

25.在EditText中指定輸入法的數(shù)字軟鍵盤

public class MainActivity extends AppCompatActivity {
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.edit_text);
    }

    public void onClickBtn1(View view){
        mEditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
    }

    public void onClickBtn2(View view){
        mEditText.setInputType(EditorInfo.TYPE_CLASS_TEXT);
    }

}

xml這里我是使用ConstraintLayout,因為可以拖拽所以比較方便审葬。

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:onClick="onClickBtn1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="顯示數(shù)字軟鍵盤"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintRight_toLeftOf="@+id/guideline"
        android:layout_marginRight="8dp"/>

    <Button
        android:id="@+id/button2"
        android:onClick="onClickBtn2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="顯示字母軟鍵盤"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"/>

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="90dp"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"/>
</android.support.constraint.ConstraintLayout>

26.禁止在EditText中插入非字符表情符號
參考鏈接:
Android中EditText禁止輸入表情
http://www.reibang.com/p/a2b4eec5ed16

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="30dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>


</android.support.constraint.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.edit_text);
        mEditText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                        Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
                Matcher emojiMatcher = emoji.matcher(charSequence);
                if (emojiMatcher.find()) {
                    Toast.makeText(MainActivity.this, "不支持輸入表情", Toast.LENGTH_SHORT).show();
                    return "";
                }
                return null;
            }
        }});
    }

}

27.使用AutoCompleteTextView實現(xiàn)自動提示

public class MainActivity extends AppCompatActivity {
    private AutoCompleteTextView mAutoCompleteTextView;
    private String[] mStrings = {"AAAAAAAA","BBBBBBBBBB","CCCCCCC","DDDDDDDD","EEEEEEEE","FFFFFF"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.auto_text_view);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,
                mStrings);
        mAutoCompleteTextView.setAdapter(adapter);
        mAutoCompleteTextView.setThreshold(1);//表示從第一個字符開始顯示
    }

}
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <AutoCompleteTextView
        android:id="@+id/auto_text_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="30dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"/>


</android.support.constraint.ConstraintLayout>

更多用法參考鏈接:
AutoCompleteTextView
http://www.reibang.com/p/aeae6a201a7b

28.使用SearchView和ListView實現(xiàn)過濾輸入
首先manifest中加入權(quán)限深滚,如果是android6以上版本還需要動態(tài)申請權(quán)限奕谭,但是這里我偷下懶涣觉,選擇手動打開。

    <uses-permission android:name="android.permission.READ_CONTACTS"/>

xml代碼如下

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

java代碼如下

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private SearchView mSearchView;
    private ListView mListView;
    private SimpleCursorAdapter mAdapter;
    private Cursor mCursor;
    private String[] mStrings = new String[]{ContactsContract.RawContacts._ID,
            ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mCursor = getContentResolver().query(
                ContactsContract.RawContacts.CONTENT_URI,mStrings,null,null,null
        );
        mAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,mCursor,
                new String[]{ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY},
                new int[]{android.R.id.text1},0);
        mListView = (ListView) findViewById(R.id.list_view);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mSearchView.setQuery(
                        ((Cursor) mAdapter.getItem(i)).getString(1),false);
            }
        });
        mSearchView = (SearchView) findViewById(R.id.search_view);
        mSearchView.setIconifiedByDefault(true);
        mSearchView.onActionViewExpanded();
        mSearchView.setSubmitButtonEnabled(true);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                //在Toast中顯示搜索框文本內(nèi)容
                Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                String SQL = ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY +
                        " LIKE '%" + s + "%'" + " OR " + ContactsContract.RawContacts.SORT_KEY_PRIMARY +
                        " LIKE '%" + s +  "%'";

                Log.d(TAG,"SQL = " + SQL);
                mCursor = getContentResolver().query( ContactsContract.RawContacts.CONTENT_URI,
                        mStrings,SQL,null,null);
                Log.d(TAG,"mCursor = " + mCursor.toString());

                mAdapter.swapCursor(mCursor);
                return false;
            }
        });
    }

}

SQL 這里容易寫錯血柳,要注意官册。

  String SQL = ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY +
                        " LIKE '%" + s + "%'" + " OR " + ContactsContract.RawContacts.SORT_KEY_PRIMARY +
                        " LIKE '%" + s +  "%'";

參考鏈接:
Contacts數(shù)據(jù)的訪問
http://www.reibang.com/p/67dcf08dd1d4

搜索框(SearchView)的功能與用法

SearchView的使用
http://www.reibang.com/p/00cb87a2964f

29.在EditText右端設置輸入提示內(nèi)容和圖標
xml文件如下

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="賬戶名稱:"/>

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"/>
</LinearLayout>

隨便在百度上找一個燈泡的圖片。


image.png
led.jpg
public class MainActivity extends AppCompatActivity {
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.edit_text);
        Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.led, null);
        drawable.setBounds(0,0,72,72);
        mEditText.setError("必須填寫",drawable);
    }
}
1.jpg

如果不設置自己的圖標难捌,android將顯示一個感嘆號圖標膝宁。

public class MainActivity extends AppCompatActivity {
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.edit_text);
        mEditText.setError("必須填寫");
    }

}
2.jpg

30.通過自定義Shape創(chuàng)建不同的圓角按鈕

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">
    <Button
        android:layout_margin="5dp"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="@drawable/button_selector"
        android:textSize="20dp"
        android:text="AAAAAA"/>
    <Button
        android:layout_margin="5dp"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="@drawable/button_selector"
        android:textSize="20dp"
        android:text="BBBBBB"/>
    <Button
        android:layout_margin="5dp"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="@drawable/button_selector"
        android:textSize="20dp"
        android:text="CCCCCC"/>
    <Button
        android:layout_margin="5dp"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="@drawable/button_selector"
        android:textSize="20dp"
        android:text="DDDDDD"/>
</LinearLayout>

button_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
        android:state_pressed="true"/>
    <item android:drawable="@drawable/button_normal"
          android:state_pressed="false"/>
</selector>

button_pressed.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:topRightRadius="30dp"
             android:bottomRightRadius="30dp"/>
    <solid android:color="#CD00CD"/>
</shape>

button_normal.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:topRightRadius="30dp"
             android:bottomRightRadius="30dp"/>
    <solid android:color="#98F5FF"/>
</shape>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市根吁,隨后出現(xiàn)的幾起案子员淫,更是在濱河造成了極大的恐慌,老刑警劉巖击敌,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件介返,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機圣蝎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進店門刃宵,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人徘公,你說我怎么就攤上這事牲证。” “怎么了关面?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵坦袍,是天一觀的道長。 經(jīng)常有香客問我等太,道長键闺,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任澈驼,我火速辦了婚禮辛燥,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘缝其。我一直安慰自己挎塌,他們只是感情好,可當我...
    茶點故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布内边。 她就那樣靜靜地躺著榴都,像睡著了一般。 火紅的嫁衣襯著肌膚如雪漠其。 梳的紋絲不亂的頭發(fā)上嘴高,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天,我揣著相機與錄音和屎,去河邊找鬼拴驮。 笑死,一個胖子當著我的面吹牛柴信,可吹牛的內(nèi)容都是我干的套啤。 我是一名探鬼主播,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼随常,長吁一口氣:“原來是場噩夢啊……” “哼潜沦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起绪氛,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤唆鸡,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后枣察,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體争占,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡袄琳,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了燃乍。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片唆樊。...
    茶點故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖刻蟹,靈堂內(nèi)的尸體忽然破棺而出逗旁,到底是詐尸還是另有隱情,我是刑警寧澤舆瘪,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布片效,位于F島的核電站,受9級特大地震影響英古,放射性物質(zhì)發(fā)生泄漏淀衣。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一召调、第九天 我趴在偏房一處隱蔽的房頂上張望膨桥。 院中可真熱鬧,春花似錦唠叛、人聲如沸只嚣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽册舞。三九已至,卻和暖如春障般,著一層夾襖步出監(jiān)牢的瞬間调鲸,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工挽荡, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留藐石,地道東北人。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓徐伐,卻偏偏與公主長得像贯钩,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子办素,可洞房花燭夜當晚...
    茶點故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內(nèi)容

  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,358評論 0 17
  • 31.通過設置背景圖像創(chuàng)建立體的質(zhì)感按鈕搜索質(zhì)感按鈕祸穷,隨便找一個http://image.baidu.com/se...
    梧葉已秋聲閱讀 746評論 0 0
  • -01- 這是一個開始性穿。 此時此刻,正在寫文章的我雷滚,是一個開始需曾。早上醒來,努力睜開睡眼惺忪的眼,新的一天開始了呆万,匆...
    意靜詩安閱讀 200評論 0 2
  • 第二十三天商源。 早上起來感覺很不好,暈暈乎乎的谋减,大概是因為又在凌晨醒來吧牡彻。 上午去看了一場招聘會,發(fā)現(xiàn)自己所學的專業(yè)...
    言千悟閱讀 108評論 0 0
  • 選中文本 命令模式下:1.可視模式:v出爹,從光標位置開始常規(guī)選中文本庄吼。可視行模式:V严就,從光標位置所在行開始選中文本总寻,...
    TensorFlow開發(fā)者閱讀 199評論 0 3