我有一个以编程方式声明的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的中间。
答案 0 :(得分:1)
也许你应该只有一个文本视图并使用图像作为背景:
textView.setBackgroundResource(R.drawable.img);
答案 1 :(得分:1)
使用语用,你可以设置它
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);
答案 2 :(得分:1)
要以编程方式集中文本,您只需使用 gravity
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的中间