在指定空间内切换片段

时间:2016-06-25 16:50:50

标签: android listview android-fragments

我有一个布局,MainScreen.java有以下设计。

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

<include layout="@layout/toolbar"
    />

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

工具栏将是应用程序的标题。 tab_and_view将包含tabview和framelayout

这里是tab_and_view.xml的布局文件

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

<com.android.luftschlafer.engdictionary.Tab.SlidingTabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorAccent"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:layout_weight="1" />
</LinearLayout>

我制作了一些标签:主页,搜索,设置和关于应用。所有这些都将在ViewPager中显示其内容。

在主页中,只有一个ListView项。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Corr_Pages.HomePage">

<!-- TODO: Update blank fragment layout -->
<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/home_function_list"/>
</RelativeLayout>

HomePage.java的代码:

public class HomePage extends BaseFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "Home";
private static final String ind_color="IndicatorColor";
private static final String div_color="DividerColor";


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

private OnFragmentInteractionListener mListener;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param tab_name Parameter 1.

 * @return A new instance of fragment HomePage.
 */
// TODO: Rename and change types and number of parameters
public static HomePage newInstance(String tab_name, int indicatorColor,int   
dividerColor,int iconResId) {
    HomePage fragment = new HomePage();
    fragment.setTitle(tab_name);
    fragment.setIndicatorColor(indicatorColor);
    fragment.setDividerColor(dividerColor);

    fragment.setIconResId(iconResId);

    //Pass out data
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, tab_name);
    args.putInt(ind_color,indicatorColor);
    args.putInt(div_color,dividerColor);
    fragment.setArguments(args);
    return fragment;
}

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

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

//This method will be done by
@Override
public void onViewCreated(View v, final Bundle savedInstanceState){
    //Initialize all visual elements here
    final LayoutInflater inflater= LayoutInflater.from(getContext());//Test
    ListView lv=(ListView) v.findViewById(R.id.home_function_list);

    //Initialize the list items and their corresponding adapter
    String[] SampleSelections=new String[] {"New things","Most common words","Recommendation from Wilson"};
    ArrayAdapter<String> adapter= new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, SampleSelections);
    lv.setAdapter(adapter);

    //Declare the events
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                //Toasts will be replaced by appropriate methods soon
                case 0:
                    Toast.makeText(getContext(),"New Contents are coming",Toast.LENGTH_SHORT).show();
                    declare_new_content_page();
                    break;
                case 1:
                    Toast.makeText(getContext(),"There are some most common words",Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(getContext(),"Wilson's recommendation",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    //Nothing is selected
                    break;
            }
        }
    });
}

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

@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;
}

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
}

/**
 * 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);
}

//Handles the operation of new content page.
private void declare_new_content_page(){
    //Declare widgets here
                FragmentManager fm=getFragmentManager();
                FragmentTransaction ftran=fm.beginTransaction();
                ftran.replace(R.id.tab_and_view,NewContent.newInstance("NewContent"));
                ftran.commit();
    }
}

在MainScreen.java的ListView中,它有三个选择:什么是新的,最常见的单词和推荐。现在,如果我按下什么是新的,则应在ViewPager中显示一个名为NewContent.java的新片段。我尝试使用以下代码执行此操作:

FragmentManager fm=getFragmentManager();
FragmentTransaction ftran=fm.beginTransaction();      
ftran.replace(R.id.tab_and_view,NewContent.newInstance("NewContent"));
ftran.commit();

然而,在事务完成后,新片段不再保留在viewPager中,它也将空格用于tabview。

因此我想知道如何在这个指定的ViewPager空间内切换片段。

在新片段NewContent.java中,它还有一个按钮,供用户返回主页。我还想问一下如何完成这个操作?

我是stackoverflow的新手,所以我希望你知道我面临的问题......谢谢。

另一个片段文件TabFragment.java,我用它来构建标签。

package com.android.luftschlafer.engdictionary;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.luftschlafer.engdictionary.Corr_Pages.AboutPage;
import com.android.luftschlafer.engdictionary.Corr_Pages.SearchPage;
import com.android.luftschlafer.engdictionary.Corr_Pages.SettingPage;
import com.android.luftschlafer.engdictionary.Tab.BaseFragment;
import com.android.luftschlafer.engdictionary.Tab.SlidingTabLayout;
import com.android.luftschlafer.engdictionary.Corr_Pages.HomePage;

import java.util.LinkedList;

/**
 * Created by LuftSchlafer on 6/17/2016.
 */

//Configurations of all fragments

public class TabFragment extends Fragment {

private SlidingTabLayout tabs;
private ViewPager pager;
private FragmentPagerAdapter adapter;


public static Fragment newInstance(){
    TabFragment f = new TabFragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    return inflater.inflate(R.layout.tab_and_view, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    //adapter
    final LinkedList<BaseFragment> fragments = getFragments();
    adapter = new TabFragmentPagerAdapter(getFragmentManager(), fragments);
    //pager
    pager = (ViewPager) view.findViewById(R.id.pager);
    pager.setAdapter(adapter);
    //tabs
    tabs = (SlidingTabLayout) view.findViewById(R.id.tabs);
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {

        @Override
        public int getIndicatorColor(int position) {
            return fragments.get(position).getIndicatorColor();
        }

        @Override
        public int getDividerColor(int position) {
            return fragments.get(position).getDividerColor();
        }

    });
    tabs.setBackgroundResource(R.color.colorAccent);
    tabs.setCustomTabView(R.layout.tab_title, R.id.txtTabTitle,     
R.id.imgTabIcon);//REMEMBER THE SEQUENCE!
    tabs.setViewPager(pager);



}
//Produce the fragments and corresponding tabs.
private LinkedList<BaseFragment> getFragments(){
    int indicatorColor = Color.parseColor("RED");
    int dividerColor = Color.TRANSPARENT;

    LinkedList<BaseFragment> fragments = new LinkedList<>();
    //Add fragments here
    fragments.add(HomePage.newInstance("Home", indicatorColor,      
      dividerColor,R.drawable.ic_home_black_24dp));
    fragments.add(SearchPage.newInstance("Search", indicatorColor, 
    dividerColor,R.drawable.ic_book_black_24dp));
    fragments.add(SettingPage.newInstance("Settings", indicatorColor, 
    dividerColor,R.drawable.ic_build_black_24dp));
    fragments.add(AboutPage.newInstance("About        
   app",indicatorColor,dividerColor,R.drawable.ic_info_outline_black_24dp));
    return fragments;
    }
}

0 个答案:

没有答案