简体   繁体   中英

Drawing shapes programmatically for Android

I'm new to the Android SDK so I'm trying to figure this out. I have read the documentation and a text book and they haven't been particularly helpful in this matter.

I'm just trying to draw a simple rectangle in a linear layout on the screen. I can't get the shape to show up, however, when I add text to this layout in the same fashion, the text does show up. What am I missing?

package jorge.jorge.jorge;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ShapesActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ShapeDrawable rect = new ShapeDrawable(new RectShape());

        rect.getPaint().setColor(Color.GREEN);

        ImageView view1 = new ImageView(this);

        view1.setImageDrawable(rect);

        LinearLayout frame = (LinearLayout)findViewById(R.id.linear1);

        frame.addView(view1);

//        TextView tx = new TextView(this);
//        
//        tx.setText("Hello World");
//        
//        frame.addView(tx);
    }
}

The Shape is usually used for making a background to some View. Its width and height is the same of the view that is using it. Then, if this view has no width and height, It'll have no width and height, too.

Basically, I think that your ImageView has no width and height, then it's invisible. You can see how to set it programatically here: Set ImageView width and height programmatically?

But, I recomend you to make the layout in XML's way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM