下面是我想要實現的一點背景,爲了幫助我的問題更清晰一點...我創建了一個導航抽屜,其中每個項目在ListView看起來類似於以下內容:Subclassed RelativeLayout在ListView中不調用的onDraw()方法
不過,我需要能夠在右側邊框(藍色)的顏色改變爲各種不同顏色的程序,因此,雖然打轉轉通過解決方案,我決定延長RelativeLayout
並在onDraw(Canvas c);
方法中畫出線。我RelativeLayout
代碼如下:
public class CustomRelativeLayout extends RelativeLayout {
private final Paint paint = new Paint();
public CustomRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
//Other Constructors
private void init() {
setPaintColor(Color.argb(128, 0, 0, 0));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(getMeasuredWidth() - 1, 0, getMeasuredWidth() - 1, getMeasuredHeight(), paint);
}
public void setPaintColor(int color){
paint.setColor(color);
invalidate();
}
}
我NavigationDrawer
的ListView
還包含使用這個類的標題,並能正常工作的頭視圖。但是,對於每個人ListView
項目,邊框不存在。我已經調試了我的解決方案,並發現我的子類別RelativeLayout
的onDraw(Canvas c);
方法是針對標題視圖調用的,但不會爲我的ArrayAdapter<String>
提供的ListView
的子視圖調用每個方法。
我知道還有其他方法可以處理這個問題,例如使用默認的View
,將背景設置爲我想要的顏色,並將其對齊到右側 - 但那不是我的問題。我的問題是爲什麼我的CustomRelativeLayout
的onDraw(Canvas c);
方法被稱爲ListView
的標題視圖,而不是爲我的適配器提供的每個視圖?任何洞察這種行爲將不勝感激。另外,這裏是在情況與ListView
使用CustomArrayAdapter
和nav_drawer_item.xml
他們是有幫助的:
public class SimpleDrawerAdapter extends ArrayAdapter<String> {
public SimpleDrawerAdapter(Context context, int resource,
String[] sections) {
super(context, resource, sections);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout container = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
container = (CustomRelativeLayout) inflater.inflate(R.layout.nav_drawer_item, parent, false);
} else {
container = (CustomRelativeLayout) convertView;
}
((TextView)container.findViewById(R.id.nav_item_text)).setText(getItem(position));
return container;
}
}
nav_drawer_item.xml
<?xml version="1.0" encoding="utf-8"?>
<com.mypackage.views.CustomRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="wrap_content">
<TextView
android:id="@+id/nav_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/nav_drawer_grey"
android:textSize="@dimen/text_large"
android:layout_margin="@dimen/navigation_drawer_item_margin"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</com.mypackage.views.CustomRelativeLayout>
您是否嘗試通過在自定義佈局中調用[setWillNotDraw](http://developer.android.com/reference/android/view/View.html#setWillNotDraw(boolean))方法來清除WILL_NOT_DRAW標誌? – curtisLoew
不錯,這解決了這個問題。我猜ListView通過將此標誌設置爲true來優化ViewGroups?發佈這個答案,我會接受。 – Submersed
很高興幫助。我相信ViewGroups默認啓用了這個功能,是的。 – curtisLoew