0

私は最近、thisのチュートリアルをフォローして、私のHomePage内にフラグメントを作成しました。これは(私の知る限り)うまくいきませんでしたので、代わりにNavigation Drawerを保持するMain Activityに次のコードを実装しました。Android:ListView/GridViewオーバーラッピングツールバー:MainActivity/Fragment

  1. ユーザーログをアプリにユーザーが経由してナビゲーションドロワーを保持している「主な活動」に取られ
  2. :私は、私は以下を達成したいのですが何のアプリの順序と一緒にご理解を簡素化しようとしていますIntent
  3. ユーザは、ナビゲーション・ドロワー(ホーム、お気に入り、ヘルプなど)内のさまざまなフラグメントから選択することができます< - これは、リスト・ビューがMainActivityと完全に重複するため、これ以上機能しません。ナビゲーション・ドロワーへのアクセス(これは私のフラグメント「ホーム」内に表示したいものです) - >

ListView/GridView内で画像、タイトル、説明のメソッドを保持するProductクラスも作成しました。また、ListView/GridView内に保持されている「Products」を拡張するために、ListViewAdapterクラスとGridViewAdapterクラスを作成しました。

MainActivity.java:

import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.support.v4.app.FragmentTransaction; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewStub; 
import android.widget.AdapterView; 
import android.widget.GridView; 
import android.widget.ListView; 
import android.widget.Toast; 

import java.util.ArrayList; 
import java.util.List; 

public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener { 

    private ViewStub stubGrid; 
    private ViewStub stubList; 
    private ListView listView; 
    private GridView gridView; 
    private ListViewAdapter listViewAdapter; 
    private GridViewAdapter gridViewAdapter; 
    private List<Product> productList; 
    private int currentViewMode = 0; 

    static final int VIEW_MODE_LISTVIEW = 0; 
    static final int VIEW_MODE_GRIDVIEW = 1; 

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

     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 

     stubList = (ViewStub) findViewById(R.id.stub_list); 
     stubGrid = (ViewStub) findViewById(R.id.stub_grid); 

     // Inflate ViewStub before we get view 
     stubList.inflate(); 
     stubGrid.inflate(); 

     listView = (ListView) findViewById(R.id.myListView); 
     gridView = (GridView) findViewById(R.id.myGridView); 

     // Get list of products 
     getProductList(); 

     // Get current view mode in shared preferences 
     SharedPreferences sharedPreferences = getSharedPreferences("View Mode", MODE_PRIVATE); 
     currentViewMode = sharedPreferences.getInt("currentViewMode", VIEW_MODE_LISTVIEW); // Default view is ListView 

     // Register item click 
     //listView.setOnItemClickListener(onItemClick); 
     //gridView.setOnItemClickListener(onItemClick); 

     switchView(); 
    } 

    private void switchView() { 
     if (VIEW_MODE_LISTVIEW == currentViewMode) { 
      // Display ListView 
      stubList.setVisibility(View.VISIBLE); 
      // Hide GridView 
      stubGrid.setVisibility(View.GONE); 
     } else { 
      // Hide ListView 
      stubList.setVisibility(View.GONE); 
      // Display GridView 
      stubGrid.setVisibility(View.VISIBLE); 
     } 

     setAdapters(); 

    } 

    private void setAdapters() { 
     if (VIEW_MODE_LISTVIEW == currentViewMode) { 
      listViewAdapter = new ListViewAdapter(this, R.layout.list_item, productList); 
      listView.setAdapter(listViewAdapter); 
     } else { 
      gridViewAdapter = new GridViewAdapter(this, R.layout.grid_item, productList); 
      gridView.setAdapter(gridViewAdapter); 
     } 
    } 

    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case R.id.item_menu_1: 
       if (VIEW_MODE_LISTVIEW == currentViewMode) { 
        currentViewMode = VIEW_MODE_GRIDVIEW; 
       } else { 
        currentViewMode = VIEW_MODE_LISTVIEW; 
       } 
       // Switch view 
       switchView(); 
       // Save view mode in share preferences 
       SharedPreferences sharePreferences = getSharedPreferences("ViewMode", MODE_PRIVATE); 
       SharedPreferences.Editor editor = sharePreferences.edit(); 
       editor.putInt("currentViewMode", currentViewMode); 
       editor.commit(); 

       break; 
     } 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     /* 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     */ 

     return super.onOptionsItemSelected(item); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     // Handle navigation view item clicks here. 
     int id = item.getItemId(); 

     if (id == R.id.first_fragment) { 
      setTitle("Home"); 
      FirstFragment fragment = new FirstFragment(); 
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
      fragmentTransaction.replace(R.id.frame, fragment, "fragment1"); 
      fragmentTransaction.commit(); 
     } else if (id == R.id.second_fragment) { 
      setTitle("Favourites"); 
      SecondFragment fragment = new SecondFragment(); 
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
      fragmentTransaction.replace(R.id.frame, fragment, "fragment2"); 
      fragmentTransaction.commit(); 
     } else if (id == R.id.third_fragment) { 
      setTitle("Account"); 
      ThirdFragment fragment = new ThirdFragment(); 
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
      fragmentTransaction.replace(R.id.frame, fragment, "fragment3"); 
      fragmentTransaction.commit(); 
     } else if (id == R.id.fourth_fragment) { 
      setTitle("Help & Feedback"); 
      FourthFragment fragment = new FourthFragment(); 
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
      fragmentTransaction.replace(R.id.frame, fragment, "fragment4"); 
      fragmentTransaction.commit(); 
     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

    public List<Product> getProductList() { 
     // Pseudo code to get product, replace your code to get product here 
     productList = new ArrayList<>(); 
     productList.add(new Product(R.drawable.nightclub, "Title 1", "This is description 1")); 
     productList.add(new Product(R.drawable.nightclub, "Title 2", "This is description 2")); 
     productList.add(new Product(R.drawable.nightclub, "Title 3", "This is description 3")); 
     productList.add(new Product(R.drawable.nightclub, "Title 4", "This is description 4")); 
     productList.add(new Product(R.drawable.nightclub, "Title 5", "This is description 5")); 
     productList.add(new Product(R.drawable.nightclub, "Title 6", "This is description 6")); 
     productList.add(new Product(R.drawable.nightclub, "Title 7", "This is description 7")); 
     productList.add(new Product(R.drawable.nightclub, "Title 8", "This is description 8")); 
     productList.add(new Product(R.drawable.nightclub, "Title 9", "This is description 9")); 
     productList.add(new Product(R.drawable.nightclub, "Title 10", "This is description 10")); 

     return productList; 
    } 

    /* 
    AdapterView.OnItemClickListener onItemClick = new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      // Do something when u ser clicks an item 
      Toast.makeText(getApplicationContext(), productList.get(position).getTitle() + " - " + productList.get(position).getDescription(), Toast.LENGTH_SHORT).show(); 
     } 
    };*/ 
} 

Content_Main.xml

<?xml version="1.0" encoding="utf-8"?> 
<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" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.example.michael.whatsupldn.MainActivity" 
    tools:showIn="@layout/app_bar_main"> 

    <FrameLayout 
     android:id="@+id/frame" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:alpha="200"/> 
</LinearLayout> 

Activity_Main.xml

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.DrawerLayoutx mlns: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:id="@+id/drawer_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:openDrawer="start"> 

    <include 
     layout="@layout/app_bar_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <android.support.design.widget.NavigationView 
     android:id="@+id/nav_view" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:fitsSystemWindows="true" 
     app:headerLayout="@layout/nav_header_main" 
     app:menu="@menu/activity_main_drawer"/> 

    <ViewStub 
     android:id="@+id/stub_list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="10dp" 
     android:inflatedId="@+id/showlayout" 
     android:layout="@layout/my_listview"/> 

    <ViewStub 
     android:id="@+id/stub_grid" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="10dp" 
     android:inflatedId="@+id/showlayout" 
     android:layout="@layout/my_gridview"/> 

</android.support.v4.widget.DrawerLayout> 

app_bar_main.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" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.michael.whatsupldn.MainActivity"> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:scaleType="centerCrop" 
     android:src="@drawable/london_skyline_dark" 
     android:layout_alignParentTop="true" 
     android:id="@+id/imageView" 
     android:contentDescription="@string/london_skyline"/> 

    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

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

    <include layout="@layout/content_main" /> 

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

エミュレータ出力:

予想される出力:断片と enter image description here

ナビゲーションドロワー:(私は enter image description here

すべてのヘルプ 'ホーム' フラグメントにリストビューを挿入したいのですが非常に感謝されます!

+0

が完了 –

+0

@StanislavBondar activity_main.xml' '投稿してくださいするのに役立ちます、それをしてくださいチェックアウトします。また、必要に応じてcontent_main.xmlをアップロードしました。 – AndroidDevBro

+0

最も簡単な方法は、 'android:layout_marginTop ="?attr/actionBarSize "' を 'ViewStub'にxmlで追加することです。 –

答えて

1

まず、DrawerLayoutは、最もtwo子ビューを保持することができます。 Firstビューには、画面(your primary layout when the drawer is hidden)のメインcontentが含まれ、Secondビューにはnavigation drawerの内容が含まれています。

1.activity_MainレイアウトからListViewGridViewためViewStubを削除します。

Documentation

がSOLUTIONを参照してください。代わりにListViewGridView

// activity_Main.xml 
<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.DrawerLayoutx mlns: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:id="@+id/drawer_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:openDrawer="start"> 

    <include 
     layout="@layout/app_bar_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <android.support.design.widget.NavigationView 
     android:id="@+id/nav_view" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:fitsSystemWindows="true" 
     app:headerLayout="@layout/nav_header_main" 
     app:menu="@menu/activity_main_drawer"/> 

</android.support.v4.widget.DrawerLayout> 

2.、ちょうど異なるLayoutManagerでのみRecyclerViewを使用しています。一覧にはLinearLayoutManager、グリッドにはGridLayoutManagerを使用します。 FirstFragmentHomeFragmentとしているとします。 FirstFragmentレイアウトXMLにリストまたはグリッドを表示するためにRecyclerViewを追加します。あなたのFirstFragmentクラスで

// first_fragment.xml 
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_height="match_parent" 
    android:layout_width="match_parent"> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recycler_view" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:clipToPadding="false" /> 

</RelativeLayout> 

3.、2つのレイアウトマネージャ(LinearLayoutManagerGridLayoutManager)を追加します。

は、あなたがしてRecyclerViewGrid使用GridLayoutManagerためLinearLayoutManagerと を使用Listを表示したい場合。方法toggleListGrid()を呼び出してビューを切り替えます。

更新します以下のようにFirstFragment

//FirstFragment.java 

......... 
............... 

RecyclerView mRecyclerView; 

RecyclerView.LayoutManager mGridLayoutManager; 
RecyclerView.LayoutManager mLinearLayoutManager; 

boolean isList = false; // By default list will be shown 


@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 

    // Required for option menu 
    setHasOptionsMenu(true); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.first_fragment, null); 

    //REFERENCE 
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); 

    // Layout manager 
    mGridLayoutManager = new GridLayoutManager(getActivity(), 2); 
    mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); 

    // Set layout manager 
    toggleListGrid(); 


    // Set adapter to RecyclerView 
    ............... 
    .................... 

    return rootView; 
} 

public void toggleListGrid() { 

    isList = !isList; 

    if(isList) 
     mRecyclerView.setLayoutManager(mLinearLayoutManager); 
    else 
     mRecyclerView.setLayoutManager(mGridLayoutManager); 
} 

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
{ 
    // Inflate the menu; this adds items to the action bar if it is present. 
    inflater.inflate(R.menu.main, menu); 

    super.onCreateOptionsMenu(menu, inflater); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    switch(item.getItemId()) 
    { 
     case R.id.item_menu_1: 
     { 
      // Change view 
      toggleListGrid(); 
      return true; 
     } 
     default: 
      return super.onOptionsItemSelected(item);  
    } 
} 

......... 
................... 

4.RecyclerView.AdapterRecyclerView上にデータを移入します。ここで

がRecyclerViewについての良いチュートリアルです: Android NavigationView – Fragments With RecyclerView

希望これは〜

+0

詳細なお返事ありがとうございます。しかし、私はステップ2について混乱しています。これは.xml、.javaファイルを参照していますか?のように、RecyclerViewをどこに挿入すればいいですか?どのように宣言しますか? – AndroidDevBro

+0

私は自分の答えを更新しました。 'ListView'と' GridView'の代わりに 'RecyclerView'を使います。 'STEP 1'の' activity_main.xml'から 'ListView'と' GridView'を削除したので、リストとグリッドを表示するために、 'first_fragment.xml'に' RecyclerView'を追加しました。 'RecyclerView'に' Adapter'、 'STEP 3と4'で説明したように2つの' LayoutManager'を使う必要があります。主なものは、あなたの必要に応じてあなたの断片のいずれかにリスト/グリッドを表示することです。 'RecyclerView'と' Fragment'の使い方については、付属のチュートリアルリンクを参照してください。 – FAT

+0

フラグメントのAdapterクラスを作成する必要があるということについて何も言及していませんが、この場合は必要ですか? (ビデオチュートリアルで示されているように) – AndroidDevBro

0

stub_liststub_list ViewStub xml宣言にこのコード行を追加する必要があります。これはappbarのすぐ下に配置する必要があります。あなたはCoordinatorLayoutの下でそのhereについての詳細を読むことができますし、すべてのアプリバーセクション

+0

MainActivity.xml内の両方のViewStubに上記の行を追加しましたが、何も変更されていません。 – AndroidDevBro

関連する問題