簡體   English   中英

Android GridLayout僅顯示最后一個孩子

[英]Android GridLayout only shows last child

我是Android開發的新手。 我一直在使用GridLayout來顯示動態插入的ImageView。

我的問題位於“ onFocusWindowChanged”中,但是我將onCreate粘貼到了我分配圖像的位置。

private List<Behavior> behaviors = null;
private static int NUM_OF_COLUMNS = 2;
private List<ImageView> images;
private GridLayout grid;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_behaviors);

    XMLPullParserHandler parser = new XMLPullParserHandler();

    try {
        behaviors = parser.parse(getAssets().open("catagories.xml"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    grid = (GridLayout) findViewById(R.id.behaviorGrid);
    images = new ArrayList<ImageView>();

    grid.setColumnCount(NUM_OF_COLUMNS);
    grid.setRowCount(behaviors.size() / NUM_OF_COLUMNS);

    for (Behavior behavior : behaviors)
        images.add(this.getImageViewFromName(behavior.getName()));

}

@Override
public void onWindowFocusChanged(boolean hasFocus) {

    super.onWindowFocusChanged(hasFocus);
    View view = (View) findViewById(R.id.scrollView);

    int width = (int) (view.getWidth() * .45);
    Log.i("ViewWidth", Integer.toString(width));

    GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
    lp.height = width;
    lp.width = width;

    int childCount = images.size();

    ImageView image;

    for (int i = 0; i < childCount-1; i++) {

        image = images.get(i);
        image.setLayoutParams(lp);      
        grid.addView(image);

    }

}

根據我以前的經驗,使用

grid.add(View); 

工作正常,但現在我只能看到最后一個子顯示。 通過調試器,我可以看到gridview不僅填充了最后一個元素,還包含了最后一個imageview。

謝謝您的幫助

您應該為每個ImageView創建一個GridLayout.LayoutParams:

for (int i = 0; i < childCount-1; i++) {
    GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
    lp.height = width;
    lp.width = width;

    ......
}

GridLayout.LayoutParams包含位置信息,例如[column:2,row:3]。 在您的代碼中,所有ImageView都設置了相同的GridLayout.LayoutParams,因此它們位於同一單元格中(彼此重疊)。

當改用LinearLayout.LayoutParams時,其中沒有位置信息。 GridLayout將為每個子視圖創建一個新的GridLayout.LayoutParams,因此所有ImageView都使用它們自己的不同GridLayout.LayoutParams和位置。

希望這個幫助。 您可以閱讀GridLayout.java和ViewGroup.java以獲得更多詳細信息。

所以我解決了我的問題,盡管我不確定如何-

GridLayout.LayoutParams lp = new GridLayout.LayoutParams();

變成...

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(x,y);

使它按我想要的方式工作。 但是我不確定為什么-如果有人可以解釋,請:)

暫無
暫無

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

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