如何使用导航活动下的按钮切换片段

时间:2017-08-16 11:46:38

标签: android android-fragments android-button android-navigation-drawer

我是Android Studio上的新手,所以请耐心等待。我创建了两个名为 locate_before locate_after 的片段。我的 locate_before 片段上有一个ID为触发器的按钮。我想在点击该按钮后切换到 locate_after

这是我的主要活动。我为我的碎片使用了一个框架容器。我已经为我想要的名称​​ onSelectFragment 创建了一个代码,但它不起作用。它说“方法onSelectFragment永远不会被使用”

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Button trigger;

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

        //Set the fragment initially
        locate_before fragment = new locate_before();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction(); //check this out

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        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);

    }

    public void onSelectFragment(View v){
        Fragment newFragment;

        if(v == findViewById(R.id.trigger)){
            newFragment = new locate_after();
        }
        else{
            newFragment = new locate_before();
        }

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }



    @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) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

locate_before片段java ofc扩展片段

public locate_before () {
        // Required empty public constructor

    }

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

        // Inflate the layout for this fragment
        return rootView;
    }
}

locate_before xml文件按钮

 <Button
        android:id="@+id/trigger"
        android:layout_width="284dp"
        android:layout_height="58dp"
        android:text="View Car's Location"
        android:layout_marginRight="24dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.633"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="133dp" />

locate_after java

public class locate_after extends Fragment {


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


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

        // Inflate the layout for this fragment
        return rootView;
    }
}

谢谢!

5 个答案:

答案 0 :(得分:1)

使用onNavigationItemSelected()导航到片段。下面是示例代码

@Override
public boolean onNavigationItemSelected(MenuItem item) {

    // Handle navigation view item clicks here.
    int id = item.getItemId();

    FragmentManager fragmentManager = getSupportFragmentManager();

    if (id == R.id.nav_home) {
        Fragment homeFragment = new HomeFragment();
        fragmentManager.beginTransaction().replace(R.id.relative_layout_fragment1, homeFragment, homeFragment.getTag()).commit();

    }  else if (id == R.id.nav_logout) {

        Toast.makeText(mContext, "logout", Toast.LENGTH_SHORT).show();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

答案 1 :(得分:1)

你的buttom似乎没有onClickListener。

在您的XML中添加android:onClick="onSelectFragment"或绑定您的Button并在OnCreate中添加onClickListener。

答案 2 :(得分:0)

您的onCreate()

后有未经授权的交易
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction(); //check this out

答案 3 :(得分:0)

首先,你永远不会使用方法OnSelectFragment()。 在OnCreate方法中添加以下

trigger = (Button) findViewById(R.id.trigger); //get Button
trigger.setOnClickListener(new View.OnClickListener() { // action to do when button is pressed
        @Override
        public void onClick(View view) {
            if(before)
                onSelectFragment(new locate_after());
            else
                onSelectFragment(new locate_before());
            before = !before; //this makes it a switch
        }
    });

在&#34;之前声明属性&#34;沿着其他属性

boolean before = true;

并将onSelectFragment方法更改为以下

 public void onSelectFragment(Fragment newFragment){

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

答案 4 :(得分:0)

检查当前显示的片段并相应地设置所需的片段。请尝试以下代码。

        Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);
        if(!(fragment instanceof locate_before)) {
            newFragment = new locate_after();
        }
        else{
            newFragment = new locate_before();
        }
        getSupportFragmentManager().beginTransaction().replace(newFragment).commit();