如何在布局中重叠图像视图

How to overlap imageviews in a layout

我遇到了视图之间 space 的问题。使用 LinerLayout 并将视图(ImageViews)动态添加到线性布局。

我想调整imageview之间的space。我希望它们有重叠 - 添加新视图时。

Current view of the app

目前应用蓝色背景来突出两个线性布局。

将图像视图添加到现有布局的代码

dealerImages= (LinearLayout) findViewById(R.id.dealerImages);
    dealerImages.setBackgroundColor(Color.BLUE);

ImageView view = new ImageView(BlackJack.this);
    view.setImageResource(R.drawable.back);
    dealerImages.addView(view);

每次添加新视图时 - 我都想指定与旧视图的相对位置。我希望 新视图从布局中最后一个视图 的中心开始。

如果您需要任何其他详细信息,请告诉我。请建议我是否需要使用任何其他布局来使事情变得更容易。

编辑 - 在此处发布代码

 playerLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.MATCH_PARENT);
    dealerLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.MATCH_PARENT);


private void dealTwoCardsEach(){
    player.addCard(hit());
    ImageView imageView = new ImageView(BlackJack.this);
    imageView.setImageResource(getResourceId(player.getFirstCard()));
    playerImages.addView(imageView, player.getCards().size()-1);

    dealer.addCard(hit());
    imageView = new ImageView(BlackJack.this);
    imageView.setImageResource(getResourceId(dealer.getFirstCard()));
    dealerImages.addView(imageView);

    player.addCard(hit());
    if(player.getCount() == 21)
        player.setBlackJack(true);

    imageView = new ImageView(BlackJack.this);
    imageView.setImageResource(getResourceId(player.getSecondCard()));
    updateMarginForPlayer(); // updating start margin
    playerImages.addView(imageView, player.getCards().size()-1, playerLayoutParams);

    dealer.addCard(hit());
}


private void updateMarginForPlayer(){
        playerLayoutParams.setMarginStart(playerLayoutParams.getMarginStart()+100);
}

请注意,我没有为玩家的第一张牌设置任何保证金。 我可以看到两张卡片,直到这里。第一张图片的起始边距为 0,第二张图片的起始边距为 100。

private void handleHit(){
    Card c1 = hit();
    player.addCard(c1);

    ImageView imageView = new ImageView(this);
    imageView.setImageResource(getResourceId(c1));
    updateMarginForPlayer();
    playerImages.addView(imageView, playerLayoutParams);

}

单击 'Hit' 按钮时会调用 handleHit()。并且添加的新图像使所有图像从 2nd 到当前视图不可见。我只能看到第一个和最后一个(最新添加的)。

A LinearLayout 以线性方式一个接一个地堆叠视图。您永远无法仅使用 LinearLayout 创建重叠布局,它始终会根据定义的任何方向将其堆叠在当前视图旁边。

您正在寻找的是相对布局中的 RelativeLayout,视图相互依赖堆叠,并且由于它也是 ViewGroup class,因此相同的代码将也为它工作。

查看相关布局文档here and a brief post of their comparison here

此外,当您在相对布局中创建子项时,您可以将参数添加到它所在的位置,或者只需添加一个占原始布局一半大小的边距,以便从中心堆叠它们!

您不必调用更新参数,而是将参数添加到图像视图。

  ImageView imageView = new ImageView(this);
    imageView.setImageResource(getResourceId(c1));
      RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(100,0,0,0);
    imageView.setLayoutParams(layoutParams);

    playerImages.addView(imageView, playerLayoutParams);