先写出界面顶部top
然后底部buttom
注意bottom不需要放在底部,因为后续放在main.xml中的时候,FrameLayout权重设置为1,会将头顶部分开。
主页面main.xml就是将写好的top和bottom引用进来,中间放一个FrameLayout显示内容,如下
然后写四个按钮tab,如下
再用四个fragment关联tab,比如
public class Fragment1 extends Fragment{
public Fragment1() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.tab01, container,false);
}
}
最后编辑mainactivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "123";
private Fragment fragment1,fragment2,fragment3,fragment4;
private FragmentManager manager;
private LinearLayout linearLayout1,linearLayout2,linearLayout3,linearLayout4;
private FragmentTransaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout1=findViewById(R.id.linearlayout11);
linearLayout2=findViewById(R.id.linearlayout22);
linearLayout3=findViewById(R.id.linearlayout33);
linearLayout4=findViewById(R.id.linearlayout44);
fragment1=new Fragment1();
fragment2=new Fragment2();
fragment3=new Fragment3();
fragment4=new Fragment4();
manager=getSupportFragmentManager();
initial();
hidden();
linearLayout1.setOnClickListener(this);
linearLayout2.setOnClickListener(this);
linearLayout3.setOnClickListener(this);
linearLayout4.setOnClickListener(this);
}
private void initial() {
transaction=manager.beginTransaction()
.add(R.id.frameLayout,fragment1)
.add(R.id.frameLayout,fragment2)
.add(R.id.frameLayout,fragment3)
.add(R.id.frameLayout,fragment4);
transaction.commit();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.imageButton1:select(1);
break;
case R.id.imageButton2:select(2);
break;
case R.id.imageButton3:select(3);
break;
case R.id.imageButton4:select(4);
break;
};
}
private void select(int i) {
hidden();
switch (i) {
case 1: showfragment(fragment1);
break;
case 2: showfragment(fragment2);
break;
case 3: showfragment(fragment3);
break;
case 4: showfragment(fragment4);
break;
}
}
private void showfragment(Fragment fragment) {
transaction.show(fragment);
}
private void hidden() {
transaction=manager.beginTransaction()
.hide(fragment1)
.hide(fragment2)
.hide(fragment3)
.hide(fragment4);
transaction.commit();
}
}
最终效果如下
代码
https://github.com/luludadaa?tab=repositories