开发者

How to add ImageViews to a View, dynamically

开发者 https://www.devze.com 2023-04-02 23:44 出处:网络
I want to create a deck of cards. I have a view called Deck (class Deck extends View) which I have set as the ContentView and I want to add the cards as ImageViews on the Deck, dynamically. I have sea

I want to create a deck of cards. I have a view called Deck (class Deck extends View) which I have set as the ContentView and I want to add the cards as ImageViews on the Deck, dynamically. I have searched a lot (google,forums) and I can't find a way that I can understand how it works, so I thought I'd ask this noob question..

If I have an ImageView card, how do I add it to the View deck and how do I specify where exactly it should be placed? I don't want to create an XML layout, because then I will have to add 52 cards by hand on the xml as ImageViews. I want to do this dynamically, and the layout handling has me confused. Help or pointers appreciated, thanks. Also, I dont want to use a canvas because I have no way of determining w开发者_如何学Pythonhich card bitmap is on top of another.


Here is how I would do it:

Deck deck = new Deck(this); // Create initial deck view
int iterations = 10; // Defined card count

for (int i = 0; i < iterations; i++) {
    Card card = new Card(this); // Create a new card (extends ImageView)
    card.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // Set some layout parameters
    card.setImageResource(R.drawable.card_blank); // Set the cards image
    deck.addView(card); // Add it to the deck
}
0

精彩评论

暂无评论...
验证码 换一张
取 消