[英]android studio Make a textView below an imageview visible if imageview has no image
[英]Android Studio - TextView below ImageView
我正在使用Android Studio,并且正在尝试使用Java将TextView放在ImageView下面。 为此,我编写了以下代码:
//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);
但是当我运行该代码时,它仅在屏幕上显示ImageView:
有什么问题? 非常感谢!
使用LinearLayout
最简单方法,然后先添加ImageView
然后再添加TextView
。 这将起作用。
1>在android应用程序中,需要为您的组件(例如textview,imageview等)提供唯一的id(例如,在layout / main.XML等位置,id = textview1喜欢),您可以在其中找到您的XML文件。 您必须在Java代码中使用that(id)来连接后端和前端。 然后只有它您的textview起作用。
2>在其他情况下,只需检查您的布局是否其他组件没有隐藏您的textview。
为此,有一个更好的解决方案,只需使用:
start.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.logo);
这样一来,您就不需要像RelativeLayout
这样的另一个包装视图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.