适配器有条件

时间:2014-03-11 12:22:54

标签: android android-adapter

可以在适配器中放入if / else语句吗?这是代码:

public void viewentry() {
    EntryList = controller.getAllEntry();
    ListAdapter adapter = new SimpleAdapter(
        MainActivity.this, 
        EntryList,
        R.layout.timeline,
        new String[] { "Id", "title", "content", "date", "time", "category", "tag", "location", "mood" }, 
        new int[] { R.id.Id, R.id.title, R.id.content, R.id.date, R.id.time, R.id.category, R.id.tag, R.id.location, R.id.mood }
    );
    setListAdapter(adapter);
}

2 个答案:

答案 0 :(得分:1)

是的,但是你需要为列表创建自己的自定义适配器。

完成本教程以创建自定义适配器Tutorial

以下是一个例子

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
  private final Context context;
  private final String[] values;

  public MySimpleArrayAdapter(Context context, String[] values) {
    super(context, R.layout.rowlayout, values);
    this.context = context;
    this.values = values;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
    textView.setText(values[position]);
    // Change the icon for Windows and iPhone
    String s = values[position];

    if (s.startsWith("Windows7") || s.startsWith("iPhone")
        || s.startsWith("Solaris")) {
      imageView.setImageResource(R.drawable.no);
    } else {
      imageView.setImageResource(R.drawable.ok);
    }

    return rowView;
  }
} 

在适配器的方法中查看 R.layout.rowlayout

在这里,您需要为列表创建自定义布局(rowlayout),然后找到您的repsective TextView的ID并执行您想要的任何操作。

答案 1 :(得分:0)

由于SimpleAdapter不是最终版,您可以从中扩展:

public void viewentry() {
    EntryList = controller.getAllEntry();
    ListAdapter adapter = new SimpleAdapter(
        MainActivity.this, 
        EntryList,
        R.layout.timeline,
        new String[] { "Id", "title", "content", "date", "time", "category", "tag", "location", "mood" }, 
        new int[] { R.id.Id, R.id.title, R.id.content, R.id.date, R.id.time, R.id.category, R.id.tag, R.id.location, R.id.mood }
    ) {

        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            v.findViewById(R.id.mood).setVisibility(condition ? View.GONE : View.VISIBLE);
            return v;
       }
    };
    setListAdapter(adapter);

}