无法从viewpager中的片段编辑actionbar标题

8xiog9wr  于 2021-07-09  发布在  Java
关注(0)|答案(6)|浏览(372)

我有一张单人床 Activity 它通过一个 ViewPager . 在活动的 onCreate 方法我正在使用以下代码来更改 ActionBar 职务:

Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if(getSupportActionBar() != null) {
        getSupportActionBar().setTitle(getResources().getString(R.string.custom_title));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

它工作得很好,但我无法尽快改变它 Fragment 变得可见。为了检测它,我实现了:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {

    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser && getContext() != null) {
            ((MainActivity) getContext()).editActionBarTitle("new title");
    }
}

以下是 editActionBarTitle :

public void editActionBarTitle(String title) {
     if(getSupportActionBar() != null) {
         getSupportActionBar().setTitle(title);
         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
     }
}

我可以看到,只要一个片段变得可见,就会调用这个方法,但是它对actionbar的标题没有任何影响。为了正确编辑标题,我遗漏了什么?
编辑
我也尝试过 addOnPageChangeListenerviewPager ,我可以看出 onPageSelected 调用,但对标题没有影响,以下是mainactivity的示例:

public class MainActivity extends BaseActivity {   

    private NoScrollViewPager mViewPager;
    private SectionsPagerAdapter mAdapter;

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

        // Toolbar initialization
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null) {
            getSupportActionBar().setTitle("MainActivity");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // ViewPager initialization
        mViewPager = findViewById(R.id.containter);
        setupViewPager();
    }

    private void setupViewPager() {

        mAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mAdapter.addFragment(new Fragment1(), "Fragment 1");
        mAdapter.addFragment(new Fragment2(), "Fragment 2");
        mAdapter.addFragment(new Fragment3(), "Fragment 3");

        mViewPager.setOffscreenPageLimit(mAdapter.getCount());
        mViewPager.setAdapter(mAdapter);

        // viewPager event listener
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

            @Override
            public void onPageSelected(int position) {
                setTitle("fragment " + position);
                if(getSupportActionBar() != null) {
                    getSupportActionBar().setTitle("fragment " + position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) { }
        });
    }

    public void setViewPager(int position) { mViewPager.setCurrentItem(position); }
}

这是习俗 ViewPager 班级:

public class NoScrollViewPager extends ViewPager {

    // Disable horizontal scrolling in ViewPager
    private boolean isPagingEnabled = false;

    public NoScrollViewPager(Context context) {
        super(context);
    }

    public NoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    @SuppressLint("AndroidLintClickableViewAccessibility")
    public boolean onTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}

这是自定义适配器类:

public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    private FragmentManager fragmentManager;

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
        fragmentManager = fm;
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public Fragment getItem(int position) { return mFragmentList.get(position); }

    @Override
    public int getCount() { return mFragmentList.size(); }

    @Override
    public int getItemPosition(Object object) { return POSITION_NONE; }

}
ztigrdn8

ztigrdn81#

你也可以使用 viewPager.addOnPageChangeListener() 添加一个侦听器,该侦听器将在页面更改或以增量方式滚动时调用
viewPager.addOnPageChangeListener() 你需要在你的书名中设置标题 actionbar 内部 onPageSelected() 返回当前选定页的当前值 viewpager 样本代码

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {

            if (i == 0) {
                getSupportActionBar().setTitle("Fragment One");
            } else if (i == 1) {
                getSupportActionBar().setTitle("Fragment Two");
            } else if (i == 2) {
                getSupportActionBar().setTitle("Fragment three");
            } else if (i == 3) {
                getSupportActionBar().setTitle("Fragment four");
            } else if (i == 4) {
                getSupportActionBar().setTitle("Fragment Five");
            }

        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });

这是我的工作代码
活动代码

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class HomeActivity extends AppCompatActivity {

    private NoScrollViewPager mViewPager;
    private SectionsPagerAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        // Toolbar initialization
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setTitle("Fragment One");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // ViewPager initialization
        mViewPager = findViewById(R.id.containter);

        findViewById(R.id.btnOne).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(0);
            }
        });
        findViewById(R.id.btnTwo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(1);
            }
        });
        findViewById(R.id.btnThree).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewPager.setCurrentItem(2);
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {

                if (i == 0) {
                    getSupportActionBar().setTitle("Fragment One");
                } else if (i == 1) {
                    getSupportActionBar().setTitle("Fragment Two");
                } else if (i == 2) {
                    getSupportActionBar().setTitle("Fragment three");
                }

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        setupViewPager();

    }

    private void setupViewPager() {

        mAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mAdapter.addFragment(new Fragment1(), "Fragment 1");
        mAdapter.addFragment(new Fragment2(), "Fragment 2");
        mAdapter.addFragment(new Fragment3(), "Fragment 3");

        mViewPager.setOffscreenPageLimit(mAdapter.getCount());
        mViewPager.setAdapter(mAdapter);

        // viewPager event listener
    }

}

布局

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnOne"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Frag 1" />

        <Button
            android:id="@+id/btnTwo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Frag 2" />

        <Button
            android:id="@+id/btnThree"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Frag 3" />

    </LinearLayout>

    <neel.com.demo.NoScrollViewPager
        android:id="@+id/containter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

输出
https://www.youtube.com/watch?v=ytjogokj1zq

qzwqbdag

qzwqbdag2#

我在最近的一个项目中遇到了这个问题。最后,我为每个片段设计了单独的工具栏,每个片段都有自己的标题。我确实用过:

Theme.MaterialComponents.NoActionBar
jhkqcmku

jhkqcmku3#

更改onpageselected from中的代码

setTitle("fragment " + position);
if(getSupportActionBar() != null) {
    getSupportActionBar().setTitle("fragment " + position);
}

为了这个

toolbar.setTitle(title);

扩展appcompatactivity而不是baseactivity。在oncreate中保留相同的代码

5rgfhyps

5rgfhyps4#

唯一合法的理解方式 FragmentA 正在中显示 ViewPager 对…有React OnPageChangeListener 回调。
采用本答案中提到的技术,您可能会得到以下代码:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(final int i) {
            MyAdapter adapter = ((MyAdapter) viewPager.getAdapter());
            TitleOwner titleOwner = adapter.getTitleOwner(index);
            String title = titleOwner.getTitle();
            getSupportActionBar().setTitle(title);
        }

        @Override
        public void onPageScrollStateChanged(final int i) {
        }

        @Override
        public void onPageScrolled(final int i,final float v,final int i1) {
        }
});

这假设在 ViewPager ,实现 TitleOwner :

interface TitleOwner {
    String getTitle();
}

和片段类:

class MainScreenFragment extends Fragment implements TitleOwner {
    ...
    @Override
    public String getTitle() {
        return "Main Screen";
    }
}
kx1ctssn

kx1ctssn5#

在oncreateview方法中尝试将其转换为片段。也许对你有帮助。

if(getActivity() != null){
     getActivity().setTitle("Your title");
}

如果在片段中使用viewpager,那么可以使用

@Override
    public void setUserVisibleHint(boolean isVisible) {
        super.setUserVisibleHint(isVisible);

        if (isVisible) {
            if(getActivity() != null){
               getActivity().setTitle("Your title");
            }
        }
    }
qfe3c7zg

qfe3c7zg6#

你能检查一下你用的是不是电话机吗 NoActionBar 主题。例如 Theme.AppCompat.Light.NoActionBar 或者 Theme.MaterialComponents.NoActionBar .

相关问题