LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout3);
TextView tv = new TextView(this);
ImageButton imb=new ImageButton(this);
ll.addView(tv);
tv.setSingleLine();
tv.setEllipsize(TruncateAt.MARQUEE);
tv.setHorizontallyScrolling(true);
tv.setFocusableInTouchMode(true);
tv.setText(myString1);
上面的代码,现在可以在 textView 中显示数据。但是我想把一个 imageButton 放置到
textView 的左边,但是如何以代码的形式实现呢?
解决你的问题有两种方法。如果你想在 textview 的右边显示图像,使用下面的代码:
TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon,0, 0,0);
或者,把 linearlayout设置成横向的,首先添加 imageview,然后再添加 textview。就用按照你需要的对齐:
TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
ImageButton imb=new ImageButton(this);
imb.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
ll.addView(imb);
ll.addView(tv);