Android Studio -Fragment

xiaoxiao2021-02-27  268

喵呜~今天来写片段了~

点击App->New-.>Fragment->Fragment(blank)~就会出现啦(Include的两个东西不需要喔,factory methods和Interface feedbacks)

然后呢,就会有新建了Fragment.java和.xml的两个文件,到Fragmen.xml随便写点什么,background,Button,Textview,然后到activity_main.xml,新建个Button,给它个@id/bn

然后到MainActivity.java

これを打ち込むでよいだ

package com.example.fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { boolean status=false; Button bn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bn=(Button)findViewById(R.id.bn); bn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { android.app.FragmentManager fragmentManager=getFragmentManager(); android.app.FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction(); if(!status) { FragmentOne f1=new FragmentOne(); fragmentTransaction.add(R.id.fragment_container,f1); fragmentTransaction.commit(); bn.setText("LOAD SECOND FRAGMENT"); status=true; } else { FragmentTwo f2=new FragmentTwo(); fragmentTransaction.add(R.id.fragment_container,f2); fragmentTransaction.commit(); bn.setText("LOAD FIRST FRAGMENT"); status=false; } } }); } }

转载请注明原文地址: https://www.6miu.com/read-9917.html

最新回复(0)