问题描述:

I'm working with Android Studio and I'm trying with Java to put a TextView below a ImageView. For that, I wrote this code:

 //RelativeLayout

RelativeLayout relativeLayout = new RelativeLayout(this);

relativeLayout.setBackgroundColor(Color.parseColor("#006699"));

//Texto: Press to start

TextView start = new TextView(this);

start.setId(R.id.startText);

start.setText("Press to start");

start.setTextColor(Color.parseColor("#FFFFFF"));

start.setTextSize(16);

//ImageView

ImageView logo = new ImageView(this);

int id = getResources().getIdentifier("logo", "drawable", getPackageName());

logo.setImageResource(id);

logo.setId(R.id.logo);

//Posición de la imagen

RelativeLayout.LayoutParams imageDetails = new RelativeLayout.LayoutParams(

RelativeLayout.LayoutParams.WRAP_CONTENT,

RelativeLayout.LayoutParams.WRAP_CONTENT

);

imageDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);

imageDetails.addRule(RelativeLayout.CENTER_VERTICAL);

relativeLayout.addView(logo, imageDetails);

//Text Position:

RelativeLayout.LayoutParams textDetails = new RelativeLayout.LayoutParams(

RelativeLayout.LayoutParams.WRAP_CONTENT,

RelativeLayout.LayoutParams.WRAP_CONTENT

);

textDetails.addRule(RelativeLayout.ABOVE, logo.getId());

textDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);

// start.bringToFront(); It still doesn't appear

relativeLayout.addView(start, textDetails);

setContentView(relativeLayout);

But when I run that code, it only appears the ImageView on the screen:

1

What's the problem? Thank you so much!

网友答案:

Easiest way to use LinearLayout and then first add ImageView then add TextView. This will work.

网友答案:

1>In android application, there is a need of unique id(eg.In layout/main.XML etc. place, id=textview1 like ) for your component(eg. textview,imageview etc.) which you can find it out in your XML file. You have to use that(id) into your java code to connect backend and forntend. Then only it your textview work.

2>In other case just check with your layout that other components are not hiding your textview.

网友答案:

There a better solution for this, just use:

start.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.logo);

That's way you don't need another wrapper view like RelativeLayout

相关阅读:
Top