Кнопка клавиатуры Android Calculator OnClickListener не работает?

Привет, я внедряю клавиатуру типа калькулятора в свое приложение, где пользователь нажимает на клавиатуру, которую она хочет отображать в Edittext, но я не получаю никаких ошибок, а также никаких результатов. Вот мой код Java

public class MainActivity extends Activity {
GridView mKeypadGrid;
KeypadAdapter mKeypadAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Get reference to the keypad button GridView
    mKeypadGrid = (GridView) findViewById(R.id.grdButtons);

    // Create Keypad Adapter
    mKeypadAdapter = new KeypadAdapter(this);

    // Set adapter of the keypad grid
    mKeypadGrid.setAdapter(mKeypadAdapter);

    // Set button click listener of the keypad adapter
    mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Button btn = (Button) v;
            // Get the KeypadButton value which is used to identify the
            // keypad button from the Button's tag
            KeypadButton keypadButton = (KeypadButton) btn.getTag();

            // Process keypad button
            ProcessKeypadInput(keypadButton);
        }
    });

    mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

        }
    });

}

protected void ProcessKeypadInput(KeypadButton keypadButton) {
    // TODO Auto-generated method stub
    Toast.makeText(
            MainActivity.this,
            keypadButton.getText().toString() + " "
                    + keypadButton.toString(), Toast.LENGTH_SHORT).show();


        }
      }

Вот мой KeypadAdapter.java

    public class KeypadAdapter extends BaseAdapter {
private Context mContext;

public KeypadAdapter(Context c) {
    mContext = c;
}

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

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

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

// create a new ButtonView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    Button btn;
    if (convertView == null) { // if it's not recycled, initialize some attributes
        btn = new Button(mContext);
        KeypadButton keypadButton = mButtons[position];

        // Set CalculatorButton enumeration as tag of the button so that we
        // will use this information from our main view to identify what to do
        btn.setTag(keypadButton);
    } 
    else {
        btn = (Button) convertView;
    }

    btn.setText(mButtons[position].getText());
    return btn;
}

// Create and populate keypad buttons array with CalculatorButton values
private KeypadButton[] mButtons = {KeypadButton.SEVEN,KeypadButton.EIGHT, KeypadButton.NINE, 
        KeypadButton.FOUR, KeypadButton.FIVE,KeypadButton.SIX, 
        KeypadButton.ONE, KeypadButton.TWO, KeypadButton.THREE,
        KeypadButton.ZERO,KeypadButton.DOT,KeypadButton.BACKSPACE };

public void setOnButtonClickListener(OnClickListener onClickListener) {
    // TODO Auto-generated method stub

}
public enum KeypadButton {
    BACKSPACE("Clear",KeypadButtonCategory.CLEAR)
    , ZERO("0",KeypadButtonCategory.NUMBER)
    , ONE("1",KeypadButtonCategory.NUMBER)
    , TWO("2",KeypadButtonCategory.NUMBER)
    , THREE("3",KeypadButtonCategory.NUMBER)
    , FOUR("4",KeypadButtonCategory.NUMBER)
    , FIVE("5",KeypadButtonCategory.NUMBER)
    , SIX("6",KeypadButtonCategory.NUMBER)
    , SEVEN("7",KeypadButtonCategory.NUMBER)
    , EIGHT("8",KeypadButtonCategory.NUMBER)
    , NINE("9",KeypadButtonCategory.NUMBER)
    , DOT(".",KeypadButtonCategory.OTHER);

    CharSequence mText; // Display Text
    KeypadButtonCategory mCategory;

    KeypadButton(CharSequence text,KeypadButtonCategory category) {
        mText = text;
        mCategory = category;
    }

    public CharSequence getText() {
        return mText;
    }
}
public enum KeypadButtonCategory {
    MEMORYBUFFER
    , NUMBER
    , OPERATOR
    , DUMMY
    , CLEAR
    , RESULT
    , OTHER
  }
  }

так что, пожалуйста, помогите мне решить эту проблему..........


person androidgeek    schedule 08.03.2013    source источник


Ответы (1)


Из того, что я знаю, чтобы сделать элемент внутри gridView кликабельным, вам нужно полностью реализовать onItemClickListener и использовать onClickListener так, как вы фактически назначаете этот прослушиватель представлению сетки, а не каждой отдельной кнопке в представлении сетки. Я думаю, что если вы возьмете код, который у вас есть в вашем onClickListener, и поместите его в свой onItemClickListener, тогда он должен работать.

mKeypadAdapter.setOnButtonClickListener(new OnClickListener() { //This won't work 
    //because keypadAdaptor.setOnButtonClickAdaptor(.....); is empty
    @Override public void onClick(View v) { 
        Button btn = (Button) v; 
        KeypadButton keypadButton = (KeypadButton) btn.getTag();
        ProcessKeypadInput(keypadButton); 
    } 
});

mKeypadGrid.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
    {
    //This needs to be filled in with your button processing code
    } 
});

Также вызов keypadAdaptor.setOnButtonClickListener(onClickListener.....); ничего не сделает, так как определение вашего метода для него в вашем keypadAdator пусто.

person chefburns    schedule 08.03.2013
comment
Если вы возьмете код из своего OnClickListener и поместите его в свой OnItemClickListener, тогда он должен работать, вы можете удалить mKeyAdapter.setOnButtonClickAdapter, поскольку он не используется. - person chefburns; 08.03.2013