我制作了一个带有基本抽屉的Android Studio项目。但是,永远不会调用onNavigationItemSelected函数。
我的目标是在菜单中选择其他选项时更改活动中的片段,但目前它只显示我的ControllerFragment(我放在XML文件中的那个),并且永远不会更改它。
这是我的代码:
MainActivity.java
package com.dylem.robotremotev2;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
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);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
System.out.println("0");
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
System.out.println("1"); // NOT CALLED
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.param_connexion) {
} else if (id == R.id.piloter_robot) {
System.out.println("2");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.controller_fragment, new ControllerFragment());
ft.commit();
} else if (id == R.id.trajets_enregistres) {
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.drawer_layout, new ParcoursFragment());
ft.commit();
} else if (id == R.id.nouveau_trajet) {
} 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;
}
}
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" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</RelativeLayout>
<fragment
android:id="@+id/controller_fragment"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:layout_marginTop="?android:attr/actionBarSize"
class="com.dylem.robotremotev2.ControllerFragment" />
</android.support.v4.widget.DrawerLayout>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
app:srcCompat="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Robot Remote v2.0"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolo@github.io" />
</LinearLayout>
app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
tools:context="com.dylem.robotremotev2.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/piloter_robot"
android:icon="@drawable/ic_menu_manage"
android:title="Piloter le robot" />
<item
android:id="@+id/trajets_enregistres"
android:icon="@drawable/ic_menu_gallery"
android:title="Trajets enregistrés" />
<item
android:id="@+id/nouveau_trajet"
android:icon="@drawable/ic_menu_slideshow"
android:title="Nouveau Trajet" />
<item
android:id="@+id/param_connexion"
android:icon="@drawable/ic_menu_manage"
android:title="Paramètres de connexion" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="@+id/nav_share"
android:icon="@drawable/ic_menu_share"
android:title="Share" />
<item
android:id="@+id/nav_send"
android:icon="@drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
</menu>
ControllerFragment.java
package com.dylem.robotremotev2;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
// Nouvelle activité
public class ControllerFragment extends Fragment implements View.OnTouchListener, View.OnClickListener {
/*
Contains the commands to send to the DB
Map<Key, [Arrow, Time]>
*/
private Map<Integer, ControllerAction> commands = new HashMap<>();
private char direction = 'S';
private boolean started = false;
private Chronometer chrono;
private long actionChrono = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.controller_layout, container, false);
final ImageButton[] arrows = {
view.findViewById(R.id.up),
view.findViewById(R.id.left),
view.findViewById(R.id.right),
view.findViewById(R.id.down)
};
for(final ImageButton arrow : arrows) {
arrow.setBackgroundResource(getButtonResource(arrow, false));
arrow.setOnTouchListener(this);
}
view.findViewById(R.id.start_course).setOnClickListener(this);
chrono = (Chronometer) view.findViewById(R.id.simpleChronometer);
// Inflate the layout for this fragment
return view;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(v instanceof ImageButton) {
if (!(event.getAction() == (MotionEvent.ACTION_UP))) { // PENDANT
v.setBackgroundResource(getButtonResource(v, true));
this.direction = getButtonDirection(v);
if(this.started)
this.actionChrono = SystemClock.elapsedRealtime();
} else { // APRES
if (this.started) {
final ControllerAction action = new ControllerAction(SystemClock.elapsedRealtime() - this.actionChrono, this.direction);
this.commands.put(this.commands.size(), action);
}
v.setBackgroundResource(getButtonResource(v, false));
}
}
return true;
}
public void onClick(View v) {
if(v.getId() == R.id.start_course) {
Button b = (Button)v;
this.started = !this.started;
this.chrono.setBase(SystemClock.elapsedRealtime());
if(this.started) {
b.setText("Terminer le parcours");
this.chrono.start();
}
else {
b.setText("Commencer un parcours");
this.chrono.stop();
sendActions();
}
}
}
public void sendActions() {
Iterator it = this.commands.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
ControllerAction action = (ControllerAction) pair.getValue();
Log.d("DEBUG : ", pair.getKey() + " -> action : " + action.getAction() + ", temps : " + action.getTimeIn());
}
}
public char getButtonDirection(View v) {
switch (v.getId()) {
case R.id.up:
return 'W';
case R.id.left:
return 'A';
case R.id.right:
return 'D';
case R.id.down:
return 'S';
default:
return 'O';
}
}
/*
Envoie l'action à effectuer en fonction du bouton appuyé.
@Param v la vue
@Param pressed si le bouton est appuyé ou non
@Return la nouvelle ressource à utiliser
*/
public int getButtonResource(View v, boolean pressed) {
int r = 0; // ressource à retourner
if(pressed) {
switch (v.getId()) {
case R.id.up:
r = R.drawable.up_c;
break;
case R.id.left:
r = R.drawable.left_c;
break;
case R.id.right:
r = R.drawable.right_c;
break;
case R.id.down:
r = R.drawable.down_c;
break;
}
}
else {
switch (v.getId()) {
case R.id.up:
r = R.drawable.up;
break;
case R.id.left:
r = R.drawable.left;
break;
case R.id.right:
r = R.drawable.right;
break;
case R.id.down:
r = R.drawable.down;
break;
}
}
return r;
}
}