从片段中打开片段imageButton单击?

时间:2014-12-28 12:02:24

标签: java android android-layout android-fragments navigation-drawer

我遇到了从另一个片段打开片段的问题。 My Main Activity实现了最新的Nav Drawer,Nav Bar列表中的每个选项都会打开一个新片段。实施并运作良好。我遇到的问题是下一层碎片。我有一个带有imageButton的事件片段。单击此按钮时,我需要导航到此子事件的新片段。我尝试在事件片段中创建一个onclicklistener打开子事件页面,但是我收到以下错误。

找不到代码为0x7f08000a(com.ikimuhendis.ldrawer.sample:id / imagefrag)的视图片段imageFragment1 {348db088#0 id = 0x7f08000a}

public class EventFragment extends Fragment

{
    ImageButton test;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_event, container, false);

        SliderLayout sliderShow = (SliderLayout) rootView.findViewById(R.id.slider);
        sliderShow.setDuration(8000);
        sliderShow.setPresetTransformer(SliderLayout.Transformer.ZoomOut);

        //get the button view
        test = (ImageButton) rootView.findViewById(R.id.imageButton);

        test.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Fragment videoFragment = new imageFragment1();
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                transaction.replace(R.id.imagefrag, videoFragment)
                        .commit();
            }

        });

        HashMap<String, Integer> file_maps = new HashMap<String, Integer>();
        file_maps.put("Munster Vs Leinster", R.drawable.rugby);
        file_maps.put("Ennio Morricone", R.drawable.ennio);
        file_maps.put("Leinster Vs Harlequins", R.drawable.heino);
        file_maps.put("WWE Live", R.drawable.wwe);

        for (
                String name
                : file_maps.keySet())

        {
            TextSliderView textSliderView = new TextSliderView(getActivity());
            textSliderView
                    .description(name)
                    .image(file_maps.get(name));
            sliderShow.addSlider(textSliderView);
        }

        getActivity().setTitle("Events");
        return rootView;
    }
}

上面的代码旨在打开此图像片段

public class imageFragment1 extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.imagefragment1, container, false);

        return rootView;
    }
}

imageFragment1 xml代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@id/imagefrag" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="This is a test"
        android:id="@+id/textView"
        android:layout_marginTop="41dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

How to replace the activity's fragment from the fragment itself?

我很不确定碎片事务应该在哪里发生。在我的主要活动中,片段事务发生在导航抽屉的开关块中。我读过“请注意,片段不应该直接替换自身或任何其他片段。片段应该是单独的实体。片段应该做的是通知其父活动已经发生了一些事件。但它又不是片段工作决定如何处理它!应该是活动决定即在手机上替换片段,但是在平板电脑上添加另一个片段。所以你基本上做错了设计“

另一张海报提到“处理这种情况的更好方法是为主要活动创建一个回调实现来处理请求,例如启动一个新片段”如何在我的主要活动中设置它以便它与抽屉碎片的子片段。对此的任何想法都非常赞赏。

主要活动

    public class SampleActivity extends Activity {

        private DrawerLayout mDrawerLayout;
        private ListView mDrawerList;
        private ActionBarDrawerToggle mDrawerToggle;
        private DrawerArrowDrawable drawerArrow;
        private CharSequence mDrawerTitle;
        private CharSequence mTitle;
        CustomDrawerAdapter adapter;
        List<DrawerItem> dataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);
        ActionBar ab = getActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);

        dataList = new ArrayList<DrawerItem>();
        dataList.add(new DrawerItem("Home", R.drawable.home));
        dataList.add(new DrawerItem("How It Works", R.drawable.howitworks));
        dataList.add(new DrawerItem("Events", R.drawable.events));
        dataList.add(new DrawerItem("Profile", R.drawable.signin));

        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.navdrawer);

        drawerArrow = new DrawerArrowDrawable(this)
        {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            drawerArrow, R.string.drawer_open,R.string.drawer_close)
        {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

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

        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
        adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
                dataList);
        /* ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, mNames); */
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                {
                    displayView(position);
                    // Running Fragment Transaction code here
                }
            }

             // Method that updates content frame with different fragments
            private void displayView(int position) {
             // update the main content by replacing fragments

                Fragment fragment = null;
                Bundle args = new Bundle();
                switch (position) {
                    case 0:
                        fragment = new TitleFragment();
                        mDrawerToggle.setAnimateEnabled(true);
                        drawerArrow.setProgress(1f);
                        mDrawerToggle.syncState();
                        break;
                    case 1:
                        fragment = new HowFragment();
                        mDrawerToggle.setAnimateEnabled(true);
                        drawerArrow.setProgress(1f);
                        mDrawerToggle.syncState();
                        break;
                    case 2:
                        fragment = new EventFragment();
                        mDrawerToggle.setAnimateEnabled(true);
                        drawerArrow.setProgress(1f);
                        mDrawerToggle.syncState();
                        break;
                    case 3:
                        fragment = new ProfileFragment();
                        mDrawerToggle.setAnimateEnabled(true);
                        drawerArrow.setProgress(1f);
                        mDrawerToggle.syncState();
                        break;
                }
                    fragment.setArguments(args);
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.content_frame, fragment).addToBackStack(null).commit();

                    // update selected item and title, then close the drawer
                    mDrawerList.setItemChecked(position, true);
                    setTitle(dataList.get(position).getItemName());
                    mDrawerLayout.closeDrawer(mDrawerList);
            }
        });

    }

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

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

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

1 个答案:

答案 0 :(得分:0)

正如评论中所建议的那样,您必须制作自定义界面。通过界面,Fragment可以与其父Activity进行通信。

在你的片段中,你有按钮:

private OnDataPass dataPasser;

//Interface, trought the fragment can comunicate with activity
public interface OnDataPass {
    public void onDataPass();
}

//Method, which you call in your onClickListener
public void passData() {
    // Method in the Activity
    dataPasser.onDataPass();
}

//Method, which creates the interface
@Override
public void onAttach(Activity a) {
    super.onAttach(a);
    try {
        dataPasser = (OnDataPass) a;
    } catch (ClassCastException e) {
        throw new ClassCastException(a.toString() + " must implement onDataPass");
    }
}

在您的活动中:

// You can also pass arguments, if you need
@Override
public void onDataPass() {

    //Do your code for switching the fragments or anything else
    ...

}

您的活动必须实现此监听器:

public class ActivityMain extends Activity implements OnDataPass{

但是下次尝试在询问之前进行更多研究时,对这个主题有很多问题。 Example