Ваш код не работает, потому что он делает это:
Create variable `funcs` and assign it an empty array;
Loop from 0 up until it is less than 3 and assign it to variable `i`;
Push to variable `funcs` next function:
// Only push (save), but don't execute
**Write to console current value of variable `i`;**
// First loop has ended, i = 3;
Loop from 0 up until it is less than 3 and assign it to variable `j`;
Call `j`-th function from variable `funcs`:
**Write to console current value of variable `i`;**
// Ask yourself NOW! What is the value of i?
Теперь вопрос в том, каково значение переменной i
при вызове функции? Поскольку первый цикл создается с условием i < 3
, он немедленно останавливается, когда условие ложно, поэтому оно i = 3
.
Вам нужно понять, что во время создания ваших функций ни один из их кодов не выполняется, он сохраняется только позже. И поэтому, когда они вызываются позже, интерпретатор выполняет их и спрашивает: «Каково текущее значение i
?»
Итак, ваша цель - сначала сохранить значение функции i
для функции и только после этого сохраните функцию до funcs
. Это можно сделать следующим образом:
var funcs = [];
for (var i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function(x) { // and store them in funcs
console.log("My value: " + x); // each should log its value.
}.bind(null, i);
}
for (var j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
Таким образом, каждая функция будет иметь свою собственную переменную x
, и мы устанавливаем значение x
на значение i
на каждой итерации.
Это только один из нескольких способов решения этой проблемы.
Есть по крайней мере полдюжины способов сделать это, но, возможно, самый простой и самый короткий - использовать отражение, чтобы захватить ActionBarDrawerToggle
's Drawable
и перевернуть его направление.
пример обертывает эту функциональность в подклассе и должен работать независимо от настройки ActionBar
/ Activity
(если исходный класс работал там в первую очередь).
public class FlippedDrawerToggle extends ActionBarDrawerToggle {
public FlippedDrawerToggle(Activity activity, DrawerLayout drawerLayout,
int openDrawerContentDescRes, int closeDrawerContentDescRes) {
this(activity, drawerLayout, null,
openDrawerContentDescRes, closeDrawerContentDescRes);
}
public FlippedDrawerToggle(Activity activity, DrawerLayout drawerLayout,
Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
super(activity, drawerLayout, toolbar,
openDrawerContentDescRes, closeDrawerContentDescRes);
try {
Field sliderField = ActionBarDrawerToggle.class.getDeclaredField("mSlider");
sliderField.setAccessible(true);
DrawerArrowDrawable arrow = (DrawerArrowDrawable) sliderField.get(this);
arrow.setDirection(DrawerArrowDrawable.ARROW_DIRECTION_RIGHT);
}
catch (NoSuchFieldException | IllegalAccessException e) {
// Fail silently
}
}
}
Это изменит только направление изображения переключателя. Если вы действительно хотите, чтобы все ActionBar
/ Toolbar
были перевернуты, вы должны соответственно изменить направление макета.
Попробуйте следующее:
//Find the action bar for customizations
final ActionBar ab = getSupportActionBar();
assert ab != null;
//Make the action bar display an up arrow and set its drawable and color
ab.setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = ResourcesCompat.getDrawable(
getResources(),
R.drawable.abc_ic_ab_back_mtrl_am_alpha, //this is the <- arrow from android resources. Change this to the thing you want.
null);
assert upArrow != null;
upArrow.setColorFilter(
ContextCompat.getColor(
getApplicationContext(),
R.color.white // change this to the color you want (or remove the setColorFilter call)
),
PorterDuff.Mode.SRC_ATOP);
ab.setHomeAsUpIndicator(upArrow);
Добавьте это условие между mDrawerToggle = new ActionBarDrawerToggle...
и mDrawerToggle.syncState();
следующим образом:
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL)
{
toolbar.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
mDrawerToggle.syncState();