0
夥計們我迷失了我的想法,我希望我的主要活動用按鈕顯示UI,一旦我點擊了按鈕,我希望片段打開,但我只是看起來無法正確,我知道我必須創建一個ViewGroup容器,所以我可以使用Transaction.add方法,但我不知道下一步該做什麼或放哪裏。請幫助,提前致謝。通過OnClickListner實例化活動中的片段
Main.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Fragment;
import android.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.btnFragmentA);
b1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Fragment newFragment = new Fragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment1 , newFragment);
transaction.commit();
}
});
}
}
片段
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentA extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.a_fragment, container, false);
}
}
主要XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.dane.fragmenttest.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment A"
android:id="@+id/btnFragmentA"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
片段XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="0">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the fragment"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />
</LinearLayout>