Android: кнопки, созданные с помощью адаптера кнопок, расположены не в правильном порядке

новичок в андроиде. Я создал 12 (3 строки, 4 столбца) кнопок в GridView и создал тост для отображения чего-либо после нажатия кнопки, следуя руководству. Кнопки отображаются на экране правильно, а всплывающие сообщения — нет. Когда я нажимаю верхнюю левую кнопку, я получаю нижний левый тост. Когда я нажимаю среднюю левую кнопку, я получаю средний правый тост. Когда я нажимаю нижнюю левую кнопку, я получаю верхний правый тост.

Visually:

button location:
1 2 3 4
5 6 7 8
9 10 11 12

toast message
9 10 11 12
8 7 6 5
4 3 2 1

Вот код адаптера:

public class KeypadAdapter extends BaseAdapter {
    private Context mContext;

    // Declare button click listener variable
    private OnClickListener mOnButtonClick;

    // Method to set button click listener variable
    public void setOnButtonClickListener(OnClickListener listener) {
        mOnButtonClick = listener;
    }

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

    private KeypadButtons[] mButtons = { KeypadButtons.ADD,
            KeypadButtons.SUBTRACT, KeypadButtons.MULTIPLY,
            KeypadButtons.DIVIDE, KeypadButtons.DET, KeypadButtons.INV,
            KeypadButtons.POW2, KeypadButtons.POWN, KeypadButtons.TRANSPOSE,
            KeypadButtons.NORM1, KeypadButtons.NORM2, KeypadButtons.NORMINF };

    @Override
    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);
            KeypadButtons keypadButton = mButtons[position];
            if (keypadButton != KeypadButtons.DUMMY) {
                btn.setOnClickListener(mOnButtonClick);
            }

            // 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;
    }

}

а вот код активности

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

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

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

        // 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
                KeypadButtons keypadButton = (KeypadButtons) 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(KeypadButtons keypadButton) {
        // TODO Auto-generated method stub
        Toast.makeText(
                MainActivity.this,
                keypadButton.getText().toString() + " "
                        + keypadButton.toString(), Toast.LENGTH_SHORT).show();


    }
}

Сначала кажется, что порядок тостов обратный. Поэтому я попытался сделать

KeypadButtons keypadButton = mButtons[mButtons.length - 1 - position];

Это исправило две нижние строки, но верхняя строка по-прежнему перевернута.

Заранее спасибо.


person lamba    schedule 05.09.2012    source источник


Ответы (1)


Представления перерабатываются (как вы, очевидно, знаете, потому что вы проверяете, является ли convertview нулевым). Простое исправление здесь состоит в том, чтобы переместить блок btn.setTag(keypadButton); to outside of theif(convertView==null)` и выполнять его всегда, прежде чем вы вернетесь из getView();

person LuxuryMode    schedule 05.09.2012