AS中級 フラグメント編①問題&解説~Fragmentで1画面に2つの画面を入れる~できるけどダメな例
Fragmentで1画面に2つの画面を入れる際、できるけどダメな例を提示します。
activity_main.xmlや、fragment_top.xml、fragment_bottomは同じです。
ただし、本当にだめなのでしょうか?
なぜダメなのでしょうか?
MainActivity.java
package com.example.fragmentdemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopFragment topFragment = new TopFragment();
BottomFragment bottomFragment = new BottomFragment();
//ここを修正
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container1,topFragment);
transaction.add(R.id.container2,bottomFragment);
transaction.commit();
}
}
TopFragment.java
package com.example.fragmentdemo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.ColorInt;
import androidx.fragment.app.Fragment;
public class TopFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_top, container, false);
}
}
BottomFragment.java
package com.example.fragmentdemo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.ColorInt;
import androidx.fragment.app.Fragment;
public class BottomFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_bottom, container, false);
}
}