I'm trying to write a simple checklist application that contains a LinkedList view that has text and two radio buttons that indicate yes/no. The problem is that when I check one radio button as I scroll down the LinkedList changes the answers in my radio buttons. I'd appreciate any suggestions you have.
My code is as follows
My primary layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
android:divider="#b5b5b5"
android:dividerHeight="1dp" />
</RelativeLayout>
My row item layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radio_group1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/mRadio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="radio1" />
<RadioButton
android:id="#+id/mRadio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="radio2" />
</RadioGroup>
</LinearLayout>
My backend java class for the main checklist activity
public class Checklist2 extends Activity {
//Class Values
AlertHandler ah; // object that manages the database of alerts
QuestionHandler qh; // object that manages the database of questions
List <Question>questions ; //List that holds all the Question items in the program
List <Alert> alerts; //List that holds all the Alert items in the program
private ArrayList<RowObject> mSource;
TextView mCountTextView; // from internet example
ListView mListView;
RadioGroupAdapter adapter;
private ListView listView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist2);
Log.w("Test", "setList()");
setList();
RadioGroup rg = (RadioGroup) findViewById(R.id.radio_group1);
}
//sets the ListView with questions
private void setList(){
mSource = new ArrayList<RowObject>();
Log.w("Test", "ArrayList<RowObject> created");
for (int i =0; i<questions.size(); i++){
Question q = questions.get(i);
mSource.add(new RowObject());
mSource.get(i).setID(q.getID());
mSource.get(i).setQuestion(q.getQuestion());
mSource.get(i).setYes(false);
mSource.get(i).setNo(false);
}
Log.w("Test", "array list filled");
mListView = (ListView) findViewById(R.id.list);
adapter = new RadioGroupAdapter(this,
R.layout.listitem, mSource);
Log.w("Test", "adapter created");
mListView.setAdapter(adapter);
Log.w("Test", "adapter set");
}}
My RowObject.java class
package com.randstad.jpmcchecklist;
public class RowObject {
private int ID;
private boolean yes;
private boolean no;
public String question;
public RowObject(){
super();
}
public RowObject(int iD, String q,boolean y) {
super();
ID = iD;
question = q;
this.yes = y;
}
public RowObject( String question) {
super();
this.question = question;
}
public void setYes(boolean y){
yes = y;
}
public boolean getYes(){
return yes;
}
public void setNo(boolean n){
no = n;
}
public boolean getNo(){
return no;
}
public void setQuestion(String q){
question = q;
}
public String getQuestion(){
return question;
}
public void setID(int id){
ID = id;
}
public int getID(){
return ID;
}
}
My Adapter class
public class RadioGroupAdapter extends ArrayAdapter<RowObject> {
Context context;
int layoutResourceId;
ArrayList <RowObject> data = null;
int position;
ViewHolder holder;
public RadioGroupAdapter(Context context, int layoutResourceId,
ArrayList <RowObject> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
holder = null;
this.position = position;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
holder.yes = (RadioButton) row.findViewById(R.id.mRadio1);
holder.no = (RadioButton) row.findViewById(R.id.mRadio2);
holder.group = (RadioGroup) row.findViewById(R.id.radio_group1);
row.setTag(holder);
//final RadioButton[] rb = new RadioButton[2];
/*
for(int i=0; i<2; i++){
rb[i] = new RadioButton(context);
//rb[i].setButtonDrawable(R.drawable.single_radio_chice);
rb[i].setId(i);
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
0, LayoutParams.WRAP_CONTENT);
params.weight=1.0f;
params.setMargins(15, 0, 5, 10);
holder.group.addView(rb[i],params); //the RadioButtons are added to the radioGroup instead of the layout
}
rb[0].setText("Yes");
rb[1].setText("No");
row.setTag(holder);*/
} else {
holder = (ViewHolder) row.getTag();
}
holder.group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.mRadio1:
data.get(position).setYes(true);
data.get(position).setNo(false);
break;
case R.id.mRadio2:
data.get(position).setNo(true);
data.get(position).setYes(false);
}
if(data.get(position).getYes()==true){
holder.yes.setChecked(true);
holder.no.setChecked(false);
}else if(data.get(position).getNo() == true){
holder.yes.setChecked(false);
holder.no.setChecked(true);
}else{
holder.yes.setChecked(false);
holder.yes.setChecked(false);
}
}
});
if(data.get(position).getYes()==true){
holder.yes.setChecked(true);
holder.no.setChecked(false);
}else if(data.get(position).getNo() == true){
holder.yes.setChecked(false);
holder.no.setChecked(true);
}else{
holder.yes.setChecked(false);
holder.yes.setChecked(false);
}
//RowObject option = data[position];
//holder.txtTitle.setText(option.title);
return row;
}
static class ViewHolder {
TextView txtTitle;
RadioGroup group;
RadioButton yes;
RadioButton no;
int position;
}}
Thanks, I really appreciate your help.
I guess the error is in
else{
holder.yes.setChecked(false);
holder.yes.setChecked(false);
}
Which should be
else {
holder.yes.setChecked(false);
holder.no.setChecked(false);
}
And for performance - call data.get(position) once in getView() and store it as a local variable.
Try calling row.setTag(holder); right before return row.
Also, you have holder.yes.setChecked(false) twice in your else case.
Related
I have a custom List Adapter that has a question in a Text View and four options as an answer in Radio Buttons. All the Radio Buttons are bound together in a Radio Group.
The problem is that I cannot keep track of the buttons that are checked.On scrolling the buttons get checked on random.
How can I store the radio buttons that are checked for a particular
public class MCQAdapter extends ArrayAdapter {
public MCQAdapter(Activity context, ArrayList<MCQ> mcq) {
super(context, 0, mcq);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.activity_mcqlist, parent, false);
}
final MCQ currentContent = (MCQ) getItem(position);
TextView content = (TextView) listItemView.findViewById(R.id.Question_Block);
content.setText(currentContent.getQuestion());
RadioGroup rg = (RadioGroup) listItemView.findViewById(R.id.Radio_Group);
final RadioButton rb1 = (RadioButton) listItemView.findViewById(R.id.Option1_Block);
rb1.setText(currentContent.getOptionA());
final RadioButton rb2 = (RadioButton) listItemView.findViewById(R.id.Option2_Block);
rb2.setText(currentContent.getOptionB());
final RadioButton rb3 = (RadioButton) listItemView.findViewById(R.id.Option3_Block);
rb3.setText(currentContent.getOptionC());
final RadioButton rb4 = (RadioButton) listItemView.findViewById(R.id.Option4_Block);
rb4.setText(currentContent.getOptionD());
return listItemView;
}
}
public class MCQ {
String question,optionA,optionB,optionC,optionD,answer,userAnswer;
public MCQ(String quest,String a,String b,String c, String d,String ans){
question = quest;
optionA = a;
optionB = b;
optionC = c;
optionD = d;
answer = ans;
}
public String getQuestion(){
return question;
}
public String getOptionA() {
return optionA;
}
public String getOptionB() {
return optionB;
}
public String getOptionC() {
return optionC;
}
public String getOptionD() {
return optionD;
}
public String getAnswer() {
return answer;
}
public String getUserAnswer() {
return userAnswer;
}
public void setUserAnswer(String userAnswer) {
this.userAnswer = userAnswer;
}
}
public class PropertiesOfConstructionMaterail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_properties_of_construction_materail);
final ArrayList<MCQ> mcq = new ArrayList<MCQ>();
//Creating Different Instance Of MCQ to genarte various questions for Properties of Consrtuction Material
mcq.add(new MCQ("The property of material by which it can be beaten or rolled into thin plates, is called ?",
"Malleability","Ductility","Plasticity","Elasticity","Malleability"));
mcq.add(new MCQ("The property by which a body returns to its original shape after removal of the force, is called ?",
"Plasticity","Elasticity","Ductility","Malleability","Elasticity"));
mcq.add(new MCQ("The property of a material by which it can be drawn into smaller section due to tension, is called ?"
,"Plasticity","Ductility","Elasticity","Malleability","Ductility"));
MCQAdapter adapter = new MCQAdapter(this,mcq);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_mcqlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.silen.civilengineeringmcq.MCQList"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Question_Block"
android:textSize="18dp"
android:textStyle="bold"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Radio_Group">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option1_Block"
android:checked="false"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option2_Block"
android:checked="false"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option3_Block"
android:checked="false"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option4_Block"
android:checked="false"/>
</RadioGroup>
You should create a wrapper around your PoJo class (MCQ), name it ViewModel, which store the current state of view inside adapter. In your case that state is a state of radio buttons.
It will looks like:
class ViewModel extends MCQ {
MCQ mcq;
int radioButtonSelectedId;
public ViewModel(MCQ mcq) {
this.mcq = mcq;
this.radioButtonSelectedId = R.id.Option1_Block;
}
public void setRadioButtonSelectedId(int id) {
this.id = id;
}
public int getRadioButtonSelectedId() {
return id;
}
//delegates to mcq getter/setter methods
}
Your getView method:
public View getView(int position, View convertView, ViewGroup parent) {
//your logic above
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
viewModel.setRadioButtonSelectedId(checkedId);
}
});
//same for other radio buttons
rb1.setChecked(viewModel.getRadioButtonSelectedId() == R.id.Option1_Block);
//your logic below
}
So as i mention above, your array list inside adapter would contain ViewModels wrappers, not MCQ classes directly
final ArrayList<ViewModel> mcqList = new ArrayList<>();
MCQ mcq = new MCQ("The property of material by which it can be beaten or rolled into thin plates, is called ?",
"Malleability","Ductility","Plasticity","Elasticity","Malleability")
mcqList.add(new ViewModel(mcq));
I think you should get an option
I wanted to show 2 items on a single row in textfield,How can I place 2 items in the same row in listview?
I want something like this to be displayed :
item 1
item 2|item3
item 4
item 5 | item 6
My code :
public class MultipleItemsList extends ListActivity {
private MyCustomAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();
int count=0;
for (int i = 1; i < 50; i++) {
if(count==0){
mAdapter.addItem("item " + i);
count++;
}
else if (count == 1) {
mAdapter.addSeparatorItem("item " + i);
count++;
}
else if(count==2){
mAdapter.addSeparatorItem1("item "+i);
count=0;
}
}
setListAdapter(mAdapter);
}
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_SEPARATOR1=2;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
private TreeSet<Integer> mSeparatorSet1=new TreeSet<Integer>();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public void addSeparatorItem1(final String item){
mData.add(item);
mSeparatorSet1.add(mData.size()-1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
if(mSeparatorsSet.contains(position)){
return TYPE_SEPARATOR;
}
else if(mSeparatorSet1.contains(position)){
return TYPE_SEPARATOR1;
}
else
return TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.item1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.item2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
break;
case TYPE_SEPARATOR1:
convertView=mInflater.inflate(R.layout.item2,null);
holder.textView=(TextView)convertView.findViewById(R.id.textSeparator1);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
}
ListView doesn't really support this kind of operation. Items in a ListView must be stacked vertically. And the inner implementation of ListView will prevent any simple attempt to convince it to lay items out differently.
Check out the GridLayout control in the compatibility library. That covers what you want to do fairly easily.
For displaying two items in one row, you must use LinearLayout as parent with weight 1. Orientation of linear layout must be horizontal.
add two childs with weight 0.5 inside the linear layout.
Definitely not the only way to do it but it will do what you ask for.
Hope it helps.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="text" />
</LinearLayout>
I have a ListView in my MainActivity which has a customAdapter to it. I am implementing a slider on each of the list items. I have also attached a footerView to my listView. Now my problem is that, the setOnClickListener is not fired, and I am not able to print the position's of the listView. It only print's for the footerView alone, which I have attached.
The code for MainActivity is
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
Then the code for my CustomAdapter is
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
Then finally the ViewPagerAdapter code is
public class MyViewPager extends ViewPager {
private static final String TAG = "MyViewPager";
private float xDown;
private float xMove;
private float yDown;
private float yMove;
private boolean isScroll = false;
private int selfIndex;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSelfIndex(int index) {
selfIndex = index;
}
public int getSelfIndex() {
return selfIndex;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.v(TAG, "on intercept");
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return super.onInterceptTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v(TAG, "on dispatch");
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
xDown = ev.getRawX();
yDown = ev.getRawY();
Log.v(TAG, "action down: " + xDown + ", " + yDown);
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
xMove = ev.getRawX();
yMove = ev.getRawY();
Log.v(TAG, "action move: " + xMove + ", " + yMove);
if (isScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
if (Math.abs(yMove - yDown) < 5 && Math.abs(xMove - xDown) > 20) {
isScroll = true;
} else {
return false;
}
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
isScroll = false;
}
return super.dispatchTouchEvent(ev);
}
}
The MainActivity layout is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
The layout for listview_item is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
Added all XML Layouts
listview_item_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:minHeight="100dp" >
<TextView
android:id="#+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/main_list_text"
android:textSize="48sp"
android:textStyle="bold" />
<EditText
android:id="#+id/et_input_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/add_contact_hint"
android:textColorHint="#color/main_list_text"
android:textColor="#color/main_list_text"
android:textSize="30sp"
android:textStyle="bold"
android:inputType="textCapCharacters"
android:background="#null"
android:textCursorDrawable="#null"
android:singleLine="true"
android:imeOptions="actionDone"
android:visibility="gone" />
</RelativeLayout>
listview_item_slide
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_menu_cancel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:focusableInTouchMode="true"
android:background="#color/gold"
android:gravity="center"
android:text="#string/cancel"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_delete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/green"
android:gravity="center"
android:text="#string/delete"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_block"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/royalblue"
android:gravity="center"
android:text="#string/block"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
</LinearLayout>
Please help me to listen to the onItemClickListener in the MainActivity's list. I am not able to figure out where I went wrong. Thanks in advance.
you have to put your "setOnItemClickListener" to your Adapter class insted of MainActivity.
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
ViewHolder holder;
View iView = convertView;
if (convertView == null) {
iView = inflater.inflate(R.layout.listview_item, parent, false);
holder = new ViewHolder();
holder.txt_name = (TextView) iView.findViewById(R.id.name);
Typeface custom_fontG = Typeface.createFromAsset(
context.getAssets(), "KozGoPr6N-Regular.otf");
holder.txt_name.setTypeface(custom_fontG);
holder.txt_desc = (TextView) iView.findViewById(R.id.detail);
holder.ivProfile = (ImageView) iView.findViewById(R.id.flag);
iView.setTag(holder);
} else {
holder = (ViewHolder) iView.getTag();
}
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// Capture position and set results to the TextViews
holder.txt_name.setText(resultp.get(OurTeam.TAG_NAME));
holder.txt_desc.setText(resultp.get(OurTeam.TAG_DETAIL));
imageLoader.displayImage(TAG_IMAGEURL + resultp.get((OurTeam.TAG_IMG)),
holder.ivProfile, options);
// Capture ListView item click
iView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
// your code
}
});
return iView;
}
At a time you can handle click event either in Adapter class of in Activity. in your case you are doing both.
And to manage
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
Write above on click event of what ever is main view in listview_item layout (Do not forget to pass addContact and inputName views to your CustomAdapter).
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
/* mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});*/
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
and Adapter Class was..
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// your code here for list item click listener...
}
})
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
add this below line in your listview_item parent layout only.
android:descendantFocusability="blocksDescendants"
actually when the list item contains a element which can get focus then list item click listener not work.
Add this to the parent of your Listview and parent of your listview_item and try again:
android:descendantFocusability="blocksDescendants"
Like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
and this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:descendantFocusability="blocksDescendants"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
If this does not work, call isFocusable() on your EditText and TextView
addContact.isFocusable(false);
inputName.isFocusable(false);
I am guessing you made a common error. Please check/try both changes.
1) add android:descendantFocusability="blocksDescendants" into the ListView UI ("#+id/lv_main").
Note: If this and 2nd suggestion does not work, then the Listview layout may need rework.
2) mainListView.setItemsCanFocus(false);
Note: The Listview may be confused with focusing on an item in the UI.
I think the suggested code by "Nirmal Shethwala" looks good. It has the if/else block for if (convertView == null).
EDIT: I noticed you inflated 3 xml layout files in getView(). You can only have one, and that is listview_item in your code. I know this is not well documented. I have tried this in the past. The reason is getView() method has to return only one view, and your code return convertView; like me.
Sorry I know this will take some modifications in your layout.
I'm using drag-sort-listview to sort rows of my ListView, and I have created a demo using this library, but it is not working. When I try to drag rows it is not working.
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] titles = new String[] { "Strawberry",
"Banana", "Orange", "Mixed" };
public static final String[] descriptions = new String[] {
"It is an aggregate accessory fruit",
"It is the largest herbaceous flowering plant", "Citrus Fruit",
"Mixed Fruits" };
public static final Integer[] images = { R.drawable.drag,
R.drawable.drag, R.drawable.drag, R.drawable.drag };
//ListView listView;
DragSortListView listView;
List<RowItem> rowItems;
CustomListViewAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
listView = (DragSortListView) findViewById(R.id.listview);
//listView = (ListView) findViewById(R.id.list);
final CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setDropListener(new DropListener() {
#Override
public void drop(int from, int to) {
if (from != to) {
//DragSortListView list = getListView();
RowItem item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
listView.moveCheckState(from, to);
//Log.d("DSLV", "Selected item is " + listView.getCheckedItemPosition());
}
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(), "Item "
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:dslv="http://schemas.android.com/apk/res/com.example.testingui"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.mobeta.android.dslv.DragSortListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="5dp"
dslv:collapsed_height="2dp"
dslv:drag_enabled="true"
dslv:drag_handle_id="#drawable/drag"
dslv:drag_scroll_start="0.33"
dslv:drag_start_mode="onMove"
dslv:float_alpha="0.6"
dslv:max_drag_scroll_speed="0.5"
dslv:remove_enabled="true"
dslv:remove_mode="flingRemove"
dslv:slide_shuffle_speed="0.3"
dslv:sort_enabled="true"
dslv:track_drag_sort="true"
dslv:use_default_controller="true" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descs);
holder.txtTitle = (TextView) convertView.findViewById(R.id.titles);
holder.imageView = (ImageView) convertView.findViewById(R.id.icons);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icons"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/titles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icons"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/descs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titles"
android:layout_toRightOf="#+id/icons"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
RowItem.java
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
Use Drag handle Id in DragSortListView tag in Xml
dslv:drag_handle_id="#id/drag_handle"
Make an id.xml file and put drag handle id as above to make it common and use the same id on dragable handle image view in your row item.
Hope it helps.
i have a custom adapter to place items inside listview. To customize it i have a listitem.xml file where i set the elements that compose a listitem.
They are as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="fitXY" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_marginLeft="23dp"
android:layout_marginTop="5dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:text=""/>
</RelativeLayout>
I have a classe Settings.java that uses the following layout settings.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayoutSettings"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#666666"
android:orientation="vertical" >
<ListView
android:id="#+id/listViewSettings"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
Class Settings.java is like this:
public class Settings extends Activity {
private SensorAdapter sensorAdapter;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.settings);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
R.layout.title_bar);
context = getApplicationContext();
sensorAdapter = new SensorAdapter();
ListView sensorListview = (ListView) findViewById(R.id.listViewSettings);
sensorListview.setAdapter(sensorAdapter);
sensorListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
sensorItem sensor = sensorAdapter.getCodeLearnChapter(arg2);
}
});
}
public class sensorItem {
String sensorName;
String sensorDescription;
Drawable sensorImage;
}
public List<sensorItem> getDataForListView() {
List<sensorItem> sensorsList = new ArrayList<sensorItem>();
sensorItem sensorGps = new sensorItem();
sensorGps.sensorName = "Location";
sensorGps.sensorDescription = "Collect location";
sensorGps.sensorImage = getResources().getDrawable(R.drawable.location);
sensorItem sensorPhoto = new sensorItem();
sensorPhoto.sensorName = "Photos";
sensorPhoto.sensorDescription = "Collect photos";
sensorPhoto.sensorImage = getResources().getDrawable(R.drawable.photos);
sensorItem sensorAmplitude = new sensorItem();
sensorAmplitude.sensorName = "Sound";
sensorAmplitude.sensorDescription = "Collect amplitude";
sensorAmplitude.sensorImage = getResources().getDrawable(
R.drawable.amplitude);
sensorItem sensorOrientation = new sensorItem();
sensorOrientation.sensorName = "Orientation";
sensorOrientation.sensorDescription = "Collect orientation";
sensorOrientation.sensorImage = getResources().getDrawable(
R.drawable.compass);
sensorItem sensorSms = new sensorItem();
sensorSms.sensorName = "Messages";
sensorSms.sensorDescription = "Collect messages";
sensorSms.sensorImage = getResources().getDrawable(R.drawable.sms);
sensorItem sensorBattery = new sensorItem();
sensorBattery.sensorName = "Battery";
sensorBattery.sensorDescription = "Collect battery";
sensorBattery.sensorImage = getResources().getDrawable(
R.drawable.battery);
sensorItem sensorCalendar = new sensorItem();
sensorCalendar.sensorName = "Calendar";
sensorCalendar.sensorDescription = "Collect calendar";
sensorCalendar.sensorImage = getResources().getDrawable(
R.drawable.calendar);
sensorItem sensorAccelerometer = new sensorItem();
sensorAccelerometer.sensorName = "Accelerometer";
sensorAccelerometer.sensorDescription = "Collect accelerometer";
sensorAccelerometer.sensorImage = getResources().getDrawable(
R.drawable.accelerometer);
sensorItem sensorLight = new sensorItem();
sensorLight.sensorName = "Light";
sensorLight.sensorDescription = "Collect luminosity";
sensorLight.sensorImage = getResources().getDrawable(R.drawable.light);
sensorItem sensorContacts = new sensorItem();
sensorContacts.sensorName = "Contacts";
sensorContacts.sensorDescription = "Collect contact";
sensorContacts.sensorImage = getResources().getDrawable(
R.drawable.contacts);
sensorsList.add(sensorGps);
sensorsList.add(sensorPhoto);
sensorsList.add(sensorAmplitude);
sensorsList.add(sensorOrientation);
sensorsList.add(sensorSms);
sensorsList.add(sensorBattery);
sensorsList.add(sensorCalendar);
sensorsList.add(sensorAccelerometer);
sensorsList.add(sensorLight);
sensorsList.add(sensorContacts);
return sensorsList;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class SensorAdapter extends BaseAdapter {
List<sensorItem> sensorList = getDataForListView();
private ToggleButton locationToggle, photosToggle, soundToggle,
orientationToggle, messagesToggle, batteryToggle, calendarToggle,
accelerometerToggle, lightToggle, contactsToggle;
#Override
public int getCount() {
return sensorList.size();
}
#Override
public sensorItem getItem(int arg0) {
return sensorList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
LayoutInflater inflater = (LayoutInflater) Settings.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arg1 = inflater.inflate(R.layout.listitem, arg2, false);
}
TextView sensorDescription = (TextView) arg1
.findViewById(R.id.textView2);
ImageView sensorImage = (ImageView) arg1
.findViewById(R.id.imageView1);
locationToggle = (ToggleButton) arg1.findViewById(R.id.toggleButton1);
locationToggle.setChecked(true);
locationToggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "CARREGOU", Toast.LENGTH_LONG).show();
}
});
sensorItem sensor = sensorList.get(arg0);
sensorDescription.setText(sensor.sensorDescription);
sensorImage.setBackground(sensor.sensorImage);
return arg1;
}
public sensorItem getCodeLearnChapter(int position) {
return sensorList.get(position);
}
}
}
The problem with this is that now every element in the listitem.xml has exactly the same ID. So every toggle button has the same ID. I dont know which togglebutton the user pressed.
How can i know which togglebutton the user pressed? Do i have to change the way i populate the listview?
Thx very much.
EDIT:
This is how it looks right now and the problem is that the ArrayList that i have to check whether a toggleButton in a row was clicked or not it seems to all set every element to true when i click in another row.
Example:
I have
true | true | true
i click in the third button and i get
true | false | true
but if i click in the first button for example i get
false | true | true
when i should get instead
false | false | true.
Here is the code adapter so someone can take a look.
public class SensorAdapter extends BaseAdapter {
List<sensorItem> sensorList = getDataForListView();
private ToggleButton settingsToggle;
private ArrayList<Boolean> checkedSensors;
#Override
public int getCount() {
return sensorList.size();
}
#Override
public sensorItem getItem(int arg0) {
return sensorList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
LayoutInflater inflater = (LayoutInflater) Settings.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arg1 = inflater.inflate(R.layout.listitem, arg2, false);
}
// TextView sensorName = (TextView)
// arg1.findViewById(R.id.textView1);
TextView sensorDescription = (TextView) arg1
.findViewById(R.id.textView2);
ImageView sensorImage = (ImageView) arg1
.findViewById(R.id.imageView1);
settingsToggle = (ToggleButton) arg1.findViewById(R.id.toggleButton1);
settingsToggle.setChecked(true);
checkedSensors = new ArrayList<Boolean>();
int i = 0;
while(i < 10){
checkedSensors.add(i,true);
i++;
}
settingsToggle.setTag(new Long(getItemId(arg0)));
settingsToggle.setOnClickListener(mOnToggleListener);
/*settingsToggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if(isChecked){
Toast.makeText(Settings.this, "on "+buttonView.getId(), Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Settings.this, "off "+buttonView.getId(), Toast.LENGTH_LONG).show();
}
}
});*/
sensorItem sensor = sensorList.get(arg0);
// sensorName.setText(sensor.sensorName);
sensorDescription.setText(sensor.sensorDescription);
sensorImage.setBackground(sensor.sensorImage);
return arg1;
}
public OnClickListener mOnToggleListener = new OnClickListener(){
#Override
public void onClick(View v){
long id = (Long) v.getTag();
if (checkedSensors.get((int)id)){
//enableSensor(id);
checkedSensors.add((int)id, false);
}else{
//disableSensor(id);
checkedSensors.add((int)id, true);
}
for(int i = 0; i<10 ; i++){
System.out.println(i + " " + checkedSensors.get(i));
}
}
};
public sensorItem getSensor(int position) {
return sensorList.get(position);
}
}
}
You can set the index in a tag on the toggle button so the onClick event knows which index got clicked.
Before you set the onClick listener add this line:
locationToggle.setTag(arg0);
And inside your onClick listener:
int position = (Integer)v.getTag();
you can create your listener ouside of getView like this:
public OnClickListener mOnToggleListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get id of your item from view
//v is locationToggleView
long id = (Long)v.getTag();
}
};
and make these change in getView method:
//set id as view tag when create or reuse view
//arg0 is position
locationToggle.setTag(new Long(getItemId(arg0)));
locationToggle.setOnClickListener(mOnToggleListener);
by this way you can get view related item id when locationToggle is clicked.