gpt4 book ai didi

android - Gridview setEnabled 不适用于第一项

转载 作者:行者123 更新时间:2023-11-29 16:08:05 28 4
gpt4 key购买 nike

我今天有一个奇怪的问题。我正在尝试实现一个游戏,其中我有一个带有一些按钮的 gridview。单击任何按钮时,它会被禁用(使用 setEnabled(false))。问题是,只有第一个按钮没有被禁用。尽管日志输出显示调用了 setEnabled(false)

这是我的代码:

public class ButtonAdapter extends BaseAdapter {

private LayoutInflater inflater;
private GameScreen gameScreen;
private Hangman hangman;
private static final String[] buttonValues =
{
"A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U",
"", "V", "W", "X", "Y", "Z", "" ,
};
private Button[] holder = new Button[getCount()];

public ButtonAdapter(GameScreen gameScreen) {
inflater = (LayoutInflater) gameScreen
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.gameScreen = gameScreen;
}

public View getView(final int position, View convertView, ViewGroup arg2) {
View view = convertView;
if(view == null) {
view = inflater.inflate(R.layout.game_button, null);

final Button button = (Button) view.findViewById(R.id.button);
button.setText(buttonValues[position]);
holder[position] = button;
view.setTag(holder[position]);
}
else
holder[position] = (Button) view.getTag();

holder[position].setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if(buttonValues[position].length() != 0) {
Hangman.GameState gameState = hangman.updateCurrentWord(
buttonValues[position].charAt(0));
holder[position].setEnabled(false);

gameScreen.updateView(gameState);
Log.d("Button", position + ":" + holder[position].getText());
}
}
});

return view;
}

public int getCount() {
return buttonValues.length;
}

public Object getItem(int position) {
return buttonValues[position];
}

public long getItemId(int position) {
return position;
}

@Override
public boolean areAllItemsEnabled() {
return false;
}

@Override
public boolean isEnabled(int position) {
return holder[position].isEnabled();
}
}

我也尝试过 ((Button) view.findViewById(R.id.button)).setOnClickListener(...);,但没有任何变化。

最佳答案

有时会发生这些事情,因为您正在尝试访问尚未膨胀的 View 。试试这个:

    View view = convertView;

if(view == null)
{
view = inflater.inflate(R.layout.game_button, null);
vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Override public void onGlobalLayout()
{
final Button button = (Button) view.findViewById(R.id.button);
button.setText(buttonValues[position]);
holder[position] = button;
view.setTag(holder[position]);

ViewTreeObserver obs = view.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}});
...

或者可能将 ViewTreeObserver 放在其他地方。这完全取决于代码首先进入 if 语句 的哪一侧。

关于android - Gridview setEnabled 不适用于第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16285143/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com