我无法将我的MainActivity链接到任何片段。
这里是我的MainActivity.java:将LinearLayout活动链接到片段
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn1,btn2,btn3,btn4,btn5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn3=(Button)findViewById(R.id.btn3);
btn4=(Button)findViewById(R.id.btn4);
btn5=(Button)findViewById(R.id.btn5);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
}
@Override
public void onClick(View v) {
onItemSelected(v.getId());
/*Fragment fragment=null;
int id=v.getId();
switch(id){
case R.id.btn1:
fragment=new Btn1Fragment();
break;
case R.id.btn2:
fragment=new Btn2Fragment();
break;
case R.id.btn3:
fragment=new Btn3Fragment();
break;
case R.id.btn4:
fragment=new Btn4Fragment();
break;
case R.id.btn5:
finish();
}
FragmentManager fm=getSupportFragmentManager();
fm.beginTransaction().replace(R.id.main,fragment).commit();
LinearLayout linear=(LinearLayout)findViewById(R.id.main);*/
}
private void onItemSelected(int id) {
Fragment fragment=null;
switch(id){
case R.id.btn1:
fragment=new Btn1Fragment();
break;
case R.id.btn2:
fragment=new Btn2Fragment();
break;
case R.id.btn3:
fragment=new Btn3Fragment();
break;
case R.id.btn4:
fragment=new Btn4Fragment();
break;
case R.id.btn5:
finish();
}
FragmentManager fm=getSupportFragmentManager();
fm.beginTransaction().replace(R.id.main,fragment).addToBackStack(null).commit();
}
而且片段:
public class Btn1Fragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_btn1,container,false);
return view;
}
帮助我的人。
读https://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/ –
尝试在地方取代添加片段的话,并确保您要添加的片段到主要活动 –
采取的framelayout我已经尝试添加以及狗屎不起作用xD 是的..我添加它,虽然我在Main上使用LinearLayout。 –