替换选项卡内的片段

时间:2016-05-31 15:51:16

标签: android android-layout android-fragments

我有4个标签。我们只说Tab Ende(FragmentEnde),Tab Kidung(FragmentKidung),Tab Renungan(FragmentRenungan)和Tab About(FragmentAbout)。
每个标签都使用片段。

在Tab Renungan(FragmentRenungan)里面,我有2个按钮,让我们说按钮列表和按钮搜索。
当我单击按钮列表时,我想用片段RenunganMonthly替换它。我使用ViewPager进行布局。

目前,我可以替换片段Renungan,但它不会显示片段RenunganMonthly的内容。我该怎么做才能在ViewPager上显示内容?

PagerAdapter.java

package com.tektokan.apps.rmh;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int mNumOfTabs;

    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                FragmentEnde ende = new FragmentEnde();
                return ende;
            case 1:
                FragmentKidung kidung = new FragmentKidung();
                return kidung;
            case 2:
                FragmentRenungan renungan = new FragmentRenungan();
                return renungan;
            case 3:
                FragmentAbout about = new FragmentAbout();
                return about;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }

}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/main_layout"
    android:orientation="vertical"
    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"
    tools:context=".MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="2dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_below="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="fill_parent" />

</LinearLayout>

MainActivity.java

package com.tektokan.apps.rmh;

import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

public class MainActivity extends AppCompatActivity implements FragmentRenungan.OnFragmentInteractionListener {

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

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ende));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.kidung));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.renungan));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.about));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(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) {
                viewPager.setCurrentItem(tab.getPosition());
            }
        });

    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}

FragmentRenungan.java

package com.tektokan.apps.rmh;


import android.app.DatePickerDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentRenungan extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public FragmentRenungan() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RenunganFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentRenungan newInstance(String param1, String param2) {
        FragmentRenungan fragment = new FragmentRenungan();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_renungan, container, false);

        Button daftar = (Button) view.findViewById(R.id.renDaftar);
        Button cari = (Button) view.findViewById(R.id.renCari);
        daftar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.pager, new FragmentRenunganMonthly()).addToBackStack(null).commit();
            }
        });

        cari.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePicker();
            }
        });

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void showDatePicker() {
        DatePickerFragment date = new DatePickerFragment();

        Bundle args = new Bundle();
        args.putString("title", "Pilih Tanggal Renungan");

        date.setArguments(args);
        date.setCallBack(ondate);
        date.show(getFragmentManager(), "DatePicker");
    }

    DatePickerDialog.OnDateSetListener ondate = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            int bulan = monthOfYear + 1;
            String tanggal = String.valueOf(year) + " - " + String.valueOf(bulan) + " - " + String.valueOf(dayOfMonth);

            Calendar cal = Calendar.getInstance();
            cal.set(year, monthOfYear, dayOfMonth);
            Date date = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String abc = sdf.format(date);
        }
    };
}

fragment_renungan.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:weightSum="1"
            android:layout_weight="0.5">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5"
                android:padding="5dp">
                <Button
                    android:id="@+id/renDaftar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:text="Daftar Renungan"
                    android:background="@drawable/button"
                    android:drawableTop="@drawable/ic_list_ren" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5"
                android:padding="5dp">
                <Button
                    android:id="@+id/renCari"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:text="Cari Renungan"
                    android:background="@drawable/button"
                    android:drawableTop="@drawable/ic_event_ren" />
            </LinearLayout>
        </TableRow>

    </TableLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.CardView
            android:id="@+id/renHariIni"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/thumbnail"
                    android:maxLines="3"
                    android:padding="8dp"
                    android:text="Judul"
                    android:textColor="#222"
                    android:textStyle="bold"
                    android:textSize="22dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/title"
                    android:maxLines="3"
                    android:padding="8dp"
                    android:text="Deskripsi"
                    android:textColor="#666"
                    android:textSize="14dp" />

            </LinearLayout>
        </android.support.v7.widget.CardView>
    </LinearLayout>

</LinearLayout>

FragmentRenunganMonthly.java

package com.tektokan.apps.rmh;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class FragmentRenunganMonthly extends Fragment {

    public FragmentRenunganMonthly() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("testing", "testing");
        return inflater.inflate(R.layout.fragment_renungan_monthly, container, false);
    }

}

fragment_renungan_monthly.xml

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fragment Renungan Monthly" />
</LinearLayout>
</FrameLayout>

1 个答案:

答案 0 :(得分:0)

我不知道为什么视图没有更新。这是一个解决方法:

创建基本片段FragmentRenunganBase并在PagerAdapter而不是FragmentRenungan中使用它。

FragmentRenunganBase内,默认情况下会膨胀FragmentRenungan

    Fragment fragment = null;
    try {
        fragment = new FragmentRenungan();
    } catch (Exception e) {
        e.printStackTrace();
    }
    FragmentManager fragmentManager = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();

fragment_renungan_base.xml(示例)

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"> 

    <FrameLayout android:id="@+id/container" android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

通过在FragmentRenungan中实施界面,FragmentRenunganBase中的处理按钮点击(片段通讯:https://developer.android.com/training/basics/fragments/communicating.html#DefineInterface

FragmentRenunganBase中的界面方法内,充气/添加FragmentRenunganMonthly

Fragment fragment = null;
    try {
        fragment = new FragmentRenunganMonthly();
    } catch (Exception e) {
        e.printStackTrace();
    }
    FragmentManager fragmentManager = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();