AndroidStudio新特性5.0&6.0

Studio安裝

2.3 第一次打開需要配置
    2.3.1 在Android Studio安裝目錄下的 bin 目錄下,找到 idea.properties 文件,在文件最後
    追加 disable.android.first.run=true,避開連接谷歌服務器更新SDK

代碼模板
logi
sout 打印
shift+F6改名
ctrl+H 查看繼承類
ctrl+R 全局替換
ctrl+alt+M 提取方法

導入開源庫
main 目錄 下 java 和 res 和 清單文件 修改過時的API

你可以使用 ALT-UP 和 ALT-DOWN實現按照“節點”來擴大和縮小選擇範圍 - 讓你選擇代碼的時候更加高效。

同時,ALT-SHIFT-UP 和 ALT-SHIFT-DOWN則可以讓你當前所在行上移或者下移,省去了通過複製粘貼調整順序的麻煩。
全局替換
 Android Studio正是基於IntelliJ之上。Android Studio最值得記住的快捷鍵是CMD-SHIFT-A(如果你是Windows或者Linux的pc則是CTRL-SHIFT-A )。

開源框架:
butterknife 插件
gsonformat 插件


快捷鍵

Android.5.0 L體驗

卡片效果
水波紋效果
Android Material

RecyclerView CardView

material design

Marshmallow 棉花糖 安卓23M 6.0

lollipop 棒棒糖 安卓21,22 L 5.0 5.1

安卓M 6.0 material design

安卓5.0L體驗
特點 : 卡片效果 ; 水波紋效果

安卓型號

ActionBar是什麼?


升級版本的title.可以存放更多的控件的佈局/工具欄。
開發者可以添加新的元素與編寫對應的事件。
也可以刪除ActionBar

  ActionBar actionBar = getSupportActionBar();//獲取當前升級後標題欄
        //設置一個標題
        actionBar.setTitle("谷歌市場");
   setContentView(R.layout.activity_main);

寫一個類繼承於AppCompatActivity

獲取ActionBar actionbar = getSupportActionBar();

res 目錄下新建 menu文件夾 展示title 

onCreateOptionsMenu 創建菜單

appNs 自定義屬性 自動導入

showAsAction 顯示方式1.always 顯示 2.never 默認值 3.ifRoom 如果有空間 就去展示

處理ActionBar的點擊事件
onOptionsItemSelected()

標題上的元素

一。佈局元素
C:\Users\Administrator\Desktop\DemoLM\001.ActionBar\src\main\res\menu\main_menu.xml

?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<!--menu是ActionBar上面元素的集合
元素是item
id控件的id
title顯示字符串
icon顯示圖標
MenuInflater :菜單的打氣筒
showAsAction顯示方式1.always 顯示 2.ifRoom有空間就顯示 3.never默認值  顯示在隱藏菜單
-->
<item android:id="@+id/item1" android:title="元素1"
    app:showAsAction="always"
    android:icon="@mipmap/ic_launcher"/>
<item android:id="@+id/item2" android:title="元素2"
    app:showAsAction="ifRoom"
    android:icon="@mipmap/ic_launcher"/>
<item android:id="@+id/item3" android:title="元素3"
    app:showAsAction="never"
    android:icon="@mipmap/ic_launcher"/>
<item android:id="@+id/item4" android:title="元素4"
    android:icon="@mipmap/ic_launcher"/>
</menu>

二.初始化與事件

//ActionBar元素的初始化方面

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.元素
    //2.集合
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;//
}

//處理ActionBar元素的點擊事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    //Ctrl+D複製行
    switch (item.getItemId()) {
        case R.id.item1:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.item2:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.item3:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.item4:
            Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
            break;

    }
    return super.onOptionsItemSelected(item);
}

菜單支持側滑

1.SlidingMenu第三開源的側滑控件

2.SlidingDrawer抽屜控件。

3.DrawerLayout:新的佈局,可以添加兩個元素(菜單與頁面內容)

變量 android:layout_gravity=”start” 左側 end 右側

使用方法:
android.support.v4.widget.DrawerLayout 包裹兩個元素
android:layout_gravity=”start”去標記菜單

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.itheima.a001actionbar.MainActivity">
<FrameLayout
    android:id="@+id/content"
    android:background="#FFF000"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
<FrameLayout
    android:id="@+id/menu"
    android:background="#8EC349"
    android:layout_gravity="start"
    android:layout_width="200dp"
    android:layout_height="match_parent"/>
</android.support.v4.widget.DrawerLayout>

配置5.0主題相關的顏色

parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <!--配置actionbar背景顏色-->
    <item name="colorPrimary">@color/colorPrimary</item>
    <!--手機狀態欄的顏色colorPrimaryDark-->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

#換膚(切換theme)
 替換軟件或者系統的"皮膚"--theme

 步驟一。
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     int theme=getSharedPreferences("theme.xml",MODE_PRIVATE).getInt("theme",R.style.GreenTheme);
setTheme(theme);

步驟二。重啓activity不讓用戶發現(去掉動畫)
int []themes=new int[]{R.style.CyanTheme,R.style.PinkTheme,R.style.BrownTheme,R.style.BlueTheme};
  public void changeSkin(View view)
  {
      SharedPreferences.Editor editor = getSharedPreferences("theme.xml", MODE_PRIVATE).edit();
      Random random=new Random();
      editor.putInt("theme",themes[random.nextInt(4)]);
      editor.commit();
      startActivity(new Intent(this,MainActivity.class));
      finish();
      //覆蓋activity動畫效果
      overridePendingTransition(0,0);
  }

旋轉按鈕

是一個聯動控件。(在菜單與箭頭之間產生聯動。)
ActionBarDrawerToggle

一。創建按鈕 綁定給 DrawerLayout

drawer = (DrawerLayout) findViewById(R.id.activity_drawer);
    actionBar.setDisplayHomeAsUpEnabled(true);//讓Actionbar去初始化箭頭按鈕
    ActionBarDrawerToggle actionBarDrawerToggle =    new ActionBarDrawerToggle(activity, drawer, R.string.open, R.string.close);
    actionBarDrawerToggle.syncState();//同步  替換原有按鈕
    drawer.addDrawerListener(actionBarDrawerToggle);

二。編寫ActionBar中的元素android.R.id.home;

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    //Ctrl+D複製行
    switch (item.getItemId()) {
        case android.R.id.home:
            Toast.makeText(this, "旋轉箭頭", Toast.LENGTH_SHORT).show();
            //Ctrl+Alt+L 格式化代碼
            //Ctrl+Alt+F 將局部變量生成成員變量
            View menu=findViewById(R.id.menu);
            if (drawer.isDrawerOpen(menu)) {
                drawer.closeDrawer(menu);
            } else {
                drawer.openDrawer(menu);
            }
            break;
         }
      }

ActionBar 的logo顯示

//設置logo
        actionBar.setLogo(R.mipmap.ic_launcher);
        //加兩個條件才能顯示出來
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayUseLogoEnabled(true);

練習完整代碼

public class MainActivity extends AppCompatActivity {

@BindView(R.id.butt)
Button butt;
@BindView(R.id.content)

FrameLayout menu;
@BindView(R.id.activity_main)
DrawerLayout activityMain;
private int[] themes = new int[]{R.style.BlueGreyTheme, R.style.BlueTheme, R.style.CyanTheme, R.style.PinkTheme};
private DrawerLayout drawer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int theme = getSharedPreferences("theme.xml", MODE_PRIVATE).getInt("theme", R.style.CyanTheme);
    setTheme(theme);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("捕獲");
    setContentView(R.layout.activity_main);

    //讓actionbar 去初始化小箭頭
    actionBar.setDisplayHomeAsUpEnabled(true);
    //1上下文
    //2.側滑菜單
    //3.R.string. 開啓
    //4.R.string  關閉
    //初始化 DrawerLayout
    drawer = (DrawerLayout) findViewById(R.id.activity_main);
    ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawer, R.string.open, R.string.close);
    //同步  替換原有按鈕
    drawerToggle.syncState();
    //給DrawerLayout添加監聽
    drawer.addDrawerListener(drawerToggle);
    //Ctrl+Alt+L 格式化代碼
    //Ctrl+Alt+F 將局部變量生成成員變量
    ButterKnife.bind(this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.mani_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu2:
            Toast.makeText(this, "新聞", Toast.LENGTH_SHORT).show();
            break;
        case R.id.menu3:
            Toast.makeText(this, "NBA", Toast.LENGTH_SHORT).show();
            break;

        case R.id.menu4:
            Toast.makeText(this, "財經", Toast.LENGTH_SHORT).show();
            break;

        case R.id.menu5:
            Toast.makeText(this, "生活", Toast.LENGTH_SHORT).show();
            break;
        case android.R.id.home:
            Toast.makeText(this, "旋轉箭頭", Toast.LENGTH_SHORT).show();
            View id = findViewById(R.id.menu);
            if (drawer.isDrawerOpen(id)){
                drawer.closeDrawer(id);
            }else{
                drawer.openDrawer(id);
            }
            break;
    }

    return super.onOptionsItemSelected(item);
}

@OnClick(R.id.butt)
public void onClick() {
    SharedPreferences.Editor edit = getSharedPreferences("theme.xml", MODE_PRIVATE).edit();
    Random random = new Random();

    edit.putInt("theme", themes[random.nextInt(4)]);
    edit.commit();

    startActivity(new Intent(this, MainActivity.class));
    finish();
    overridePendingTransition(0, 0);


}

RecyclerView

去中央庫下載
compile ‘com.android.support:recyclerview-v7:24.0.0’
RecyclerView替換 ListView 和GridView

getView優化
1.convertView 2.viewHolder優化findviewbyid

layoutManager:排列方式

列表:LinearLayoutManager

網絡:GridLayoutManager

瀑布流:StaggerGridLayoutManager

列表:LinearLayoutManager 縱向

RecyclerView.LayoutManager layout = new LinearLayoutManager(this);
    //先設置LayoutManager 管理者
    rv.setLayoutManager(layout);

    MyAdapter adapter = new MyAdapter();
    rv.setAdapter(adapter);

RecyclerView.Adapter

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private ArrayList<String> list = new ArrayList<>();

    public MyAdapter() {
        for (int i = 0; i < 20; i++) {
            list.add("中心" + i);
        }
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(parent.getContext(), R.layout.item, null);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyViewHolder mvh = (MyViewHolder) holder;
        mvh.tv.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    static class MyViewHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.iv)
        ImageView iv;
        @BindView(R.id.tv)
        TextView tv;

        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
}

列表:LinearLayoutManager 縱向

    //1.上下文
    //2.方向
    //3.倒排  1->10   true  10 -->1
RecyclerView.LayoutManager layout = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
    rv.setLayoutManager(layout);

    MyAdapter adapter = new MyAdapter();
    rv.setAdapter(adapter);

網絡:GridLayoutManager 有橫向和縱向

RecyclerView.LayoutManager layout = new GridLayoutManager(this, 3, LinearLayoutManager.HORIZONTAL, true);
    rv.setLayoutManager(layout);
    MyAdapter adapter = new MyAdapter();
    rv.setAdapter(adapter);

瀑布流:StaggerGridLayoutManager 有橫向和縱向

// 參數1 列數或者橫數 參數2 方向
RecyclerView.LayoutManager layout = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL);

    rv.setLayoutManager(layout);
    MyAdapter adapter = new MyAdapter();
    rv.setAdapter(adapter);

CardView

是升級的FrameLayout.
CardView 5.0新控件  v7 .從FrameLayout擴展來的。
存放在兼容包。可以運行低版本。
1.陰影
2.圓角
3.背景顏色。

<CardView>  包裹起來
視圖
<CardView>

中央庫下載:android.support.v7.widget.CardView 

<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="100dp"
android:layout_height="100dp"
app:cardCornerRadius="14dp"
app:cardElevation="10dp"
app:cardUseCompatPadding="true"
app:contentPadding="20dp"
>
<!--視圖 註釋c+/-->
<!--cardElevation     海撥   陰影與高度有關
cardCornerRadius      卡片圓角之後
cardUseCompatPadding  針對部分設備不兼容
-->

SwipeRefreshLayout 下拉刷新佈局

不需要去下載 V7包包含V4包
android.support.v4.widget.SwipeRefreshLayout
提供一個新佈局,支持任意的下拉刷新

<SwipeRefreshLayout>
需要刷新的佈局.
</SwipeRefreshLayout>

加聯網的權限

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    web = (WebView) findViewById(R.id.wv);
    refresh = (SwipeRefreshLayout) findViewById(R.id.srl);
    initData();
}


private void initData() {

    // 不去跳轉瀏覽器加載網頁,設置一個禁止調用系統瀏覽器的對象
    WebViewClient webClient = new WebViewClient();
    web.setWebViewClient(webClient);

    WebSettings settings = web.getSettings();
    // 快速加載網頁
    settings.setJavaScriptEnabled(true);

    refresh.setColorSchemeColors(Color.BLUE,Color.CYAN,Color.GRAY,Color.MAGENTA);
    refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            web.loadUrl("http://www.baidu.com");
        }
    });


    //WebChromeClient 處理頁面加載進度
    WebChromeClient client = new WebChromeClient(){
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            //下載完成後 下拉刷新隱藏
            if (newProgress==100){
                refresh.setRefreshing(false);
            }
        }
    };
    web.setWebChromeClient(client);

安卓6.0 中央庫搜索design

compile 'com.android.support:design:24.2.0'

FloatingActionBar 懸浮按鈕。有水波紋效果

由imageview升級過來,有懸浮效果

Snackbar 底部彈出一個工具欄 用法和Toast一樣


FloatingActionBar 懸浮按鈕 有水波紋效果

compile ‘com.android.support:design:24.2.0’


Snackbar 底部彈出一個工具欄 用法和Toast一樣

 private FloatingActionButton fab;
    private Snackbar snack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        snack = Snackbar.make(fab, "開啓", Snackbar.LENGTH_SHORT);

        //點擊關閉
        snack.setAction("關閉", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                snack.dismiss();
            }
        });
    }

    public void click(View v) {
        snack.show();
    }

coordinate 協調佈局

協調Snackbar 在佈局中包裹內容就行 不能把relativelayout放進去


<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.a08_floatingactionbutton.MainActivity">

    <android.support.design.widget.FloatingActionButton xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:layout_gravity="bottom|right"
        android:onClick="click"
        app:backgroundTint="#F00"
        app:elevation="8dp"
        app:fabSize="normal"
        app:rippleColor="@color/colorPrimaryDark" />
</android.support.design.widget.CoordinatorLayout>

logcat看不到時 命令 adb logcat

指示器6.0 提供 TabLayout

compile ‘com.android.support:design:24.2.0’

用法:1.初始化viewpager
2.將viewpager設置給指示器


compile 'com.android.support:design:24.2.0'
<android.support.design.widget.TabLayout
    android:id="@+id/tab"

    android:layout_width="match_parent"
    android:layout_height="40dp">

</android.support.design.widget.TabLayout>

MyAdapter pagerAdapter = new MyAdapter(getSupportFragmentManager());
    //設置FragmentPagerAdapter
    vp.setAdapter(pagerAdapter);
    //設置指示器線條的顏色
    tab.setSelectedTabIndicatorColor(Color.DKGRAY);
    //設置指示器線條的高度
    tab.setSelectedTabIndicatorHeight(3);
    //設置指示器選中和默認的顏色,
    tab.setTabTextColors(Color.BLUE,Color.RED);
    //設置指示器的滾動模式
    tab.setTabMode(TabLayout.MODE_SCROLLABLE);
    //設置指示器依賴viewpager
    tab.setupWithViewPager(vp);

FragmentPagerAdapter

public class MyAdapter extends FragmentPagerAdapter {


    public MyAdapter(FragmentManager fm) {
        super(fm);

    }


    @Override
    public Fragment getItem(int position) {
        // 返回一個Fragment 新建的類
        return new MyFragment();
    }

    @Override
    public int getCount() {
        return 15;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "標題" + position;
    }

}

Fragment

public class MyFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ImageView view = new ImageView(container.getContext());
        view.setImageResource(R.mipmap.w4);
        return view;
    }
}

ToolBar的使用

用來取代actionbar
位置靈活 actionbar固定在activity的頂部,toolbar可以在任意位置
設置導航欄圖標
設置app的logo
設置標題和子標題
支持一個控件或者多個自定義控件
支持action Menu

佈局中設置

<android.support.v7.widget.Toolbar
    android:id="@+id/toolb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></android.support.v7.widget.Toolbar>

 //找到控件
        Toolbar bar = (Toolbar) findViewById(R.id.toolb);
        //設置logo
        bar.setLogo(R.mipmap.ic_launcher);
        //設置背景色
        bar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        //設置主標題
        bar.setTitle("野馬");
        //設置子標題
        bar.setSubtitle("在奔跑");
        //設置子標題顏色
        bar.setSubtitleTextColor(Color.RED);
        //設置導航圖標
        bar.setNavigationIcon(R.mipmap.ic_launcher);

        //設置menu菜單
        bar.inflateMenu(R.menu.main_menu);
        //設置menu菜單的點擊事件
        bar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.menu1:
                        Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_SHORT).show();
                        break;
                }

                return false;
            }
        });

AppBarLayout Toolbar 顯示推出Toolbar的效果

需要下載類庫 coordinate 包裹在外面 去掉LinearLayout 佈局AppBarLayout 實現滾出屏幕的效果

    <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.support.design.widget.AppBarLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#aaccdd"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"></android.support.v4.view.ViewPager>


</android.support.design.widget.CoordinatorLayout>

AppBarLayout Toolbar 顯示推出Toolbar的效果

    // 初始化ActionBar
    initToolBar();
    //初始化ViewPager
    initViewPager();
    //初始化TableLayout
    initTableLayout();

}

private void initToolBar() {
    Toolbar bar = (Toolbar) findViewById(R.id.bar);
    bar.setLogo(R.mipmap.ic_launcher);
    bar.setTitle("酷我");
    bar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
    bar.inflateMenu(R.menu.main_menu);

}



private void initTableLayout() {
    TabLayout tab = (TabLayout) findViewById(R.id.tl);
    tab.setTabTextColors(Color.BLACK,Color.RED);
    tab.setSelectedTabIndicatorHeight(3);
    tab.setSelectedTabIndicatorColor(Color.BLUE);
    tab.setTabMode(TabLayout.MODE_SCROLLABLE);
    tab.setupWithViewPager(pager);
}

private void initViewPager() {
    pager = (ViewPager) findViewById(R.id.vp);

    MyAdapter adapter = new MyAdapter(getSupportFragmentManager());

    pager.setAdapter(adapter);
}

ViewPager的 MyAdapter

public class MyAdapter extends FragmentPagerAdapter{


    private final ArrayList<String> list;

    public MyAdapter(FragmentManager fm) {

        super(fm);
        String[] menu = new String[]{"新聞","娛樂","體育","財經","頭條","本地","NBA"};
        list = new ArrayList<>();

        for (int i = 0; i < menu.length; i++) {
            list.add(menu[i]);
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {

        return list.get(position);
    }

    @Override
    public Fragment getItem(int position) {

        return new MyFragment();
    }

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

}

return一個MyFragment

public class MyFragment extends Fragment {


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        RecyclerView  recyView = new RecyclerView(container.getContext());
        // 創建一個垂直的瀑布流
        RecyclerView.LayoutManager layout = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        recyView.setLayoutManager(layout);
        MyRecycleAdapter adapter = new MyRecycleAdapter();
        recyView.setAdapter(adapter);

        return recyView;

    }

}

MyRecycleAdapter繼承RecyclerView

public class MyRecycleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int[] list;
    public MyRecycleAdapter() {
        list = new int[]{R.mipmap.w1,R.mipmap.w2,R.mipmap.w3,R.mipmap.w4,R.mipmap.w5};
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater from = LayoutInflater.from(parent.getContext());
        View inflate = from.inflate(R.layout.item_recyclerview, parent, false);
        RecyclerView.ViewHolder holder = new ViewHolder(inflate);


        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ViewHolder hold = (ViewHolder) holder;

        ((ViewHolder) holder).iv.setImageResource(list[position]);
    }

    @Override
    public int getItemCount() {
        return list.length;


    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.iv)
        ImageView iv;
        @BindView(R.id.tv)
        TextView tv;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}

注意

在recyclerView 時需要用LayoutInflater

把toolBar推出屏幕

TabLayout + viewpager的用法

<android.support.design.widget.TabLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:background="@color/white"
    app:tabGravity="fill"
    app:tabIndicatorColor="@color/chart_title"
    app:tabIndicatorHeight="2dp"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/chart_title"
    app:tabTextAppearance="@style/TabLayoutTextStyle"
    app:tabTextColor="@color/black_trans_45">
</android.support.design.widget.TabLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/message_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v4.view.ViewPager>

這樣設置tab平分屏幕寬度

    app:tabGravity="fill"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed"

在fragment中添加fragment,需要用到getChildFragmentManager()

List<BaseFragmnet> list = new ArrayList<>();
BaseFragmnet listFragment = new MessageListFragment();
BaseFragmnet officeFragment = new MobileOfficeFragment();
list.add(listFragment);
list.add(officeFragment);
NewMessagePagerAdapter pagerAdapter = new NewMessagePagerAdapter(getChildFragmentManager(), list);
messagePager.setAdapter(pagerAdapter);
//使tablayout依賴到viewpagwer
tabLayout.setupWithViewPager(messagePager);
//在adapter中重寫getPageTitle方法
public class NewMessagePagerAdapter extends FragmentPagerAdapter {

    private String[] titles = new String[]{"消息列表", "移動辦公"};
    private List<BaseFragmnet> list;

    public NewMessagePagerAdapter(FragmentManager fm, List<BaseFragmnet> list) {
        super(fm);
        this.list = list;
    }

    public BaseFragmnet getFragment(int pos) {
        return list.get(pos);
    }

    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
}
發佈了63 篇原創文章 · 獲贊 10 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章