我创建了一个基本上具有导航抽屉的应用程序,我希望在活动启动而不是主活动时加载一个片段“ home”。 任何想法如何做到。
答案 0 :(得分:1)
您可以调用此方法来查看片段。在您的情况下,请在您的onCreate()
//Fragment Changer
public void changeFragment(Fragment targetfragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_fragment, targetfragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commitAllowingStateLoss();
}
示例用法
changeFragment(new YourFragment());
答案 1 :(得分:0)
基本解决方案可以在您的onCreate
方法中实现类似以下代码的内容。
// get fragment manager
FragmentManager fm = getFragmentManager();
// replace
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_layout, new HomeFragment());
ft.commit();
答案 2 :(得分:0)
您的活动:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public String getHelloMessage() {
return "Hello!";
}
}
您的视图:
public class MainView extends Fragment {
// Declarations
private Button testButton;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_view, container, false);
// Getting the reference of controller from Application
MainController mainController = Application.getInstance().getMainController();
// Initializing view objects
testButton = view.findViewById(R.id.test_button);
// Setting actions
testButton.setOnClickListener(mainController.getTestAction());
return view;
}
// Reference to the view Object
public Button getTestButton() {
return testButton;
}
您的main_activity.xm l连接片段
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/containerMainView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/mainView"
android:name="com.template.views.MainView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
您的main_view.xml文件为您的最终视图定义
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/test_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/say_hello" />
</RelativeLayout>