android-单击按钮时更改片段

android-单击按钮时更改片段,第1张

概述单击按钮时如何更改片段?我正在使用androidstudio1.5并使用新的导航抽屉.这是我的MainActivity.javaimportandroid.os.Bundle;importandroid.support.design.widget.FloatingActionButton;importandroid.support.design.widget.Snackbar;importandroid.view.View;impor

单击按钮时如何更改片段?我正在使用android studio 1.5并使用新的导航抽屉.

这是我的MainActivity.java

import androID.os.Bundle;import androID.support.design.Widget.floatingActionbutton;import androID.support.design.Widget.Snackbar;import androID.vIEw.VIEw;import androID.support.design.Widget.NavigationVIEw;import androID.support.v4.vIEw.GravityCompat;import androID.support.v4.Widget.DrawerLayout;import androID.support.v7.app.ActionbarDrawerToggle;import androID.support.v7.app.AppCompatActivity;import androID.support.v7.Widget.Toolbar;import androID.vIEw.Menu;import androID.vIEw.MenuItem;import androID.support.v4.app.Fragment;import androID.support.v4.app.FragmentManager;import androID.support.v4.app.FragmentTransaction;public class MainActivity extends AppCompatActivity        implements NavigationVIEw.OnNavigationItemSelectedListener {    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findVIEwByID(R.ID.toolbar);        setSupportActionbar(toolbar);        floatingActionbutton fab = (floatingActionbutton) findVIEwByID(R.ID.fab);        fab.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw vIEw) {                Snackbar.make(vIEw, "bryanposvoc1339.garcia@gmail.com", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });        DrawerLayout drawer = (DrawerLayout) findVIEwByID(R.ID.drawer_layout);        ActionbarDrawerToggle toggle = new ActionbarDrawerToggle(                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);        drawer.setDrawerListener(toggle);        toggle.syncState();        NavigationVIEw navigationVIEw = (NavigationVIEw) findVIEwByID(R.ID.nav_vIEw);        navigationVIEw.setNavigationItemSelectedListener(this);    }    @OverrIDe    public voID onBackpressed() {        DrawerLayout drawer = (DrawerLayout) findVIEwByID(R.ID.drawer_layout);        if (drawer.isDrawerOpen(GravityCompat.START)) {            drawer.closeDrawer(GravityCompat.START);        } else {            super.onBackpressed();        }    }    @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;    }    @OverrIDe    public boolean onoptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroIDManifest.xml.        int ID = item.getItemID();        //noinspection SimplifiableIfStatement        if (ID == R.ID.action_settings) {            return true;        }        return super.onoptionsItemSelected(item);    }    @SuppressWarnings("StatementWithEmptyBody")    @OverrIDe    public boolean onNavigationItemSelected(MenuItem item) {        int ID = item.getItemID();        Fragment fragment;        if (ID == R.ID.nav_cough) {             fragment = new first();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        }        else if (ID == R.ID.nav_colds) {              fragment = new second();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        }        else if (ID == R.ID.nav_fever) {            fragment = new third();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        }        else if (ID == R.ID.nav_vegetables) {            fragment = new fourth();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        } else if (ID == R.ID.nav_fruits) {            fragment = new fifth();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        } else if (ID == R.ID.nav_about) {            fragment = new sixth();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        }        DrawerLayout drawer = (DrawerLayout) findVIEwByID(R.ID.drawer_layout);        drawer.closeDrawer(GravityCompat.START);        return true;    }}

这是我的activity_main.xml

<?xml version="1.0" enCoding="utf-8"?><androID.support.v4.Widget.DrawerLayout 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:ID="@+ID/drawer_layout"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:fitsSystemwindows="true"    tools:openDrawer="start">    <include        layout="@layout/app_bar_main"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent" />    <androID.support.design.Widget.NavigationVIEw        androID:ID="@+ID/nav_vIEw"        androID:layout_wIDth="wrap_content"        androID:layout_height="match_parent"        androID:layout_gravity="start"        androID:fitsSystemwindows="true"        app:headerLayout="@layout/nav_header_main"        app:menu="@menu/activity_main_drawer" /></androID.support.v4.Widget.DrawerLayout>

content_main.xml这是我的框架布局所在的位置

<?xml version="1.0" enCoding="utf-8"?><relativeLayout 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"    androID:paddingBottom="@dimen/activity_vertical_margin"    androID:paddingleft="@dimen/activity_horizontal_margin"    androID:paddingRight="@dimen/activity_horizontal_margin"    androID:paddingtop="@dimen/activity_vertical_margin"    app:layout_behavior="@string/appbar_scrolling_vIEw_behavior"    tools:context="appnaturemedicine.com.example.posvoc.naturesmedicine.MainActivity"    tools:showIn="@layout/app_bar_main"    androID:background="@drawable/background">    <FrameLayout        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent" androID:ID="@+ID/mainFrame">    </FrameLayout>        </relativeLayout>

我可以转到我想要的片段,问题是我如何在单击片段时使片段中的按钮改变当前片段

这是我单击导航抽屉中的一个菜单时的第一个片段

fragment_first.xml

<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="appnaturemedicine.com.example.posvoc.naturesmedicine.first">    <ImageVIEw        androID:layout_wIDth="80dp"        androID:layout_height="80dp"        androID:ID="@+ID/imageVIEw2"        androID:layout_alignParenttop="true"        androID:layout_alignParentleft="true"        androID:layout_alignParentStart="true"        androID:background="@mipmap/ic_launcher_cough" />    <button        androID:layout_wIDth="80dp"        androID:layout_height="30dp"        androID:ID="@+ID/button"        androID:layout_alignBottom="@+ID/textVIEw3"        androID:layout_alignParentRight="true"        androID:layout_alignParentEnd="true"        androID:onClick="onbuttonClicked"        />    <TextVIEw        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:textAppearance="?androID:attr/textAppearanceMedium"        androID:text="Lagundi (Vitex negundo)"        androID:ID="@+ID/textVIEw3"        androID:textcolor="#ff4081"        androID:layout_below="@+ID/imageVIEw3"        androID:layout_alignParentleft="true"        androID:layout_alignParentStart="true" />    <TextVIEw        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:textAppearance="?androID:attr/textAppearanceMedium"        androID:text="Honey"        androID:ID="@+ID/textVIEw4"        androID:textcolor="#ff4081"        androID:layout_alignBottom="@+ID/button3"        androID:layout_alignParentleft="true"        androID:layout_alignParentStart="true" />    <button        androID:layout_wIDth="80dp"        androID:layout_height="30dp"        androID:ID="@+ID/button3"        androID:layout_below="@+ID/button"        androID:layout_alignParentRight="true"        androID:layout_alignParentEnd="true" />    <TextVIEw        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:textAppearance="?androID:attr/textAppearanceMedium"        androID:text="Probiotics"        androID:ID="@+ID/textVIEw5"        androID:layout_alignBottom="@+ID/button4"        androID:layout_alignParentleft="true"        androID:layout_alignParentStart="true"        androID:layout_toleftOf="@+ID/button4"        androID:textcolor="#ff4081"        androID:layout_toStartOf="@+ID/button4" />    <button        androID:layout_wIDth="80dp"        androID:layout_height="30dp"        androID:ID="@+ID/button4"        androID:layout_below="@+ID/textVIEw4"        androID:layout_alignParentRight="true"        androID:layout_alignParentEnd="true" />    <button        androID:layout_wIDth="80dp"        androID:layout_height="30dp"        androID:ID="@+ID/button5"        androID:layout_below="@+ID/button4"        androID:layout_alignParentRight="true"        androID:layout_alignParentEnd="true" />    <button        androID:layout_wIDth="80dp"        androID:layout_height="30dp"        androID:ID="@+ID/button6"        androID:layout_alignParentRight="true"        androID:layout_alignParentEnd="true"        androID:layout_below="@+ID/button5" />    <TextVIEw        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:textAppearance="?androID:attr/textAppearanceMedium"        androID:text="bromelain"        androID:ID="@+ID/textVIEw6"        androID:textcolor="#ff4081"        androID:layout_alignBaseline="@+ID/button5"        androID:layout_alignBottom="@+ID/button5"        androID:layout_alignParentleft="true"        androID:layout_alignParentStart="true" />    <TextVIEw        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:textAppearance="?androID:attr/textAppearanceMedium"        androID:text="Peppermint"        androID:ID="@+ID/textVIEw7"        androID:textcolor="#ff4081"        androID:layout_alignBaseline="@+ID/button6"        androID:layout_alignBottom="@+ID/button6"        androID:layout_alignParentleft="true"        androID:layout_alignParentStart="true" />    <ImageVIEw        androID:layout_wIDth="250dp"        androID:layout_height="110dp"        androID:ID="@+ID/imageVIEw3"        androID:background="@drawable/ben"        androID:layout_alignParenttop="true"        androID:layout_centerHorizontal="true" /></relativeLayout>

第一.java

import androID.os.Bundle;import androID.support.v4.app.Fragment;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;/** * A simple {@link Fragment} subclass. */public class first extends Fragment {    public first() {        // required empty public constructor    }    @OverrIDe    public VIEw onCreateVIEw(LayoutInflater inflater, VIEwGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_first, container, false);    }}

您能否使它像单击btn1时进入fragmentOne,单击btn2时进入fragmentTwo的if-else语句?

我在这里放什么?

解决方法:

您可以为此使用OnfragmentInteractionListener.这是您的活动应实现的接口.您可以从片段中调用方法,就像从活动中调用方法一样.

在下面的示例中,第一个片段具有一个按钮,单击该按钮时将调用方法changeFragment(2),类似地,第二个片段将调用方法changeFragment(1).此方法是在main活动中实现的,如果不是,则会通过它找出要替换的片段.

OnFragmentInteractionListener.java

public interface OnFragmentInteractionListener {        public voID changeFragment(int ID);}

片段A:

public class first extends Fragment {    private OnFragmentInteractionListener mListener;    public first() {        // required empty public constructor    }    @OverrIDe    public VIEw onCreateVIEw(LayoutInflater inflater, VIEwGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        VIEw vIEw = inflater.inflate(R.layout.fragment_first, container, false);        button btn = (button) vIEw.findVIEwByID(R.ID.btn);        btn.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw vIEw) {                mListener.changeFragment(2);            }        });        return vIEw;    }    @OverrIDe    public voID onAttach(Activity activity) {        super.onAttach(activity);        try {            mListener = (OnFragmentInteractionListener) activity;        } catch (ClassCastException e) {            throw new ClassCastException(activity.toString()                + " must implement OnFragmentInteractionListener");        }    }    @OverrIDe    public voID onDetach() {        super.onDetach();        mListener = null;    }}

片段B:

public class first extends Fragment {    private OnFragmentInteractionListener mListener;    public first() {        // required empty public constructor    }    @OverrIDe    public VIEw onCreateVIEw(LayoutInflater inflater, VIEwGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        VIEw vIEw = inflater.inflate(R.layout.fragment_first, container, false);        button btn = (button) vIEw.findVIEwByID(R.ID.btn);        btn.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw vIEw) {                mListener.changeFragment(1);            }        });        return vIEw;    }    @OverrIDe    public voID onAttach(Activity activity) {        super.onAttach(activity);        try {            mListener = (OnFragmentInteractionListener) activity;        } catch (ClassCastException e) {            throw new ClassCastException(activity.toString()                + " must implement OnFragmentInteractionListener");        }    }    @OverrIDe    public voID onDetach() {        super.onDetach();        mListener = null;    }}

主要活动:

public class MainActivity extends AppCompatActivity    implements NavigationVIEw.OnNavigationItemSelectedListener, OnFragmentInteractionListener {    //Rest of the code    @OverrIDe    public voID changeFragment(int ID){        if (ID == 1) {            fragment = new first();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        }        else if (ID == 2) {            fragment = new second();            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();            ft.replace(R.ID.mainFrame, fragment);            ft.commit();        }    }}

希望能帮助到你!!

总结

以上是内存溢出为你收集整理的android-单击按钮时更改片段全部内容,希望文章能够帮你解决android-单击按钮时更改片段所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1090325.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存