在图书馆看到这本书,实例比较多,但是代码没有随书附赠,需要发邮件才能索取,大概是因为本书的代码占了书的一半版面左右的原因吧。因此简单手动过了一遍,我的命名习惯跟书中不一样,所以都是按自己的习惯去命名的。这本书最大的好处就是实例够多吧,做了总比较全面结。部分内容由于应用广泛并且博客解释更详细所以没有用书上的例子而是贴出我觉得写得还不错的链接,另,部分代码由于android studio提示废弃,因此修改了部分代码。还有,书中部分代码只有参考意义,实际使用中还是会有问题,待优化。
代码运行环境为android7真机。
第1章UI布局
1.使用纯java代码创建应用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("刷新内容");
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"
具体位置如下所示。
另外,这段代码在我的小米手机上可以正常显示,但是在魅族手机上无法显示文字,猜测是因为魅族手机上需要设置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。
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
//www.greatytc.com/p/a9b48dee86e0
这应该是最够用的TextInputLayout了
//www.greatytc.com/p/2b0cd9e9a4d9
TextInputLayout详解
//www.greatytc.com/p/4c99e4c0fe90
5.GridLayout创建计算器按键布局
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>
图片是随便截图做的。
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实际是被隐藏了。
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按权重分配控件空间。
这个懒得打了,就是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节点下加入一句代码即可。
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和适配器创建选项卡
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.360.cn","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中加上权限
<uses-permission android:name="android.permission.INTERNET"/>
15.使用TabLayout和Fragment创建选项卡
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关联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>
16.使用FrameLayout创建纵向选项卡
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创建横向选项卡
由于TabActivity 废弃,所以跳过。
18.使用AbsoluteLayout实现平移控件
由于AbsoluteLayout废弃,所以跳过。
19.使用FrameLayout实现闪烁控件
FrameLayout子视图的位置排列取决于它们各自的android:layout_gravity属性。
注意,本书中的Handle的用法是会引起内存泄漏的,但是目前学习目的只是学习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创建翻页卷边动画
由于代码不全,因此使用网上的链接去学习。关键是使用贝塞尔曲线quadTo实现翻页卷边。
Android自定义View——从零开始实现书籍翻页效果(一)
//www.greatytc.com/p/d02362fbd9f2
自定义View基础 - 最易懂的自定义View原理系列(1)
//www.greatytc.com/p/146e5cec4863
浅谈安卓自定义view(一):制作一个最最最简单的自定义view
https://blog.csdn.net/wsyizmao/article/details/78491422
贝塞尔曲线学习总结
//www.greatytc.com/p/f9c15dc9c38d
自定义view系列之——Android贝塞尔曲线--基础篇
//www.greatytc.com/p/3b2ac05ae3c7
第2章常用控件
21.在TextView中创建空心文字
<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中实现上文下图的布局
<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="重庆市人民大礼堂,位于重庆市渝中区人民路173号,于1951年6月破土兴建,1954年4月竣工,是一座仿古民族建筑群,是重庆十大文化符号,是中国传统宫殿建筑风格与西方建筑的大跨度结构巧妙结合的杰作,也是重庆的标志建筑物之一。"
android:textSize="20sp"/>
</LinearLayout>
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="百度官网: https://www.baidu.com/"
android:textSize="20sp"/>
</LinearLayout>
24.在自定义View中实现垂直滚动文本
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>
参考链接:
Android ScrollTo()、ScrollBy()用法
//www.greatytc.com/p/31635550aabb
Android scrollTo,scrollBy 正数却相反方向移动理解
https://blog.csdn.net/pmslrxe/article/details/83016058
坐标跟android屏幕坐标相反的原因关键在于scroll是滚动不是移动。
25.在EditText中指定输入法的数字软键盘
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="显示数字软键盘"
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禁止输入表情
//www.greatytc.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实现自动提示
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
//www.greatytc.com/p/aeae6a201a7b
28.使用SearchView和ListView实现过滤输入
首先manifest中加入权限,如果是android6以上版本还需要动态申请权限,但是这里我偷下懒,选择手动打开。
<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中显示搜索框文本内容
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数据的访问
//www.greatytc.com/p/67dcf08dd1d4
SearchView的使用
//www.greatytc.com/p/00cb87a2964f
29.在EditText右端设置输入提示内容和图标
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>
随便在百度上找一个灯泡的图片。
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);
}
}
如果不设置自己的图标,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("必须填写");
}
}
30.通过自定义Shape创建不同的圆角按钮
<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>