【发布时间】:2015-01-18 04:17:48
【问题描述】:
我正在尝试在 Android 中构建一个显示图像和一些文本字段(不可编辑)的自定义视图。
我首先为我的自定义视图扩展 RelativeLayout 类。
在我的自定义视图的构造函数中,我创建了一个ImageView 和一个TextView,并将它们添加到布局中。
TextView 会立即加载,但ImageView 会加载到不同的线程上,并且位图是通过处理程序填充的。
加载位图后,ImageView 与TextView 重叠。 TextView 应该在ImageView 的“右侧”,但这种调整不会自动发生。
我尝试使用customView.invalidate(),但这并没有帮助。
当通过 XML 声明相同的组件时,不存在此问题。
任何解决问题的帮助将不胜感激。谢谢
public class MyView extends RelativeLayout {
private TextView productName;
private ImageView productImage;
public MyView(Context context) {
super(context);
initHandler();
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initHandler();
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initHandler();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initHandler();
}
private void initHandler() {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// implement logic to show content here
productName.setText(currentProduct.getTitle());
productImage.setImageBitmap(currentProduct.getImageBitmap());
MyView.this.invalidate();
}
};
productImage = new ImageView(getContext());
RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
layout.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
productImage.setLayoutParams(layout);
//keep the textview to right of imageview
productName = new TextView(getContext());
layout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.addRule(RelativeLayout.RIGHT_OF, productImage.getId());
layout.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
productName.setLayoutParams(layout);
productName.setTextColor(Color.parseColor("#ffffff"));
this.addView(productImage);
this.addView(productName);
//logic to load content on a new thread goes here
}
}
我在其中包含自定义视图的 XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mycompany.MyView
android:background="@android:color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
【问题讨论】:
标签: android android-layout android-custom-view android-relativelayout