在Android中创建自定义视图列表

时间:2014-08-21 18:56:26

标签: android android-listview custom-controls android-custom-view custom-component

我想创建一个自定义列表,其中每个项目都包含自定义视图和其他一些内容,例如文本视图......

我应该在适配器中做什么,以便我可以在列表中显示不同coulours的自定义视图???

以下是我到目前为止的代码

Main.java

public class Main extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //some data declaration

    ListView lv = (ListView)findViewById(R.id.myList);
    lv.setAdapter(new MyAdapter(this, data, R.layout.item));
}
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
 <ListView
  android:id="@+id/myList"
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" >
 </ListView>
</LinearLayout>

MyAdapter.java

public class MyAdapter extends BaseAdapter {
   //private variables
   //some functions

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

    View vi = convertView;
    if(convertView == null) vi = inflater.inflate(gif_view);

    View customView = (View)findViewById(R.id.my_custom_view);
    /* what to do here ?? */
    /*                   */
}

item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.android.me.MyView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    class="com.android.gif.GIFView"
    android:id="@+id/my_custom_view"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />
/*
   some other stuff
*/
</RelativeLayout>

MyView.java

public class MyView extends View{
  int color;

  public MyView(Context context, int color){
    super(context);
    this.color = color;
  }

  @Override
  protected void onDraw(Canvas canvas) {
    canvas.drawColor(color);
    super.onDraw(canvas);

    this.invalidate();
  }
}

任何帮助将不胜感激。 谢谢:))

1 个答案:

答案 0 :(得分:0)

您的MyView将由系统实例化,因此您必须手动更改颜色。我添加了setColor(int)方法。

public class MyView extends View{
  int color;

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

  public void setColor(int color) {
    this.color = color;
    invalidate();
  }


  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(color);

    // DON'T CALL THIS, OR IT WILL LOOP INDEFINITELY
    //this.invalidate();
  }
}



public class MyAdapter extends BaseAdapter {
   public View getView(int position, View convertView, ViewGroup parent) {

    View vi = convertView;
    if(convertView == null) vi = inflater.inflate(gif_view);

    ((MyView)(vi.findViewById(R.id.my_custom_view)).setColor(randomColor);
}