簡體   English   中英

以編程方式在Android的imageView中間放置一個textView

[英]Place a textView in the middle of imageView programatically android

我有一個ImageView和TextView以編程方式聲明(不在任何xml中)。

ImageView img = new ImageView(this);
TextView txt = new TextView(this);
        LinearLayout.LayoutParams coordinates = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

img.setLayoutParams(coordinates);
img.setImageResource(R.drawable.img);
txt.setText("a");

如何將文本放在imageview的中間? 我需要“ a”始終位於imageView的中間。

也許您應該只具有文本視圖,並使用圖像作為背景:

textView.setBackgroundResource(R.drawable.img);

實用上可以設置

   RelativeLayout relativeLayout=new RelativeLayout(context);
//set Relative Layout Parameter using 
RelativeLayout.LayoutParams relativeLayoutParams=new RelativeLayout.LayoutParams(RelativeLayout.MATCH_PARENT,RelativeLayout.MATCH_PARENT);
relativeLayout.setLayoutParams(relativeLayoutParams);

首先創建ImageView

ImageView imageView=new ImageView(context);
relativeLayout.addView(imageView);

然后在其上設置文本視圖

TextView textView=new TextView(context);
relativeLayout.addView(textView);

要以編程方式集中文本,您只需要使用重力

ImageView img = new ImageView(this);
TextView txt = new TextView(this);
LinearLayout.LayoutParams coordinates = new 
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
LinearLayout.LayoutParams.WRAP_CONTENT);

img.setLayoutParams(coordinates);
img.setImageResource(R.drawable.img);
txt.setText("a");
txt.setGravity(Gravity.CENTER);

要在ImageView的中間顯示它,可以進一步將ImageView的寬度擴展到MATCH_PARENT,這樣文本將始終出現在Imageview的中間

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM