我正在學習Android,並且遇到了Fragments問題。我有一個簡單的項目,在主要活動中有兩個按鈕和一個「片段佔位符」。我已經爲該項目添加了兩個片段。當按下按鈕1時,片段1被加載到片段佔位符中。當按下按鈕2時,片段2被加載到片段佔位符中。Android片段中的按鈕仍然可見
我遇到的問題是,當我添加一個按鈕到fragment1時,按鈕仍然可見,當我按下button2來填充fragment2的片段佔位符。這不會發生在其他視圖上(如複選框或明文編輯器)。
是否有一些技巧需要確保按鈕屬於一個片段,並且只有當該片段可見時纔會顯示?
這裏是我的片段1佈局:
這裏是我的佈局fragment2:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.FragmentTwo">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_fragment_two"
android:background="#cc2525"/>
</FrameLayout>
下面是我的主要活動的佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="fragmentexample.MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment1"
android:id="@+id/button"
android:onClick="ChangeFragment"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment2"
android:id="@+id/button2"
android:onClick="ChangeFragment"/>
<fragment
android:id="@+id/fragment_place"
android:name="layout.FragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/fragment_fragment_two"/>
</LinearLayout>
這就是我如何變化的碎片:
public void ChangeFragment(View view)
{
Fragment fragment =
(view == findViewById(R.id.button)) ? new FragmentOne() : new FragmentTwo();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_place, fragment)
.commit();
}
我只是不明白爲什麼button3總是可見的。我期待它在切換到fragment2時不可見,但仍然可見。
==不按照你的想法工作。 –
使用view.getId()進行比較。 FindViewById是一種浪費。 – lionscribe
@ Code-Apprentice - 請參閱我對Samuel Robert的評論。這是一個三元的任務,並且按照我的想法工作。爲「片段」分配值不是問題。 –