我正在使用选项卡布局,在其中一个中我有一个按钮,我想在单击该按钮时更改片段

时间:2019-04-13 21:46:28

标签: android android-fragments android-tablayout

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

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

replace也无效,我是android开发的初学者,有人可以帮我吗?

额外的解释:在其中之一中,我有一个listview,我想要的是当我单击该项目时,我将转到该项目的详细信息。这是主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>

update:这是我的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}

2 个答案:

答案 0 :(得分:0)

您应该将viewpagertablayout关联起来

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链接

答案 1 :(得分:0)

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

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

1)删除上一个片段。

2)调用class BinarySearchTree { public: Node* root; int countHight=0; //in this line BinarySearchTree() { root = NULL; } ~BinarySearchTree() { return; } void insert(int value); void display(Node* temp); void DisplayByLevel(Node* temp,int level); }; 刷新页面列表。

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

这是我在“向左”和“向右”选项卡上使用的练习代码。然后根据用户的操作动态更改片段

这是我的代码:

notifyDataSetChanged()

如果它对您有所帮助,请竖起大拇指,我现在会这样做。 谢谢。