簡體   English   中英

Android GridLayout獲取行/列

[英]Android GridLayout get row/column

我有一個帶按鈕的3x3 GridLayout。 這些按鈕有一個onTileClicked()偵聽器。 現在我想獲得網格中點擊按鈕的位置。 這是我的代碼:

public void onTileClicked(View view) {
    Button button = (Button) view;
    GridLayout.LayoutParams params = (LayoutParams) button.getLayoutParams();
}

但是如何獲得點擊按鈕的行和列? 有params.columnSpec但我不知道該怎么做...

沒有直接的方法來獲得細胞的位置。 但是,如果您知道onItemClick偵聽器中的列數和行數,則可以計算單擊按鈕的位置:

    public void onItemClick(AdapterView parent, 
         View v, int position, long id) 
    {   
        int row_no=position/3;
        int col_no=position%3;
        .
        .
    }

感謝您的回答AmmarCSE,但我解決了這個問題只是做了這樣的事情:

public void onTileClicked(View view) {
    Button button = (Button) view;
    if(button.getId()==R.id.btn00)onTileClicked(0, 0, button);
    else if(button.getId()==R.id.btn01)onTileClicked(0, 1, button);
    else if(button.getId()==R.id.btn02)onTileClicked(0, 2, button);
    else if(button.getId()==R.id.btn10)onTileClicked(1, 0, button);
    else if(button.getId()==R.id.btn11)onTileClicked(1, 1, button);
    else if(button.getId()==R.id.btn12)onTileClicked(1, 2, button);
    else if(button.getId()==R.id.btn20)onTileClicked(2, 0, button);
    else if(button.getId()==R.id.btn21)onTileClicked(2, 1, button);
    else if(button.getId()==R.id.btn22)onTileClicked(2, 2, button);
}

這可能是舊的,但我也尋找解決方案,仍然沒有找到它。 我需要根據用戶對游戲的選擇制作多行按鈕。 使用ID是不可能的,因為按鈕的數量可以從2x2到9x9不等。

我的按鈕不需要有標題,所以這就是我所做的:

layout = (GridLayout) findViewById(R.id.layoutPrincipal);
    context = this;        
    for(int i=0;i<rowCount;i++){
        for(int j=0;j<columnCount;j++){
            Button mButon= new Button(this);
            mButon.setText(""+i+""+j);
            mButon.setTextColor(Color.TRANSPARENT);

            mButon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Button button = (Button) v;


                    //button.getText() allows me to retrieve the coordinates.

                    button.getText()

                 }
            });     
            layout.addView(mButon);

        }
    }

當然,如果您需要按鈕上的文字,這將無效。 也許你可以使用標簽?

我面臨同樣的問題,目前唯一讓我感到舒服的解決方案是修改課程並添加您需要的任何信息。 我的例子是

class ImageView extends android.widget.ImageView {
    public ImageView(Context context) {
        super(context);
    }

    //the position of the plane head.
    int xPos,yPos;

    public void setPosInGrid(int x,int y) {
        xPos=x;yPos=y;
    }

    public int[] getPosInGrid() {
        int[] pos=new int[2];
        pos[0]=xPos;
        pos[1]=yPos;
        return pos;
    }
}

現在我們可以使用這個附加功能了。 我們還可以重寫setLayoutParams並將setPosInGrid()集成到其中。 除非您希望普通的ImageView只使用完整的標識符“androi.widget.ImageView”,否則不需要修改其他代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM