Android
Fragment
AndroidStudio
android開発
TabLayout

[Android] Tab上でFragmentからFragmentの実装メモ

TabLayout上でのFragmentとFragment間の簡単な画面遷移の実装メモです。

ToolbarにMenuItemを表示しているコードも含まれています。

勉強中なので、おかしい部分があるかもしれないです、、


作ったもの

3つのタブがあり、TAB01に画面遷移するボタンがあります。

スクリーンショット 2019-02-07 21.36.26.png

*画面遷移後

Backボタンを押すとTAB01トップに戻ります。

スクリーンショット 2019-02-07 21.36.49.png


MainActivity


MainActivity.java

public class MainActivity extends AppCompatActivity {

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

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

OriginalFragmentPagerAdapter adapter = new
OriginalFragmentPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.viewPager);
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(adapter);

TabLayout tabLayout = findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}



Tab01Fragment


Tab01Fragment.java

public class Tab01Fragment extends Fragment {

public Tab01Fragment() {
// Required empty public constructor
}

private int cnt = 0;

public static Tab01Fragment newInstance(int count){
//Fragment インスタンス化
Tab01Fragment tab01Fragment = new Tab01Fragment();

//Bundleにパラメータを設定
Bundle args = new Bundle();
args.putInt("Counter", count);
tab01Fragment.setArguments(args);

return tab01Fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab01, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

Bundle args = getArguments();

if(args != null){
int count = args.getInt("Counter");
cnt = count + 1;
}

Button appButton = view.findViewById(R.id.Button);
appButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){

FragmentManager fragmentManager = getFragmentManager();

if(fragmentManager != null){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

//BackStackを設定
fragmentTransaction.addToBackStack(null);

fragmentTransaction.replace(R.id.container, Tab01NextFragment.newInstance(cnt));
fragmentTransaction.commit();
}
}
});
}
}



Tab01NextFragment


Tab01NextFragment.java

public class Tab01NextFragment extends Fragment {

public Tab01NextFragment() {
// Required empty public constructor
}

private int cnt = 0;

public static Tab01NextFragment newInstance(int count){
//Fragment インスタンス化
Tab01NextFragment tab01NextFragment = new Tab01NextFragment();

//Bundleにパラメータを設定
Bundle args = new Bundle();
args.putInt("Counter", count);
tab01NextFragment.setArguments(args);

return tab01NextFragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab01_next, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

Bundle args = getArguments();

if(args != null){
int count = args.getInt("Counter");
cnt = count + 1;
}

Button appButton = view.findViewById(R.id.backButton);
appButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){

FragmentManager fragmentManager = getFragmentManager();

if(fragmentManager != null){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

//BackStackを設定
fragmentTransaction.addToBackStack(null);

fragmentTransaction.replace(R.id.container, Tab01Fragment.newInstance(cnt));
fragmentTransaction.commit();
}
}
});
}
}



OriginalFragmentPagerAdapter

TabLayoutとviewPagerをくっつけるAdapterです。


OriginalFragmentPagerAdapter.java

public class OriginalFragmentPagerAdapter extends FragmentPagerAdapter {

private CharSequence[] tabTitles = {"Tab01", "Tab02", "Tab03"};

public OriginalFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}

@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab01Fragment();
case 1:
return new TabSystemFragment();
case 2:
return new TabAbnormalFragment();
default:
return null;
}
}

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



Layout / activity_main.xml


activity_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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/appbar_padding_top"
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:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:title="@string/app_name">

</android.support.v7.widget.Toolbar>

</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/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left" />

<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Center" />

<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right" />
</android.support.design.widget.TabLayout>

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

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

</LinearLayout>

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



Layout / fragment_tab01.xml


fragment_tab01.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout 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:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Tab01Fragment">

<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/Button"
android:layout_width="211dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="ToFragment"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.393" />
</android.support.constraint.ConstraintLayout>

</FrameLayout>



Layout / fragment_tab01_next.xml


fragment_tab01_next.xml

<?xml version="1.0" encoding="utf-8"?>

<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"
android:background="#ff97"
android:clickable="true"
tools:context=".Tab01NextFragment">

<Button
android:id="@+id/backButton"
android:layout_width="157dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Back Tab01"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.157" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="132dp"
android:layout_marginEnd="8dp"
android:text="画面遷移完了"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>



menu / menu_main.xml

Toolbarのメニューボタン。


menu_main.xml

<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="com.example.hayato.sample_iseandroid.MainActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
</menu>

おわり!