Android控件使用 — 12个Material Design风格控件的使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android控件使用 — 12个Material Design风格控件的使用相关的知识,希望对你有一定的参考价值。
项目在GitHub上的地址:
https://github.com/Hebin320/MaterialDesignUse
1、AppBarLayout、ToolBar
AppBarLayout 是继承LinerLayout实现的一个ViewGroup容器组件,它是为了Material Design设计的App Bar,支持手势滑动操作。
AppBarLayout必须作为Toolbar的父布局容器,也可以配合CoordinatorLayout一起使用。
ToolBar是谷歌新推出的代替ActionBar的一个标题栏控件,能将背景拓展到状态栏,依赖包是v7,使用之前先把style中继承的主题改为NoActionBar;
可以设置”标题”,”副标题”,”Logo”,”NavigationIcon”以及”Menu菜单”,也可以自定义布局;
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="70dp"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:fitsSystemWindows="true"
>
<TextView
android:id="@+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginStart="0dp"
android:gravity="center"
android:text="@string/app_name"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:paddingTop="6dp"
android:paddingRight="40dp"
/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
TextView是一个居中的标题,
fitsSystemWindows实现状态栏各版本适配方案:
1.Android5.0以上:material design风格,半透明(APP 的内容不被上拉到状态)
2.Android4.4(kitkat)以上至5.0:全透明(APP 的内容不被上拉到状态)
3.Android4.4(kitkat)以下:不占据status bar
在Activity中添加代码即可使用ToolBar;
mToolbar = (Toolbar) findViewById(R.id.toolbar);
tvToolTitle = (TextView) findViewById(R.id.toolbar_title);
tvToolTitle.setText("测试");
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ToolBar中的菜单布局:
<menu 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"
tools:context=".MainActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="action_settings"
app:showAsAction="never"/>
</menu>
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
break;
default:
break;
}
return true;
}
});
2、DrawerLayout、NavigationView
DrawerLayout可以轻松的实现抽屉效果、在DrawerLayout中,第一个子View必须是显示内容的view,第二个view是抽屉view,设置属性layout_gravity=”left|right”,表示是从左边滑出还是右边滑出。
使用前需添加:
compile ‘com.android.support:design:23.3.0‘
xml中的布局代码如下:
<LinearLayout 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:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="70dp"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:fitsSystemWindows="true"
>
<TextView
android:id="@+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginStart="0dp"
android:gravity="center"
android:text="@string/app_name"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:paddingTop="6dp"
android:paddingRight="40dp"
/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!--第一个,显示的布局-->
<android.support.design.widget.CoordinatorLayout
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/frame_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/appbar"
android:scrollbars="none"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
<!--第二个,不显示的抽屉布局-->
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/navigation_header"
app:menu="@menu/drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
第一个布局使用的是Framelayout,可以通过侧滑抽屉栏的点击显示出不同的Fragment;
而抽屉布局用的是NavigationView,NavigationView需要接收几个必要的参数、一个用于显示头部的布局以及用于显示选项的菜单布局;可在xml中直接添加布局;
app:headerLayout="@layout/navigation_header"
app:menu="@menu/drawer"
头部布局xml代码:
<LinearLayout 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="192dp"
android:background="?attr/colorPrimaryDark"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profile_image"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginTop="20dp"
android:src="@mipmap/ic_launcher"
app:border_color="@color/primary_light"
app:border_width="2dp" />
<TextView
android:layout_marginTop="10dp"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="测试账号"
android:gravity="center"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
/>
</LinearLayout>
选项菜单布局:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<group android:checkableBehavior="single">
<item
android:id="@+id/navigation_item_book"
android:icon="@mipmap/ic_stars_black_24dp"
android:title="测试" />
<item
android:id="@+id/navigation_item_example"
android:icon="@mipmap/ic_brightness_7_black_24dp"
android:title="测试" />
<item
android:id="@+id/navigation_item_blog"
android:icon="@mipmap/ic_flare_black_24dp"
android:title="测试" />
<item
android:id="@+id/navigation_item_about"
android:icon="@drawable/ic_favorite"
android:title="测试" />
</group>
</menu>
配合ToolBar,在Activity中的使用代码:
public class MainActivity extends AppCompatActivity implements BackHandledFragment.BackHandlerInterface {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar mToolbar;
private BackHandledFragment selectedFragment;
private NavigationView mNavigationView;
private TextView tvToolTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
tvToolTitle = (TextView) findViewById(R.id.toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open,
R.string.drawer_close);
mDrawerToggle.syncState();
mDrawerLayout.addDrawerListener(mDrawerToggle);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
setupDrawerContent(mNavigationView);
switchToBook();
}
private void switchToBook() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new RecyclerFragment()).commit();
tvToolTitle.setText("测试");
}
private void switchToExample() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new DayFragment()).commit();
tvToolTitle.setText("测试");
}
private void switchToBlog() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new BlankFragment()).commit();
tvToolTitle.setText("测试");
}
private void switchToAbout() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new TimeFragment()).commit();
tvToolTitle.setText("测试");
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.navigation_item_book:
switchToBook();
break;
case R.id.navigation_item_example:
switchToExample();
break;
case R.id.navigation_item_blog:
switchToBlog();
break;
case R.id.navigation_item_about:
switchToAbout();
break;
}
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
@Override
public void setSelectedFragment(BackHandledFragment backHandledFragment) {
this.selectedFragment = backHandledFragment;
}
private long exitTime = 0;
public void doExitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, R.string.press_again_exit_app, Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
@Override
public void onBackPressed() {
if (selectedFragment == null || !selectedFragment.onBackPressed()) {
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
} else {
doExitApp();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test,menu);
return true;
}
}
3、RecyclerView、CardView、AutoScrollViewPager
RecyclerView是用于显示大量数据的控件,有点类似与ListView、GirdView,相较而言,RecyclerView在灵活性、体验感上都有一个较大的提升,通过设置它提供的不同LayoutManager,ItemDecoration , ItemAnimator可以实现丰富的功能,依赖包是v7;
RecyclerView也能像ListView一样添加Header以及Footer,也可以通过addOnScrollListener进行分页加载;
以Recyclerview添加Viewpager为Header为例子对Recyclerview进行简单的使用,Viewpager使用的是GitHub上的一个开源项目,实现自动轮播的AutoScrollViewPager;
GitHub地址为:
https://github.com/Trinea/android-auto-scroll-view-pager
Header是通过GitHub上的一个开源项目RecyclerViewHeader,快速为Recyclerview添加Header;
GitHub地址为:
https://github.com/blipinsk/RecyclerViewHeader
添加完依赖包之后即可进行应用。
fragment_recyclerview.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:layout_gravity="center_horizontal|top"
android:layout_marginBottom="20dp"
/>
<com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_gravity="center_horizontal|top"
android:layout_marginBottom="20dp"
>
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:id="@+id/vp_books"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
/>
</com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader>
</FrameLayout>
recyclerview_item的代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 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="170dp"
android:layout_margin="5dp"
android:clickable="true"
app:cardCornerRadius="4dp"
app:cardElevation="10dp">
<ImageView
android:id="@+id/ivBook"
android:transitionName="@string/transition_book_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v7.widget.CardView>
RecyclerAdapter.class的代码
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<RecyclerBean> list = new ArrayList<>();
private static final int ANIMATED_ITEMS_COUNT = 4;
private Activity context;
private boolean animateItems = false;
private int lastAnimatedPosition = -1;
public RecyclerAdapter(Activity context , List<RecyclerBean> mlist) {
TypedValue mTypedValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
list = updateItems(mlist,true);
this.context = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView ivBook;
public int position;
public ViewHolder(View v) {
super(v);
ivBook = (ImageView) v.findViewById(R.id.ivBook);
}
}
private void runEnterAnimation(View view, int position) {
if (!animateItems || position >= ANIMATED_ITEMS_COUNT - 1) {
return;
}
if (position > lastAnimatedPosition) {
lastAnimatedPosition = position;
view.setTranslationY(Utils.getScreenHeight(context));
view.animate()
.translationY(0)
.setStartDelay(100 * position)
.setInterpolator(new DecelerateInterpolator(3.f))
.setDuration(700)
.start();
}
}
public List<RecyclerBean> updateItems(List<RecyclerBean> books, boolean animated) {
List<RecyclerBean> list = new ArrayList<>();
animateItems = animated;
lastAnimatedPosition = -1;
list.addAll(books);
notifyDataSetChanged();
return list;
}
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
runEnterAnimation(holder.itemView, position);
RecyclerBean recyclerBean = list.get(position);
holder.ivBook.setBackgroundResource(recyclerBean.getImg());
}
@Override
public int getItemCount() {
return list.size();
}
public RecyclerBean getBook(int pos) {
return list.get(pos);
}
public RecyclerItemClickListener.OnItemClickListener onItemClickListener = new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
RecyclerBean book = getBook(position);
Intent intent = new Intent(context, RecyclerDetailActivity.class);
intent.putExtra("book", book);
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(context,
view.findViewById(R.id.ivBook),context.getString(R.string.transition_book_img));
ActivityCompat.startActivity(context, intent, options.toBundle());
}
};
}
RecyclerVpAdapter.class的代码:
public class RecyclerVpAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> list;
FragmentManager fm;
public RecyclerVpAdapter(FragmentManager fm, ArrayList<Fragment> list) {
super(fm);
this.list = list;
this.fm = fm;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Fragment getItem(int arg0) {
return list.get(arg0);
}
}
RecyclerFragment.class中代码:
RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
//ListView形式的列表
// LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
//GirdView形式的列表
GridLayoutManager layoutManager = new GridLayoutManager(getContext(),2);
mRecyclerView.setLayoutManager(layoutManager);
RecyclerViewHeader header = (RecyclerViewHeader) view.findViewById(R.id.header);
AutoScrollViewPager viewPager = (AutoScrollViewPager) header.findViewById(R.id.vp_books);
ArrayList<Fragment> fragmentList = new ArrayList<>();
for (int i = 0; i < vpImgPath.length; i++) {
RecyclerVpFragment recyclerVpFragment = RecyclerVpFragment.newInstance(vpImgPath[i]);
fragmentList.add(recyclerVpFragment);
}
RecyclerVpAdapter bAdapter = new RecyclerVpAdapter(getChildFragmentManager(),fragmentList);
viewPager.setAdapter(bAdapter);
viewPager.setCurrentItem(0);
viewPager.startAutoScroll();
//开启Viewpager的自动轮播
header.attachTo(mRecyclerView,true);
for (int i = 0; i < title.length; i++) {
RecyclerBean recyclerBean = new RecyclerBean();
recyclerBean.setImg(imgPath[i]);
recyclerBean.setInfo(tvInfo[i]);
recyclerBean.setTitle(title[i]);
recyclerBean.setCatalog(title[i]);
recyclerBean.setAuthor_intro(title[i]);
recyclerBean.setSummary(title[i]);
recyclerBean.setImglarge(imgPath[i]);
mList.add(recyclerBean);
}
mAdapter = new RecyclerAdapter(getActivity(),mList);
//RecyclerView子项的点击事件
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mAdapter.onItemClickListener));
mRecyclerView.setAdapter(mAdapter);
上面RecyclerView的item布局里面,父布局是一个CardView;
CardView继承FrameLayout,是能在自身之上添加了圆角和阴影效果的一种布局,常常用在RecyclerView、ListView、GirdView的item布局里面;
比较常用的有这几个属性:
<!--圆角半径-->
app:cardCornerRadius="4dp"
<!--阴影面积-->
app:cardElevation="10dp"
<!--点击水波动画-->
android:foreground="?android:attr/selectableItemBackground"
4、CoordinatorLayout、CollapsingToolbarLayout、TabLayout
(GIF太大,压缩大小之后,有点儿问题)
CoordinatorLayout,一个从另一层面去控制子view之间触摸事件的布局,在CoordinatorLayout的布局中使用了Toolbar ,允许你更加自由的自定义其外观与布局的其余部分融为一体。使用AppBarLayout可以让你的Toolbar与其他View(比如TabLayout的选项卡)能响应被标记了ScrollingViewBehavior的View的滚动事件。
CollapsingToolbarLayout,可伸缩折叠的Toolbar ,直接添加Toolbar到AppBarLayout可以让你使用enterAlwaysCollapsed和 exitUntilCollapsedscroll标志,但是无法控制不同元素如何响应collapsing的细节。这里使用了 CollapsingToolbarLayout的app:layout_collapseMode=”pin”来确保Toolbar在view折叠的时候仍然被固定在屏幕的顶部当你让CollapsingToolbarLayout和Toolbar在一起使用的时候,title 会在展开的时候自动变得大些,而在折叠的时候让字体过渡到默认值。
TabLayout 既实现了固定的选项卡(View的宽度平均分配),也实现了可滚动的选项卡(View宽度不固定同时可以横向滚动)。如果你使用ViewPager在 tab之间横向切换,你可以直接从PagerAdapter的getPageTitle() 中创建选项卡,然后使用setupWithViewPager()将两者联系在一起。它可以使tab的选中事件能更新ViewPager,同时 ViewPager
的页面改变能更新tab的选中状态。
注:图中Activity的启动效果动画是通过下面代码实现的:
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(context,
view.findViewById(R.id.ivBook),context.getString(R.string.transition_book_img));
ActivityCompat.startActivity(context, intent, options.toBundle());
使用之前先添加Design的包,即可使用这三个;
activity_appbar_detail.xml主布局代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="@+id/ivImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:transitionName="@string/transition_book_img"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"
style="@style/MyCustomTabLayout"
/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
RecyclerDetailActivity.class代码:
public class RecyclerDetailActivity extends AppCompatActivity {
private ViewPager mViewPager;
private RecyclerBean mBook;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appbar_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
mBook = (RecyclerBean) getIntent().getSerializableExtra("book");
CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle(mBook.getTitle());
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
ivImage.setBackgroundResource(mBook.getImglarge());
mViewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.addTab(tabLayout.newTab().setText("测试"));
tabLayout.addTab(tabLayout.newTab().setText("测试"));
tabLayout.addTab(tabLayout.newTab().setText("测试"));
tabLayout.setupWithViewPager(mViewPager);
}
private void setupViewPager(ViewPager mViewPager) {
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
adapter.addFragment(DetailFragment.newInstance(mBook.getSummary()), "测试");
adapter.addFragment(DetailFragment.newInstance(mBook.getAuthor_intro()), "测试");
adapter.addFragment(DetailFragment.newInstance(mBook.getCatalog()), "测试");
mViewPager.setAdapter(adapter);
}
static class MyPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
5、TextInputLayout
TextInputLayout 控件表现得就像LinearLayout 一样,它是一个容器。TextInputLayout 中只能放一个子元素,和ScrollView有点类似,并且子元素必须是EditText;
TextInputLayout 实现的功能就是当EditText中输入第一个字母要隐藏hint的时候,TextInputLayout中会出现一个悬浮的标签来显示这个hint,还负责一个炫酷的的material 动画
布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/include_toolbar" />
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<EditText
android:id="@+id/edit_text_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_username"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edit_text_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_login" />
</LinearLayout>
6、FloatingActionButton、Snackbar
布局代码:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinatorLayout"
tools:context="com.aswifter.material.BlankFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<android.support.design.widget.FloatingActionButton
android:id="@+id/flb_black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:src="@drawable/ic_favorite"
android:layout_alignParentBottom="true"
app:fabSize="mini"
app:layout_anchor="@id/coordinatorLayout"
app:layout_anchorGravity="bottom|right|end"
app:borderWidth = "0dp"
/>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Fragment中的代码:
public class BlankFragment extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_blank, container, false);
final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.coordinatorLayout);
FloatingActionButton floatingActionButton = (FloatingActionButton) view.findViewById(R.id.flb_black);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(coordinatorLayout,
"Snackbar", Snackbar.LENGTH_LONG)
.setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(
getActivity(),
"snackbar OK clicked",
Toast.LENGTH_LONG).show();
}
})
.show();
}
});
return view;
}
}
以上是关于Android控件使用 — 12个Material Design风格控件的使用的主要内容,如果未能解决你的问题,请参考以下文章
Android Material Design新UI控件使用大全 二
Android Material Design控件使用——CardView和SnackBar使用
Android Material Design新UI控件使用大全 三
Android Material Design新UI控件使用大全 三