【问题标题】:i am using tab layout , in one of them i have a button , i want to change the fragment when that button is clicked我正在使用选项卡布局,其中一个我有一个按钮,我想在单击该按钮时更改片段
【发布时间】:2019-04-13 21:46:28
【问题描述】:

我有一个包含三个TabItem 和一个ViewPager 的布局,选项卡正在工作并显示,但是当我想加载新片段时,例如单击其中一个选项卡布局上的按钮,无论我做什么,我都无法更改片段。我想在单击我的一个选项卡上的按钮时加载一个片段,但下面的代码不起作用

getSupportFragmentManager().beginTransaction().
                add(R.id.frame_layout_container,userDetailFragment).commit();

replace也不行,我是android开发的初学者,谁能帮帮我?

额外说明:其中一个我有一个列表视图,我想要的是当我单击该项目时,我将转到有关该项目的详细信息。这是主xml文件中的代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:fitsSystemWindows="true"
    android:id="@+id/drawer_layout"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/LinearLayout">



        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:id="@+id/toolbar"
            android:background="#37548D"
            android:elevation="4dp" />

        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tab_layout"
            android:background="#115A91"
            app:tabSelectedTextColor="#FFF"
            app:tabTextColor="#0A1102"
            >



            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/enter_tab"
                android:text="@string/inter_fragment"
                />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/contact_tab"
            android:text="@string/fragment_contacts"
            />

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/register_tab"
                android:text="@string/register_fragment"
                />



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

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/frame_layout_container"
            />


    </LinearLayout>


    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/navigation_view"
        app:headerLayout="@layout/drawer_layout"
        app:menu="@menu/main_menu"
        />







</android.support.v4.widget.DrawerLayout>

更新:这是我的 UserDetailFragment 的代码,其中是 ListFragment

public class ContactsFragment extends ListFragment {

    CallBacks callBacks;

    public ContactsFragment() { }
    ArrayList<UserObject> userObjects;
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            userObjects = intent.getParcelableArrayListExtra(Intent_Service.SERVICE_PAYLOAD);
            ArrayAdapter<UserObject> userObjectArrayAdapter = new UserArrayAdapter(context,0,userObjects);
            setListAdapter(userObjectArrayAdapter);
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(getActivity(), Intent_Service.class);
        getActivity().startService(intent);

        LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).
                registerReceiver(broadcastReceiver,new IntentFilter(Intent_Service.SERVICE_MESSAGE));
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_contacts,null);
    }


    public void onListItemClick(ListView l, View v, int position, long id) {
        UserObject userObject = userObjects.get(position);
        this.callBacks.send_user_object(userObject);
    }

    public interface CallBacks {
        public void send_user_object(UserObject userObject);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.callBacks = (CallBacks)context;
    }
}

这是我的 MainActivity 的代码:

public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks {

    android.support.v7.widget.Toolbar toolbar;
    PageAdapter pageAdapter;
    ViewPager viewPager;
    TabLayout tabLayout;
    TabItem contacts;
    TabItem register;
    TabItem signIn;

//    ArashBroadCast broadcastReceiver = new ArashBroadCast(this);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page_drawer);
        tab_variable_initialiser();
        setSupportActionBar(toolbar);

        NavigationView navigationView = findViewById(R.id.navigation_view);
        navigationView.setItemIconTintList(null);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                if(tab.getPosition() == 1) {
                    toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.tab_contacts));
                    tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.main_contacts));
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(MainActivity.this,R.color.status_contacts));
                    }
                } else if(tab.getPosition() == 2) {
                    toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.tab_register));
                    tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.main_register));
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(MainActivity.this,R.color.status_register));
                    }
                } else {
                    toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.tab_signin));
                    tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.main_signin));
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(MainActivity.this,R.color.status_signin));
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

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

            }
        });

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//        tabLayout.setupWithViewPager(viewPager);

    }


    protected void onDestroy() {
        super.onDestroy();
    }

    public void tab_variable_initialiser() {
        this.tabLayout = findViewById(R.id.tab_layout);
        this.contacts = findViewById(R.id.contact_tab);
        this.register = findViewById(R.id.register_tab);
        this.signIn = findViewById(R.id.enter_tab);
        this.viewPager = findViewById(R.id.view_pager);
        this.pageAdapter = new PageAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
        this.viewPager.setAdapter(pageAdapter);

        this.toolbar = findViewById(R.id.toolbar);

    }

    @Override
    public void send_user_object(UserObject userObject) {
        UserDetailFragment userDetailFragment = new UserDetailFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.contact_fragment_layout,userDetailFragment).commit();
    }
}

如果我使用R.id.contact_tab,它可以工作,但它不会替换整个片段,而是userDetailFragment 显示在列表下方。 我得到了错误:No view found for id 0x7f080031 (arash.samandar.recyclerview_final:id/contact_tab) for fragment UserDetailFragment{e489f08 #3 id=0x7f080031}

【问题讨论】:

    标签: android android-fragments android-tablayout


    【解决方案1】:

    您应该将您的viewpager 与您的tablayout 链接起来

    tabLayout.setupWithViewPager(viewPager)
    

    编辑

    如何为您的TabLayout 设置样式

    首先添加你的风格:

    <style name="AppTabLayoutDetail" parent="Widget.Design.TabLayout">
        <item name="tabIndicatorColor">@color/colorPrimary</item>
        <item name="tabIndicatorHeight">2dp</item>
        <item name="tabPaddingStart">6dp</item>
        <item name="tabPaddingEnd">6dp</item>
        <item name="tabBackground">?attr/selectableItemBackground</item>
        <item name="tabTextAppearance">@style/AppTabTextAppearance</item>
        <item name="tabSelectedTextColor">@color/colorPrimary</item>
    </style>
    
    <style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">12sp</item>
        <item name="android:textColor">#b3ffffff</item>
        <item name="textAllCaps">false</item>
    </style>
    

    然后将其添加到您的TabLayout

      <android.support.design.widget.TabLayout
            ......
            style="@style/AppTabLayoutDetail"
            ......
          />
    

    不要忘记从您的 tablayout 中删除侦听器并将其与您的 pager 链接

    【讨论】:

    • 它不起作用,我试过了,它甚至会删除选项卡上的文本。你知道为什么吗?
    • 删除,什么意思?你检查过你的tablayout风格吗?文字颜色和背景设置
    • 是的,我自己写的样式,如果我必须修复删除文本,问题是它不起作用,用你建议的方法,我不能吹,在我的 ListFragment 选项卡中膨胀一个片段。它只是不起作用。什么都没有发生,你的方法没有帮助,你能更具体一点吗?你想让我更新我的代码吗?
    • 我更新并添加了我的 MainActivity 类和我的 UserDetailFragment。我想要的是当我单击其中一个列表视图项目时,我想要一个新片段显示该项目的详细信息。
    • 你必须在 tablayout 上移除你的监听器,并且你必须在你的样式文件中定义你的样式并将它添加到你的 widget.TabLayout android:styles 的属性样式中
    【解决方案2】:

    经过大量练习,我找到了解决方案: 我学到了什么:

    您必须使用 FragmentPagerAdapter 来处理您的片段更改。有 3 件重要的事情:

    1) 删除之前的片段。

    2) 调用notifyDataSetChanged()刷新页面列表。

    3) 如果请求旧片段,则在 getItemPosition 中返回 POSITION_NONE。

    这是我在左右选项卡中使用的练习代码。我会根据用户的操作动态更改片段

    这是我的代码:

    public class MyPager extends ViewPager {
    
        private MyPagerAdapter mMyPagerAdapter;
    
        public MyPager(Context context, FragmentActivity activity) {
            super(context);
    
            mMyPagerAdapter = new MyPagerAdapter(activity.getSupportFragmentManager());
            setAdapter(mMyPagerAdapter);
    
        }
        public void replaceLeftFragment(Fragment fragment) {
            mMyPagerAdapter.replaceLeftFragment(fragment);
        }
        public void replaceRightFragment(Fragment fragment) {
            mMyPagerAdapter.replaceRightFragment(fragment);
        }
    }
    
    public class MyPagerAdapter extends FragmentPagerAdapter {
    
        private FragmentManager mFragmentManager;
        private Fragment mLeftFragment;
        private Fragment mRightFragment;
    
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
            mFragmentManager = fm;
        }
    
        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return mLeftFragment;
            } else {
                return mRightFragment;
            }
        }
    
        @Override
        public int getCount() {
            final int nbLeft = (mLeftFragment == null) ? 0 : 1;
            final int nbRight = (mRightFragment == null) ? 0 : 1;
            return (nbLeft + nbRight);
        }
    
        public void replaceLeftFragment(Fragment fragment) {
            if (mLeftFragment != null) {
                mFragmentManager.beginTransaction().remove(mLeftFragment).commit();
            }
            mLeftFragment = fragment;
            notifyDataSetChanged();
        }
        public void replaceRightFragment(Fragment fragment) {
            if (mRightFragment != null) {
                mFragmentManager.beginTransaction().remove(mRightFragment).commit();
            }
            mRightFragment = fragment;
            notifyDataSetChanged();
        }
    
        @Override
        public int getItemPosition(Object object) {
            if ((object!=mLeftFragment) && (object!=mRightFragment)) {
                return POSITION_NONE;
            }
            return super.getItemPosition(object);
        }
    
    }
    

    如果对你有帮助,请点个赞,我现在会的。 谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      相关资源
      最近更新 更多