将onItemClick设置为自定义适配器ListView

时间:2013-11-21 17:30:25

标签: java android listview android-listview

当我在过滤时尝试将listView项目的位置修复为所需的意图时遇到问题,并获得信息我可以使用自定义适配器覆盖问题,我已经这样做但我不知道如何分配点击对于每个项目,请检查以下代码:

public class IndexPageActivity extends Activity { 
ListView listView;
EditText editTextB;

@Override
protected void onCreate(Bundle savfedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.indexpage);
    listView = (ListView) findViewById(R.id.pageList);
    editTextB = (EditText) findViewById(R.id.searchB);
    listView.setAdapter(new PagesAdapter(this));
    listView.setOnItemClickListener((OnItemClickListener) this);

}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
    this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements OnItemClickListener{
ArrayList<SingleRow> pagelist;
Context context;

PagesAdapter(Context c){
    context=c;
    pagelist = new ArrayList<SingleRow>();
    Resources res = c.getResources();
    String [] pagedatas = res.getStringArray(R.array.pages_data);
    for (int i=0;i<463;i++){
        pagelist.add(new SingleRow(pagedatas[i]));
    }
}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return pagelist.size();
}

@Override
public Object getItem(int i) {
    // TODO Auto-generated method stub
    return pagelist.get(i);
}

@Override
public long getItemId(int i) {
    // TODO Auto-generated method stub
    return i;
}

@Override
public View getView(int i, View view, ViewGroup viewG) {
    // TODO Auto-generated method stub
    LayoutInflater inflater=(LayoutInflater)             context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row=inflater.inflate(R.layout.single_row,viewG,false);
    TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);

    SingleRow temp=pagelist.get(i);

    pagetitle.setText(temp.pagedata);
    return row;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
    // TODO Auto-generated method stub

}
}

我将不胜感激任何帮助。谢谢Yhu!

修改

这会有用吗?

 if (index == 0) {
    Intent i = new Intent(this, WebViewActivity.class);
    i.putExtra("keyHTML", "file:///android_asset/page1.html");
    startActivity(i);
} else if (index == 1) {
    Intent i = new Intent(this, WebViewActivity.class);
    i.putExtra("keyHTML", "file:///android_asset/page2.html");
    startActivity(i);

3 个答案:

答案 0 :(得分:8)

全部编辑

我刚刚得到了您需要的内容,我在您的baseAdapter添加了一个过滤器,然后在editText内更改了文字您过滤了listView,然后您转到了所需的活动。

这里是完整的代码,但您需要记住我已经更改了以下内容:

  • 我将pageList更改为ArrayList而不是
  • 过滤时有一个错误,当我删除我在EditText中写的不更新ListView的内容时,你需要找出原因。
  • 我将函数getItem(int i)的返回值从Object更改为String
  • onItemClick内,您必须搜索名称而不是位置。

这是代码:

public class IndexPageActivity extends Activity implements OnItemClickListener{ 
ListView listView;
EditText editTextB;
PagesAdapter adapter1;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
            listView = (ListView) findViewById(R.id.pageList);
            editTextB = (EditText) findViewById(R.id.searchB);
            adapter1 = new PagesAdapter(this);
            listView.setAdapter(adapter1);
            adapter1.notifyDataSetChanged();
            listView.setOnItemClickListener(this);

            editTextB.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2,
                        int arg3) {
                    // When user changed the Text
                    IndexPageActivity.this.adapter1.getFilter().filter(cs.toString());
                    adapter1.notifyDataSetChanged();
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub
                }
            });
    }


@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
    // TODO Auto-generated method stub
    Intent i;
    String name = adapter1.getItem(position);
            Log.d("id", name);
    if (name.equals("Item1"))
    {
        i = new Intent(this, anActivity.class);
        startActivity(i);
    }
    else if (name.equals("Item2"))
    {
        i = new Intent(this, anActivity2.class);
        startActivity(i);
    }
}
}


class SingleRow {
String pagedata;
SingleRow(String pagedata){
    this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements Filterable{
ArrayList<String> pagelist;
List<String> arrayList;
Context context;
String [] pagedatas;

PagesAdapter(Context c){
    context=c;
    pagelist = new ArrayList<String>();
    Resources res = c.getResources();
    pagedatas = res.getStringArray(R.array.pages_data);
    for (int i=0;i<463;i++){
        pagelist.add(pagedatas[i]);
    }
}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return pagelist.size();
}

@Override
public String getItem(int i) {
    // TODO Auto-generated method stub
    return pagelist.get(i);
}

@Override
public long getItemId(int i) {
    // TODO Auto-generated method stub
    return i;
}


@Override
public View getView(int i, View view, ViewGroup viewG) {
    // TODO Auto-generated method stub
    LayoutInflater inflater=(LayoutInflater)             context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row=inflater.inflate(R.layout.single_row,viewG,false);
    TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);

    String temp=pagelist.get(i);

    pagetitle.setText(temp);
    return row;
}

public class filter_here extends Filter{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        // TODO Auto-generated method stub

        FilterResults Result = new FilterResults();
        // if constraint is empty return the original names
        if(constraint.length() == 0 ){
            Result.values = pagelist;
            Result.count = pagelist.size();
            return Result;
        }

        ArrayList<String> Filtered_Names = new ArrayList<String>();
        String filterString = constraint.toString().toLowerCase();
        String filterableString;

        for(int i = 0; i<pagelist.size(); i++){
            filterableString = pagelist.get(i);
            if(filterableString.toLowerCase().contains(filterString)){
                Filtered_Names.add(filterableString);
            }
        }
        Result.values = Filtered_Names;
        Result.count = Filtered_Names.size();

        return Result;
    }

    @Override
    protected void publishResults(CharSequence constraint,FilterResults results) {
        // TODO Auto-generated method stub
        pagelist = (ArrayList<String>) results.values;
        notifyDataSetChanged();
    }

}

@Override
public Filter getFilter() {
    // TODO Auto-generated method stub

    return new filter_here();
}
}

答案 1 :(得分:2)

两种不同的方式:

1)如果你想在活动的onCreate上使用这样的东西;

listView.setOnItemClickListener((OnItemClickListener) this);

您应该对您的活动实施OnItemClickListener

IndexPageActivity extends Activity implements OnItemClickListener

并在您的活动中实现其onItemClick方法。 (还要从自定义适配器中删除OnItemClickListener接口)

2)您可以直接使用以下内容而无需向任何类实施OnItemClickListener

listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO: handle row clicks here
    }

我建议第二种选择。这更容易。

编辑:这与您的问题无关,但您应该在listView上重复使用您的视图/行。将getView方法更改为:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view;
    if (convertView == null) {
        LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.single_row, parent, false);
    } else {
        view = convertView;
    }

    TextView pagetitle = (TextView) view.findViewById(R.id.textViewRow);

    SingleRow temp=pagelist.get(i);

    pagetitle.setText(temp.pagedata);
    return view;
}

答案 2 :(得分:1)

设置setOnItemClickListenerlike这个:

@Override
protected void onCreate(Bundle savfedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.indexpage);
    listView = (ListView) findViewById(R.id.pageList);
    editTextB = (EditText) findViewById(R.id.searchB);
    listView.setAdapter(new PagesAdapter(this));
    listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        //Your code here
        //int position is the index of the list item you clicked    
        //use it to manipulate the item for each click      
    }
});
}