Application of Fragment in Activity

In this section, create Fragment in Activity.

The official website has a very detailed introduction http://developer.android.com/guide/components/fragments.html . Introduced the life cycle of Fragment, Android3.0 introduced the concept of Fragmen, so that the UI can be flexibly adapted to various devices. The specific principle will not be repeated, please refer to the official website.

Fragments can be included in multiple Activities, which can adapt the application to different screen sizes. When the screen size is large enough, an Activity can contain multiple Fragments. When this is not the case, another Activity will be launched to contain different Fragments.

1 Create an empty Activity

We first create an empty Activity, arranged horizontally. As follows

res/layour/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
</LinearLayout>

com/fragment/FragmentDemoActivity.java:

copy code
package com.fragment;

import android.app.Activity;
import android.os.Bundle;

public class FragmentDemoActivity extends Activity {
    
    /** Called when the activity is first created. */
    @Override
    public  void onCreate (Bundle savedInstanceState) {
         super .onCreate (savedInstanceState);
        setContentView(R.layout.main);
    }
}
copy code

 

2 Create Fragment

We create two Fragments, one is the Directory TitlesFragment and the other is the Details DetailsFragment.

TitlesFragment integrates ListFragment to implement directory listing.

com/fragment/TitlesFragment.java:

copy code
package com.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TitlesFragment extends ListFragment {
    static String[] array;

    boolean mDualPane;
    int mCurCheckPosition = 0;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    
    @Override
    public void onPause() {
        super.onPause();
    }
    
    
    @Override
    public void onStop() {
        super.onStop();
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }
    
    @Override
    public void onStart() {
        super.onStart();
    }
    
    @Override
    public void onResume() {
        super.onResume();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        array = getResources().getStringArray(R.array.countries_array);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, array));

        View detailsFrame = getActivity().findViewById(R.id.details);

        mDualPane = detailsFrame != null
                && detailsFrame.getVisibility() == View.VISIBLE;

        if (savedInstanceState != null) {
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); //从保存的状态中取出数据
        }

        if (mDualPane) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            showDetails(mCurCheckPosition);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        showDetails(mCurCheckPosition);
    }

    void showDetails(int index) {
        mCurCheckPosition = index; 
        if (mDualPane) {
            getListView().setItemChecked(index, true);
            DetailsFragment details = (DetailsFragment) getFragmentManager()
                    .findFragmentById(R.id.details); 
            if (details == null || details.getShownIndex() != index) {
                details = DetailsFragment.newInstance(mCurCheckPosition); 

                //得到一个fragment事务(类似sqlite的操作)
                FragmentTransaction ft = getFragmentManager()
                        .beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();//提交
            }
        } else {
            new AlertDialog.Builder(getActivity()).setTitle(
                    android.R.string.dialog_alert_title).setMessage(
                    array[index]).setPositiveButton(android.R.string.ok,
                    null).show();
        }
    }

}
copy code

DetailsFragment显示点击某个目录的详情,com/fragment/DetailsFragment.java:

copy code
package com.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

public class DetailsFragment extends Fragment {
    static String[] array;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
    
    public static DetailsFragment newInstance(int index) { 
        DetailsFragment details = new DetailsFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        details.setArguments(args);
        return details;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (container == null)
            return null;

        array = getResources().getStringArray(R.array.countries_array);
        
        ScrollView scroller = new ScrollView(getActivity());
        
        /*GridView gridview = (GridView) getActivity().findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(getActivity()));

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Toast.makeText(DetailsFragment.this.getActivity(), " " + position, Toast.LENGTH_SHORT).show();
            }
        });*/
        
        /*//定义UI组件
        final ImageView iv= (ImageView)getActivity().findViewById(R.id.ImageView01);
        Gallery g = (Gallery) getActivity().findViewById(R.id.Gallery01);

        //设置图片匹配器
        g.setAdapter(new ImageAdapter(getActivity()));

        //设置AdapterView点击监听器,Gallery是AdapterView的子类
        g.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                //显示点击的是第几张图片
                Toast.makeText(DetailsFragment.this.getActivity(), "" + position,
                        Toast.LENGTH_LONG).show();
                //设置背景部分的ImageView显示当前Item的图片
                iv.setImageResource(((ImageView)view).getId());
            }
        });*/
        
        
        TextView text = new TextView(getActivity());

        int padding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
                        .getResources().getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);

        text.setText(array[getShownIndex()]);
        
        /*Button btnContact = (Button) getActivity().findViewById(R.id.bt1);
        btnContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), MainHelloGallery.class);
                startActivity(intent);
            }
        });*/
        
        return scroller;
    }
    
    /*@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
         menu.add("Menu 1a").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            menu.add("Menu 1b").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        Toast.makeText(getActivity(), "index is"+getShownIndex()+" && menu text is "+item.getTitle(), 1000).show();
        return super.onOptionsItemSelected(item);
    }*/
}
copy code

 

3 将Fragment添加至Activity中

此时,已经实现了Activity和两个Fragment,将Fragment添加至Activity有两种方式。

3.1 在activity的layout文件中声明fragment

copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

   <fragment
       android:id="@+id/titles"
       android:layout_width="0px"
       android:layout_height="match_parent"
       android:layout_weight="0.31"
       class="com.fragment.TitlesFragment" />
   
   <FrameLayout android:id="@+id/details" android:layout_weight="1" android:layout_width="0px" android:layout_height="match_parent"
       android:background="?android:attr/detailsElementBackground" >
   </FrameLayout>
</LinearLayout>
copy code

3.2 在Activity中管理Fragment

在Activity中管理fragment, 需要使用FragmentManager. 通过调用activity的getFragmentManager()取得它的实例。

copy code
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.main);

  FragmentManager fragmentManager = getFragmentManager();
  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

  TitlesFragment titleFragment = new TitlesFragment ();
  DetailsFragment detailsFragment = new DetailsFragment();
  fragmentTransaction.add (R.id.titles, titleFragment);
  fragmentTransaction.add(R.id.details, detailsFragment);
  fragmentTransaction.commit();
}
copy code

 

The effect diagram is as follows:

 

How to access the fragment function in Activity:

Fragment:

public class RandomFragment extends Fragment {

    public void randomfuntion (){

    }

}

Activity:

public class Main extends FragmentActivity{

    Fragment randomname;

    public void anotherrandomfuntion (){
       (RandomFragment)randomname.randomfuntion();
    }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326880716&siteId=291194637