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

时间:2017-04-04 17:10:56

标签: android android-layout android-view

我正面临着视图之间空间的问题。使用LinerLayout并动态地将视图(ImageViews)添加到线性布局。

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

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

}

单击“命中”按钮是在调用handleHit()时。并且添加的新图像正在使所有图像从第2个到目前的视图不可见。我只能看到第一个和最后一个(最新添加的)。

1 个答案:

答案 0 :(得分:0)

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

您在相对布局中寻找的是RelativeLayout,视图是相互依赖的,并且因为它也是ViewGroup类,所以相同的代码也适用于它。

检查相对布局文档here以及比较here

的简短帖子

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

您不必调用更新参数,而是将params添加到imageview。

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