![](/img/trans.png)
[英]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.