// main activity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener,
ButtonInterface{
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
listView = (ListView) findViewById(R.id.list_view);
Button clickMe = (Button) findViewById(R.id.main_button);
setSupportActionBar(toolbar);
ListAdapter listAdapter = new ListAdapter(this);
listAdapter.setButtonListener(MainActivity.this);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(this);
clickMe.setOnClickListener(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.list_view:
Toast.makeText(this,position+" is clicked",Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
Toast.makeText(this,"button is clicked",Toast.LENGTH_SHORT).show();
break;
case R.id.main_button:
Toast.makeText(this,"Main button is clicked",Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void buttonRespond(View view) {
Button b1 = (Button) view.findViewById(R.id.button);
b1.setOnClickListener(this);
}
}
ListAdapter:-
public class ListAdapter extends BaseAdapter{
Context context;
String[] title = new String[] {"Fruits","Animals","Plants"};
ButtonInterface buttonInterface;
public ListAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return title.length;
}
@Override
public Object getItem(int position) {
return title[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.single_row,parent,false);
findViews(view, position);
return view;
}
public void findViews(View view, int position){
TextView textView = (TextView) view.findViewById(R.id.textView);
Button button = (Button) view.findViewById(R.id.button);
buttonInterface.buttonRespond(view);
textView.setText(title[position]);
}
public void setButtonListener(ButtonInterface buttonListener){
this.buttonInterface = buttonListener;
}
}
Button Interface:-
public interface ButtonInterface {
public void buttonRespond(View view);
}
In the above example I am using an interface to get the views of a row in a listview. In main activity override that interface and find the views on single row and set onItemClickListener there itself.
Is this the right way to get list item onClick event on main activity?? Please suggest???