添加onClick到listview?

时间:2017-10-24 12:02:33

标签: java android listview

我有一个ListView我希望根据ListView上点击的值运行一个函数,我现在只想知道如何获取和烘烤我试图做的值但是不知道正确的代码......请检查我的代码。

public class SubCategory extends AppCompatActivity implements View.OnClickListener {

private ListView listView;
String buttonType;
ArrayAdapter adapter;

static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana"};
static final String[] NAMES = new String[] { "Sachin", "Brett", "Shane", "Zaheer"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sub_category);



    Bundle bundle = getIntent().getExtras();
    if(bundle != null) {
        buttonType = bundle.getString("BUTTON_CLICKED");
    }
    if(buttonType != null && buttonType.equals("A")) {
        adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, FRUITS);
    } else if(buttonType != null && buttonType.equals("B")) {
        adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, NAMES);
    }
    listView = (ListView)findViewById(R.id.listview);
    listView.setAdapter(adapter);
}

     public void getList() {

        Toast.makeText(listView.getContext(), Toast.LENGTH_LONG).show();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.listview:
                getList();
                break;
    }
}
}

3 个答案:

答案 0 :(得分:3)

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        list.get(position).GET_INFORMATION(); //GET_INFORMATION will be the method in your POJO class
    }
});

答案 1 :(得分:2)

试试这个

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      String value="";
      if(!TextUtils.isEmpty(buttonType) && buttonType.equals("A")) {
          value=FRUITS[position];
       } else if(!TextUtils.isEmpty(buttonType) && buttonType.equals("B")) {
          value=NAMES[position];
       }
     // you can get value in "value"
       showToast(value);
    }
});
public void showToast(String value) {

    Toast.makeText(this,value, Toast.LENGTH_LONG).show();

}

答案 2 :(得分:1)

要将click侦听器添加到listview,请按照以下步骤操作

1.add在活动的oncreate方法中单击这样的监听器。

listView.setOnItemClickListener(this);

2.在活动中实现OnItemClickListener。

public class Main2Activity extends AppCompatActivity implements AdapterView.OnItemClickListener {

3.在活动中取消onItemClick方法。

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    //Call method here
}