4.14作业
看题目看了半天,才明白是怎么回事。。。要创几个布局。。。
用了动态方法创建Fragment。。。
由题意可知,创建了三个界面,一个主界面,两个Fragment界面
首先来看一下主界面的重要布局代码
<LinearLayout
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
</LinearLayout>
<Button
android:id="@+id/btn_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:background="#000000"
android:textColor="#0000ff"
android:text="点击"
android:textSize="30sp"
/>
以及两个Fragment界面,两个界面布局一样,很简单,一下是主要的布局代码
<LinearLayout
android:id="@+id/second"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
>
</LinearLayout>
<TextView
android:gravity="center"
android:id="@+id/btn_two"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:textColor="#ffffff"
android:text="这是第一个Fragment"
android:textSize="20sp"/>
最大头的就是主界面的Java代码了!!!
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Fragment blankFragment;
private Fragment secondFragment;
private boolean skip = true;
private boolean exit = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
blankFragment = new BlankFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.main, blankFragment);
transaction.commit();
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_main:
jump();
break;
}
}
private void jump() {
boolean exit = true;
if (skip) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
if (secondFragment == null) {
secondFragment = new SecondFragment();
transaction.replace(R.id.main, secondFragment);
transaction.commit();
skip = false;
} else {
transaction.replace(R.id.main, secondFragment);
transaction.commit();
skip = false;
}
} else {
Toast.makeText(this, "这是第二个Fragment", Toast.LENGTH_LONG).show();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && exit) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
skip = true;
exit = false;
transaction.replace(R.id.main, blankFragment);
transaction.commit();
return false;
} else {
finish();
}
return super.onKeyDown(keyCode, event);
}
}
当然了,两个Fragment布局的Java代码也要有所改变,以下
public class SecondFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_second,container,false);
return view;
}
}