在Android中的自定义ListView中绘制矩形

时间:2014-04-10 11:26:27

标签: android view android-listview android-canvas listadapter

我必须在android中的ListView行中绘制自定义形状。我在网上发现了这个,但无法成功。我有一个DrawView.java类,它在Canvas上创建一个矩形,我希望这个类的对象包含在我的自定义ListView行中。

DrawView.java

    package com.example.horizontalscrollview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);            
    }

    @Override
    public void onDraw(Canvas canvas) {
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(30, 30, 180, 180, paint);


    }

}

我的一行Custom ListView的xml文件是

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="60dp"
    android:id="@+id/mainLayout"
     >

     <com.example.horizontalscrollview.DrawView
        android:id="@+id/drawview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >
      </com.example.horizontalscrollview.DrawView>

</LinearLayout>
ListView的自定义适配器的

和getView()函数是:

        public View getView(final int position,  View convertView, final ViewGroup parent) {

        Toast.makeText(c, "Clicked on="+position, 1).show();
        convertView = mInflater.inflate(R.layout.news_list_item,null);
        DrawView rl = (DrawView)convertView.findViewById(R.id.drawview);
        DrawView draw = new DrawView(c);
        rl=draw;
        return convertView;
} 

1 个答案:

答案 0 :(得分:1)

在你的获取视图方法中膨胀这个xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
 android:layout_margin="60dp"
android:id="@+id/mainLayout"
 >

 <com.example.horizontalscrollview.DrawView
    android:id="@+id/drawview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" >
  </com.example.horizontalscrollview.DrawView>

</LinearLayout> 

这里是获取视图方法

 public View getView(final int position,  View convertView, final ViewGroup parent) {

    Toast.makeText(c, "Clicked on="+position, 1).show();
    convertView = mInflater.inflate(R.layout.news_list_item,null);

    return convertView;
} 

它应该可以正常工作,如果这不工作请告知问题:) 快乐的编码