使用ImageButton切换片段

时间:2014-05-12 14:35:51

标签: android android-fragments android-imagebutton

我真的想知道如何使用ImageButton切换到另一个片段。 FragmentSeven是ImageButton的位置,必须链接到FragmentEight。我怎么能这样做?

这是我的FragmentSeven中的代码:

package com.mypackage;

import android.app.Fragment;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;


public class FragmentSeven extends Fragment {


      public static final String IMAGE_RESOURCE_ID = "iconResourceID";
      public static final String ITEM_NAME = "itemName";

      public FragmentSeven() {

      }



      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {

          View view = inflater.inflate(R.layout.fragment_layout_seven, container, false);

          getActivity().setRequestedOrientation(
                  ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

          final ImageButton ib = (ImageButton) view.findViewById(R.id.imageButton2);
          ib.setOnClickListener(new View.OnClickListener(){
             //SWITCH TO OTHER FRAGMENT HERE
          });

            return view;

         }
      }

这是我的MainActivity:

package com.rydee.trinitas;

 import java.util.ArrayList;
 import java.util.List;

 import android.os.Bundle;
 import android.app.Activity;
 import android.app.Fragment;
 import android.app.FragmentManager;
 import android.content.res.Configuration;
 import android.support.v4.view.GravityCompat;
 import android.support.v4.widget.DrawerLayout;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ListView;

 public class MainActivity extends Activity {

  private DrawerLayout mDrawerLayout;
  private ListView mDrawerList;
  private ActionBarDrawerToggle mDrawerToggle;

  private CharSequence mDrawerTitle;
  private CharSequence mTitle;
  CustomDrawerAdapter adapter;

  List<DrawerItem> dataList;

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

        // Initializing
        dataList = new ArrayList<DrawerItem>();
        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
                    GravityCompat.START);

        // Add Drawer Item to dataList
        dataList.add(new DrawerItem("1", R.drawable.1));
        dataList.add(new DrawerItem("2", R.drawable.2));
        dataList.add(new DrawerItem("3", R.drawable.3));
        dataList.add(new DrawerItem("4", R.drawable.4));
        dataList.add(new DrawerItem(" 5", R.drawable.5));
        dataList.add(new DrawerItem(" 6", R.drawable.6));
        dataList.add(new DrawerItem(" 7", R.drawable.7));

        adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
                    dataList);

        mDrawerList.setAdapter(adapter);

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                    R.drawable.ic_drawer, R.string.drawer_open,
                    R.string.drawer_close) {
              public void onDrawerClosed(View view) {
                    getActionBar().setTitle(mTitle);
                    invalidateOptionsMenu(); // creates call to
                                                              // onPrepareOptionsMenu()
              }

              public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle(mDrawerTitle);
                    invalidateOptionsMenu(); // creates call to
                                                              // onPrepareOptionsMenu()
              }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
              SelectItem(0);
        }

  }



  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

  }

  public void SelectItem(int possition) {

        Fragment fragment = null;
        Bundle args = new Bundle();
        switch (possition) {
        case 0:
              fragment = new FragmentOne();
              args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 1:
              fragment = new FragmentTwo();
              args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 2:
              fragment = new FragmentThree();
              args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 3:
            fragment = new FragmentFour();
            args.putString(FragmentFour.ITEM_NAME, dataList.get(possition)
                        .getItemName());
            args.putInt(FragmentFour.IMAGE_RESOURCE_ID, dataList.get(possition)
                        .getImgResID());
            break;
      case 4:
            fragment = new FragmentFive();
            args.putString(FragmentFive.ITEM_NAME, dataList.get(possition)
                        .getItemName());
            args.putInt(FragmentFive.IMAGE_RESOURCE_ID, dataList.get(possition)
                        .getImgResID());
            break;
      case 5:
            fragment = new FragmentSix();
            args.putString(FragmentSix.ITEM_NAME, dataList.get(possition)
                        .getItemName());
            args.putInt(FragmentSix.IMAGE_RESOURCE_ID, dataList.get(possition)
                        .getImgResID());
            break;
        case 6:
              fragment = new FragmentSeven();
              args.putString(FragmentSeven.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentSeven.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 7:
              fragment = new FragmentTwo();
              args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 8:
              fragment = new FragmentThree();
              args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 9:
              fragment = new FragmentOne();
              args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 10:
              fragment = new FragmentTwo();
              args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 11:
              fragment = new FragmentThree();
              args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        case 12:
              fragment = new FragmentOne();
              args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
                          .getItemName());
              args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
                          .getImgResID());
              break;
        default:
              break;
        }

        fragment.setArguments(args);
        FragmentManager frgManager = getFragmentManager();
        frgManager.beginTransaction().replace(R.id.content_frame, fragment)
                    .commit();

        mDrawerList.setItemChecked(possition, true);
        setTitle(dataList.get(possition).getItemName());
        mDrawerLayout.closeDrawer(mDrawerList);

  }

  @Override
  public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
  }

  @Override
  protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
              return true;
        }

        return false;
  }

    private class DrawerItemClickListener implements
              ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
              SelectItem(position);

        }
  }

2 个答案:

答案 0 :(得分:0)

您通常不希望从其他片段中启动片段,尤其是当您要替换其他片段时。实现此目的的正确方法是添加一个接口,您的fragmentSeven可以使用该接口与父活动进行通信,父活动将管理事务。

public interface OnImageButtonListener {
    public void onImageButton();
}

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    try {
        mListener = (OnImageButtonListener) activity;
    }catch (ClassCastException e){
        throw new ClassCastException(activity.toString() + " must implement OnImageButtonListener");
    }
}
....


OnImageButtonListener mListener = (OnImageButtonListener) this.getActivity();
final ImageButton ib = (ImageButton) view.findViewById(R.id.imageButton2);
ib.setOnClickListener(new View.OnClickListener(){
    mListener.onImageButton();
});

然后,您在主机活动中实施OnImageButtonListener并管理FragmentTransaction。您可以直接在以下位置执行此操作:

@Override
onImageButton(){
//do a fragmenttransaction here in your activity
}

答案 1 :(得分:0)

第1步:将此方法放入MainActivity.java中,

    public void switchContent(Fragment fragment) {
    mContent = fragment;

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.setTransitionStyle(android.R.attr.fragmentOpenEnterAnimation);
    ft.replace(R.id.content_frame, fragment);
    ft.commit();

    getSlidingMenu().showContent();
}

第2步:现在这个代码出现在按钮的点击事件中以及您想要切换片段的地方,

        Fragment newContent = new FragmentEight();
    if (getActivity() == null)
        return;
    if (getActivity() instanceof MainActivity) {
        MainActivity fca = (MainActivity) getActivity();
        fca.switchContent(newContent);
    }