【问题标题】:Java open Fragment from MainActivityJava 从 MainActivity 打开 Fragment
【发布时间】:2020-07-10 20:30:07
【问题描述】:

我有一个 Main Activity,它为我的不同 Fragment 托管 tabsAdapter 和 ViewPager。我正在尝试从我的主要活动中打开第二个片段(特殊片段)。下面是代码,无法启动特殊片段,其次,无法从特殊片段中引用方法。请帮忙!

主要活动:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Day Events"));
    tabLayout.addTab(tabLayout.newTab().setText("Special Events"));
    tabLayout.addTab(tabLayout.newTab().setText("Notifications"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    final TabsAdapter tabsAdapter = new TabsAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(tabsAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }
        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }
        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        if (bundle.getString("fragment") != null) {

            SpecialFragment specialFragment = (SpecialFragment) tabsAdapter.getItem(1);
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.view_pager, specialFragment).commit();

            specialFragment.setLocation("TEST");

特殊片段sn-p:

public void setLocation(String location)
{
    txtLocation = v.findViewById(R.id.txtLocationSpecialEvent);
    txtLocation.setText(location);
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fragment_container"
tools:context=".MainActivity">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tool_bar"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<androidx.viewpager.widget.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout"/>

【问题讨论】:

  • 请添加logcat
  • 你想让第二个片段默认打开吗?
  • 您好,请尽一切可能提供帮助。谢谢。第二个片段只能在单击通知时打开。如果应用默认打开,则必须打开第一个片段。

标签: java android android-fragmentactivity


【解决方案1】:

好的,我已经成功切换到特殊片段使用

viewPager.setCurrentItem(1);

            SpecialFragment specialFragment = (SpecialFragment) tabsAdapter.getItem(1);
            specialFragment.setLocation(bundle.getString("location"));

但是,Special Fragment 中的 setLocation 方法似乎会导致问题:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.scrollingtext/com.example.scrollingtext.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
    at com.example.scrollingtext.SpecialFragment.setLocation(SpecialFragment.java:359)
    at com.example.scrollingtext.MainActivity.onCreate(MainActivity.java:73)

注意v=View是在OnCreateView中发起的

v = inflater.inflate(R.layout.special_layout, viewGroup, false);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2021-02-10
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多