Malfunctioning view inflater - java

Building a custom view that inflate an xml.
everything works fine except that when a the custom view is selected, all other views inflating the custom view is also selected. Don't really know what the problem is. Snippet is below.
public class DJV_DropDown extends LinearLayout {
private UI_Model ui_models;
private String[] items;
private ArrayAdapter itemAdapter;
private UI_Object ui_object;
public void setUi_object(UI_Object ui_object) {
this.ui_object = ui_object;
}
public UI_Object getUi_object() {
return ui_object;
}
public final void setViewAttribute(UI_Object ui_object) {
ui_models = new AttributeDefiner().AttributeReader(ui_object.getUi_spec(), ui_object.getStepData(), ui_object.getName());
setUi_object(ui_object);
}
public final void setDefaultAttribute() {
if (getUi_object().getUi_spec().getParameterMode().equalsIgnoreCase("entity")) {
getUi_object().setParameterMode(true);
String entityString = getUi_object().getUi_singleField().getEntitySource();
UI_Entity entity = new UI_Entity(entityString);
ArrayList<Entity> entityArrayList = Entity.getAllEntityByName(getUi_object().getContext(), entity.getName());
getUi_object().setEntityObject(entityArrayList);
String keep = "";
for (int entityIndex = 0; entityIndex < entityArrayList.size(); entityIndex++) {
try {
JSONObject jsonObject = new JSONObject(entityArrayList.get(entityIndex).getValue());
keep = jsonObject.optString("::DisplayName::") + ",";
} catch (JSONException e) {
e.printStackTrace();
}
}
if (!keep.trim().isEmpty()) {
items = keep.substring(0, keep.length() - 1).split(",");
textView.setText(items[0]);
} else {
items = new String[0];
}
} else {
items = getUi_object().getUi_singleField().getSourceContent().split(",");
textView.setText(items[0]);
}
}
public final UI_Model getCustomViewAttribute() {
return ui_models;
}
public DJV_DropDown(Context context) {
super(context);
}
public DJV_DropDown(Context context, UI_Object ui_object) {
super(context);
initialise();
setViewAttribute(ui_object);
setDefaultAttribute();
}
TextView textView;
LinearLayout rootLinearLayout;
static int id = 0;
private void initialise() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.djv_dropdown, this);
textView = (TextView) findViewById(R.id.text);
rootLinearLayout = (LinearLayout) findViewById(R.id.root);
rootLinearLayout.setId(id);
id++; //changed the id because i initially thought the problem was a a result of more than one custom view sharing the same id
}
}
xml that is been inflated:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:background="#drawable/drop_down"
android:padding="12dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:orientation="vertical"
android:layout_margin="5dp"
android:gravity="center_vertical"
android:textSize="16dp"
android:text="uyyu"
android:id="#+id/text"
android:textColor="#000"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TextView>
<ImageView
android:src="#drawable/spinner_down"
android:background="#android:color/transparent"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>

Related

list view inside list View in android

I am Using a list view inside a listview and both listview share same list item.
It is working fine but if height of the item increases in inside list view it doesn't wrap the content and put a scrollview which is not as per requirement.
Please see the codes below
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<ListView
android:id="#+id/list_comments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:divider="#android:color/transparent"
android:dividerHeight="5dp" />
</RelativeLayout>
comments_for_topic.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:background="#fafafa">
<RelativeLayout
android:id="#+id/commentsRelLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:paddingLeft="7dp"
android:background="#d5d5d5"
android:orientation="vertical">
<TextView
android:id="#+id/UserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="User name"/>
<TextView
android:id="#+id/Comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/UserName"
android:textSize="12sp"
android:padding="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/showRep"
android:text="Comment test 1"/>
<TextView
android:id="#+id/showRep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2Replies"
android:layout_toLeftOf="#+id/Reply"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:textColor="#android:color/holo_blue_dark"
android:layout_below="#+id/UserName"/>
<TextView
android:id="#+id/Reply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reply"
android:textSize="12dp"
android:textColor="#android:color/holo_blue_dark"
android:layout_below="#+id/UserName"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<ListView
android:id="#+id/list_commentsLevel1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/commentsRelLayout"
android:layout_alignLeft="#+id/commentsRelLayout"
android:layout_marginLeft="34dp"
android:background="#d5d5d5"
android:layout_marginTop="2dp"
android:scrollbars="none"
android:divider="#android:color/white"
android:dividerHeight="1dp"
></ListView>
<TextView
android:id="#+id/showmorebtn"
android:layout_alignParentBottom="true"
android:layout_marginBottom="4dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_more"
android:layout_below="#+id/list_commentsLevel1"
android:layout_alignLeft="#+id/list_commentsLevel1"
android:textColor="#android:color/holo_blue_dark"
/>
</RelativeLayout>
AdapterComments.java
public class AdapterComments extends BaseAdapter {
private Activity activity;
private ArrayList<CommentListModel> itemsArrayList = new ArrayList<CommentListModel>();
private ArrayList<CommentListModel> Comments = new ArrayList<CommentListModel>();
CommentListModel tempValues=null;
private static LayoutInflater inflater=null;
ArrayList<AdapterComments> adapterCommentsArrayList = new ArrayList<AdapterComments>();
ViewHolder holder = new ViewHolder();
ViewHolder viewHolder;
ArrayList<String> list =new ArrayList<String>();
private int currentID=0;
boolean isChild =false;
FragmentDiscussinTopic fragmentDiscussinTopic;
public AdapterComments() {
}
public AdapterComments(Activity context, FragmentDiscussinTopic fragmentDiscussinTopic, ArrayList<CommentListModel> itemsArrayList) {
this.activity = context;
this.itemsArrayList = itemsArrayList;
this.isChild = false;
this.fragmentDiscussinTopic = fragmentDiscussinTopic;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0 ; i<itemsArrayList.size();i++){
AdapterComments adapterComments1 = new AdapterComments();
adapterCommentsArrayList.add(adapterComments1);
}
}
public AdapterComments(Activity context, ArrayList<CommentListModel> itemsArrayList) {
this.activity = context;
this.itemsArrayList = itemsArrayList;
this.isChild = true;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0 ; i<itemsArrayList.size();i++){
AdapterComments adapterComments1 = new AdapterComments();
adapterCommentsArrayList.add(adapterComments1);
}
}
#Override
public int getCount() {
if(itemsArrayList.size()<=0)
return 1;
return itemsArrayList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return position;
}
public static class ViewHolder{
public TextView UserName;
public TextView Comment;
public TextView showRep;
public TextView Reply;
public TextView showmorebtn;
public ListView list_commentsLevel1;
}
#Override
public View getView(final int position, View rowView, ViewGroup parent) {
View v1 = rowView;
if(rowView==null){
v1 = inflater.inflate(R.layout.comments_for_topic,null);
viewHolder =new ViewHolder();
viewHolder.UserName=(TextView)v1.findViewById(R.id.UserName);
viewHolder.Comment=(TextView)v1.findViewById(R.id.Comment);
viewHolder.showRep=(TextView)v1.findViewById(R.id.showRep);
viewHolder.showmorebtn=(TextView)v1.findViewById(R.id.showmorebtn);
viewHolder.Reply=(TextView)v1.findViewById(R.id.Reply);
viewHolder.list_commentsLevel1=(ListView)v1.findViewById(R.id.list_commentsLevel1);
v1.setTag( viewHolder );
}
else
viewHolder=(ViewHolder)v1.getTag();
if(itemsArrayList.size()<=0)
{
Log.e("data", " no data found");
}
else {
tempValues = itemsArrayList.get(position);
if (tempValues.isVisible()){
viewHolder.list_commentsLevel1.setAdapter(adapterCommentsArrayList.get(position));
viewHolder.list_commentsLevel1.setVisibility(View.VISIBLE);
ObjectAnimator anim = ObjectAnimator.ofFloat(viewHolder.list_commentsLevel1, "alpha", 0f, 1f);
anim.setDuration(1000);
anim.start();
setListViewHeightBasedOnChildren(viewHolder.list_commentsLevel1);
// scrollMyListViewToBottom();
}else {
Animation animation = new TranslateAnimation(0,0,0,1000);
animation.setDuration(1000);
viewHolder.list_commentsLevel1.startAnimation(animation);
viewHolder.list_commentsLevel1.setVisibility(View.GONE);
}
viewHolder.UserName.setText(tempValues.getUserName());
viewHolder.Comment.setText(tempValues.getComment());
int subcmntcount = tempValues.getSubCommentCount();
if (subcmntcount>=1){
viewHolder.showRep.setVisibility(View.VISIBLE);
if (subcmntcount==1){
String repText=new String("1Reply");
SpannableString content = new SpannableString(repText);
content.setSpan(new UnderlineSpan(), 0, repText.length(), 0);
viewHolder.showRep.setText(content);
}else {
String repText=new String(subcmntcount+"Replies");
SpannableString content = new SpannableString(repText);
content.setSpan(new UnderlineSpan(), 0, repText.length(), 0);
viewHolder.showRep.setText(content);
}
viewHolder.showmorebtn.setVisibility(View.GONE);
}else {
viewHolder.showRep.setVisibility(View.GONE);
viewHolder.list_commentsLevel1.setVisibility(View.GONE);
viewHolder.showmorebtn.setVisibility(View.GONE);
}
if (tempValues.isChild()){
viewHolder.Reply.setVisibility(View.GONE);
viewHolder.showRep.setVisibility(View.GONE);
}else {
viewHolder.Reply.setVisibility(View.VISIBLE);
String repText=new String("Reply");
SpannableString content = new SpannableString(repText);
content.setSpan(new UnderlineSpan(), 0, repText.length(), 0);
viewHolder.Reply.setText(content);
}
v1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0;i<itemsArrayList.size();i++){
CommentListModel commentListModel = ( CommentListModel ) itemsArrayList.get( i );
if (i==position){
isChild =true;
if (commentListModel.getSubCommentCount()>0){
commentListModel.setVisible(true);
itemsArrayList.remove(i);
itemsArrayList.add(i,commentListModel);
new getDiscussionForumComments(commentListModel.getDiscussionCommentID(),position).execute();
}
}else {
commentListModel.setVisible(false);
itemsArrayList.remove(i);
itemsArrayList.add(i,commentListModel);
}
}
}
});
viewHolder.Reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Configuration.currentDiscussID = itemsArrayList.get(position).getDiscussionCommentID();
fragmentDiscussinTopic.requestEditPop();
}
});
}
return v1;
}
public static void setListViewHeightBasedOnChildren(ListView listView)
{
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight=0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++)
{
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + ((listView.getDividerHeight()) * (listAdapter.getCount()));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
please see the highlighted area of image listview height is not proper to wrap the content
any help would be appericiated
The problem is you can't get the scroll of both listview at a time. if you what you both at the same time. you need to create a custom list view try something like this instead of your list view (inside list).
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
Their are some points you need to fix.
Give a proper height to your ListView so that it can scroll within that boundry, wrap_content is never recommended for ListView. So better to put some height to your ListView.
Listview inside a ListView will not give the user experience good. Try a work around or better to Use RecyclerView. RecyclerView is better in performance in case of nested list.
Hope it will help :)

How to remove item from ListView and sharedpreferences android studio?

i want to be able to do this to the code i have already I am new to programing please help.
- Add an icon the user can click (per item) to remove it
- When clicked that item on the list should be removed
-The item should be removed from storage as well (so it doesn't appear next time they load up the app)
here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String Log_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(
this,
listManager.getList()
);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(
Context context,
List<ToDoItem> items
) {
super(context, -1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox CheckBox = (CheckBox) convertView.findViewById(R.id.CheckBox);
textView.setText(items.get(position).getDescription());
CheckBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
todolistmanager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if(json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit = savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
todoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return getDescription();
}
}
Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/hintTxtItem"
/>
<Button
android:id="#+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/lblBtnAdd"
android:layout_toRightOf="#id/txtItem"
/>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:text="#string/txtEmpty"
android:gravity="center_horizontal"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:choiceMode="multipleChoice" >
</ListView>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
to_do_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<CheckBox
android:id="#+id/CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<ListView
android:layout_weight="20"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
Step1: Create activity_main.xml
<?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:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/txtItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text" />
<Button
android:id="#+id/btnAdd"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txtItem"
android:text="Add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="#+id/lvTodo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice" />
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:text="No data"
android:visibility="invisible" />
</RelativeLayout>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
Step2: Create to todo_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="10dp"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="#+id/tvTodoName"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Learn Android"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cbChooseTodo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Step3: Define Object Todo
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description, boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isComplete() {
return isComplete;
}
public void setComplete(boolean complete) {
isComplete = complete;
}
}
Step4: Create TodoItemAdapter class
public class TodoItemAdapter extends ArrayAdapter<ToDoItem> {
private ArrayList<ToDoItem> arrayListTodo;
private LayoutInflater layoutInflater;
public TodoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) {
super(context, resource, objects);
this.arrayListTodo = objects;
this.layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.todo_item, parent,false);
holder.tvTodoName = (TextView)convertView.findViewById(R.id.tvTodoName);
holder.cbTodoChoose = (CheckBox)convertView.findViewById(R.id.cbChooseTodo);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
final ToDoItem toDoItem = arrayListTodo.get(position);
holder.tvTodoName.setText(toDoItem.getDescription());
holder.cbTodoChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toDoItem.setComplete(isChecked);
}
});
holder.cbTodoChoose.setChecked(toDoItem.isComplete());
return convertView;
}
public static class ViewHolder{
public TextView tvTodoName;
public CheckBox cbTodoChoose;
}
}
Step5: Process on the MainActivity class
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ListView lvTodoItem;
private ArrayList<ToDoItem> toDoItems;
private TodoItemAdapter todoItemAdapter;
private Button btnDel;
private Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData(){
toDoItems = new ArrayList<>();
todoItemAdapter = new TodoItemAdapter(MainActivity.this, R.layout.todo_item, toDoItems);
lvTodoItem = (ListView)findViewById(R.id.lvTodo);
lvTodoItem.setAdapter(todoItemAdapter);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnDel = (Button)findViewById(R.id.btnDel);
btnAdd.setOnClickListener(this);
btnDel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnAdd:
addTodoItem();
break;
case R.id.btnDel:
deleteTodoItem();
break;
}
}
private void addTodoItem() {
}
private void deleteTodoItem() {
for (int i= toDoItems.size()-1; i>=0 ; i--){
ToDoItem toDoItem = toDoItems.get(i);
if (toDoItem.isComplete()){
toDoItems.remove(i);
}
}
todoItemAdapter.notifyDataSetChanged();
}
}
It is working fine. Thanks.

Android: Get values of listview with multiple row layout

I have a listview with multiple row layouts (radio group, edit text, text view), with multiple choice mode. I want to retrieve it's selected data (user-selected or typed data) on a submit button.
This is the code from my main file:
public class GraduatingSurvey extends Fragment {
private static final String LOGTAG = "log" ;
public String stdcode = "024-15-16079";
Button submit;
RadioGroup radioGroup;
RadioButton radioButton;
EditText comment;
ArrayList<GraduatingSurveyModel> graduatingModelList;
ListView listView;
View view;
public GraduatingSurvey() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_graduating_survey, container, false);
submit = (Button) view.findViewById(R.id.btn_graduate_submit);
listView = (ListView) view.findViewById(R.id.graduate_list);
graduatingModelList = new ArrayList<GraduatingSurveyModel>();
//handle submit form Event.
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int child=listView.getAdapter().getCount();
Log.i("radio", "child: " + child);
SparseBooleanArray checked = listView.getCheckedItemPositions(); //Is returning empty
Log.i("radio", "sparseArray: " + checked);
for(int i=0;i<child;i++) {
int type = listView.getAdapter().getItemViewType(i);
Log.i("radio", "type: " + type);
if(type == 2){
// Want to retrieve data here
}
if(type == 0)
{
}
if(type == 1){
}
}
}
});
NetAsync(view);
return view;
}
This is the adapter:
public class GraduatingSurveyAdapter extends ArrayAdapter<GraduatingSurveyModel> {
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
private static final int TYPE_ITEM3 = 2;
int type;
ArrayList<GraduatingSurveyModel> ArrayListSurvey;
int Resource;
Context context;
LayoutInflater vi;
public GraduatingSurveyAdapter(Context context, int resource, ArrayList<GraduatingSurveyModel> objects) {
super(context, resource, objects);
ArrayListSurvey = objects;
Resource = resource;
this.context = context;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (position == 14){
type = TYPE_ITEM1;
} else if (position == 23 || position == 24 || position == 25){
type = TYPE_ITEM2;
}
else
{
type= TYPE_ITEM3 ;
}
return type;
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
//first Item or row is being created hence ConvertView is NULL
if(convertView == null){
if (type == TYPE_ITEM2) {
convertView = vi.inflate(R.layout.graduates_survey_comment,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
holder.tv_comment = (TextView) convertView.findViewById(R.id.graduate_comment);
}
else if (type == TYPE_ITEM1) {
convertView = vi.inflate(R.layout.graduates_survey_subheader,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
}
else {
//infalte layout of normaltype
//Inflating items only once
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
holder.tv_comment = (TextView) convertView.findViewById(R.id.graduate_comment);
holder.rg = (RadioGroup) convertView.findViewById(R.id.graduate_radioGroup);
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
/* RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
Log.i("radio", "onCheckedChanged: " + radioButton + " " + checkedId);
notifyDataSetChanged();*/
Integer pos = (Integer) group.getTag();
GraduatingSurveyModel element = ArrayListSurvey.get(pos);
switch (checkedId) {
case R.id.graduate_sAgree:
element.current = GraduatingSurveyModel.ANSWER_ONE_SELECTED;
break;
case R.id.graduate_agree:
element.current = GraduatingSurveyModel.ANSWER_TWO_SELECTED;
break;
case R.id.graduate_uncertain:
element.current = GraduatingSurveyModel.ANSWER_THREE_SELECTED;
break;
case R.id.graduate_disagree:
element.current = GraduatingSurveyModel.ANSWER_FOUR_SELECTED;
break;
case R.id.graduate_sDisagree:
element.current = GraduatingSurveyModel.ANSWER_FIVE_SELECTED;
break;
default:
element.current = GraduatingSurveyModel.NONE; // Something was
}
}
});
}
convertView.setTag(holder);
}else{
//reuse code. (Inflate items only once then reuse them.)
holder = (ViewHolder) convertView.getTag();
}
// get info from ArrayList(that came through JSON), and set it in the View.
if (type == TYPE_ITEM1) {
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
}
else if (type == TYPE_ITEM2) {
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
}
else{
holder.rg.setTag(new Integer(position));
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
if(ArrayListSurvey.get(position).current != GraduatingSurveyModel.NONE){
RadioButton r = (RadioButton) holder.rg.getChildAt(ArrayListSurvey.get(position).current);
r.setChecked(true);
}else{
holder.rg.clearCheck();
}
}
return convertView;
}
static class ViewHolder{
private TextView tv_question;
private TextView tv_comment;
private LinearLayout lv_choices;
private RadioGroup rg;
}
}
This is my model:
public class GraduatingSurveyModel {
public String question;
public String comment;
public String choices;
public String subHeading;
public int current = NONE; // hold the answer picked by the user, initial is NONE(see below)
public static final int NONE = 1000; // No answer selected
public static final int ANSWER_ONE_SELECTED = 0; // first answer selected
public static final int ANSWER_TWO_SELECTED = 1; // second answer selected
public static final int ANSWER_THREE_SELECTED = 2; // third answer selected
public static final int ANSWER_FOUR_SELECTED = 3; // forth answer selected
public static final int ANSWER_FIVE_SELECTED = 4; // forth answer selected
public GraduatingSurveyModel() {
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getChoices() {
return choices;
}
public void setChoices(String choices) {
this.choices = choices;
}
public String getSubHeading() {
return subHeading;
}
public void setSubHeading(String subHeading) {
this.subHeading = subHeading;
}
}
And this is the XML layout of the main fragment:
<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:padding="16dp"
android:background="#color/dialog_background"
android:orientation="vertical"
tools:context="iulms.iunc.edu.pk.iqraiulms.GraduatingSurvey"
android:id="#+id/main_layout">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/graduate_list"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/btn_graduate_submit"
/>
<Button
android:id="#+id/btn_graduate_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
These are the layouts for the different types of rows in listview
Row type 1:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="13dp" />
<!-- <EditText
android:id="#+id/graduate_comment"
style="#style/GraduateTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/textbox"
android:ems="10"
android:hint="Comment"
android:inputType="textMultiLine"
android:lines="3" />-->
<LinearLayout
android:id="#+id/graduate_choices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="#+id/graduate_radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/graduate_sAgree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Strongly Agree" />
<RadioButton
android:id="#+id/graduate_agree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Agree" />
<RadioButton
android:id="#+id/graduate_uncertain"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Uncertain"
/>
<RadioButton
android:id="#+id/graduate_disagree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Disagree" />
<RadioButton
android:id="#+id/graduate_sDisagree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Strongly Disagree" />
</RadioGroup>
</LinearLayout>
</LinearLayout>
Row type 2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="13dp" />
<EditText
android:id="#+id/graduate_comment"
style="#style/GraduateTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/textbox"
android:ems="10"
android:hint="Comment"
android:inputType="textMultiLine"
android:lines="3" />
</LinearLayout>
Row type 3:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="15dp"
android:textColor="#color/primary_dark"/>
</LinearLayout>
How can I retrieve the data submitted in the main fragment?
Thanks
For this You can create a custom class with row values like,
Arraylist<CustomClass> mnewList = new ArrayList();
Class CustomClass
{
private String edValues,
private int rowId,
}
etc.
Then Implement on change listener for radio button in that add/remove current selected items to that custom list.

Display of ListView include in an other ListView

I have a problem and I can't solve it. I would like to create poll application. I Create 2 classes :
- Poll which contain user's name, the question and an ArrayList of Choice
- Choice contain the choice and its id.
I would like to display on the home page a list of questions (ArrayList) with the differents choices. I managed to display this list but I have a problem with ArrayList of the class Poll because only the first item is display but I want to display all the list of choice.
POLL CLASS
public class Poll{
String question;
String forename;
ArrayList<Choice> list_choices;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public ArrayList<Choice> getListChoice() {
return list_choices;
}
public void setListChoice(ArrayList<Choice> list_choices) {
this.list_choices = list_choices;
}
}
CHOICE CLASS
public class Choice {
int id;
String choice;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChoice() {
return choice;
}
public void setChoice(String choice) {
this.choice = choice;
}
}
Adapter for Poll
public class CustomListAdapter extends BaseAdapter{
ArrayList<Poll> listPolls;
LayoutInflater layoutInflater;
Context context;
public CustomListAdapter(Context context,ArrayList<Poll> listPolls) {
this.listPolls = listPolls;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listPolls.size();
}
#Override
public Object getItem(int arg0) {
return listPolls.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ViewHolder holder;
if (arg1==null)
{
arg1= layoutInflater.inflate(R.layout.row_list, null);
holder = new ViewHolder();
holder.ForenameView = (TextView) arg1.findViewById(R.id.forename);
holder.QuestionView = (TextView) arg1.findViewById(R.id.question);
holder.ChoiceView = (ListView) arg1.findViewById(R.id.choice);
//tagguer notre objet pour pouvoir le récupérer à la prochaine mise à jour graphique.
arg1.setTag(holder);
}
else
{
holder = (ViewHolder) arg1.getTag();
}
holder.ForenameView.setText(listPolls.get(arg0).getForename());
holder.QuestionView.setText(listPolls.get(arg0).getQuestion());
holder.ChoiceView.setAdapter(new CustomListChoiceAdapter(context, listPolls.get(arg0).getListChoice()));
return arg1;
}
static class ViewHolder {
TextView ForenameView;
TextView QuestionView;
ListView ChoiceView;
}
}
Adapter for choice
public class CustomListChoiceAdapter extends BaseAdapter {
ArrayList<Choice> listChoices;
LayoutInflater layoutInflater;
public CustomListChoiceAdapter(Context context,ArrayList<Choice> listChoices) {
this.listChoices = listChoices;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listChoices.size();
}
#Override
public Object getItem(int arg0) {
return listChoices.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ViewHolder holder;
if (arg1==null)
{
arg1= layoutInflater.inflate(R.layout.row_list_choice, null);
holder = new ViewHolder();
holder.ChoiceView = (TextView) arg1.findViewById(R.id.choice_text);
//holder.IdView = (TextView) arg1.findViewById(R.id.question);
//tagguer notre objet pour pouvoir le récupérer à la prochaine mise à jour graphique.
arg1.setTag(holder);
}
else
{
holder = (ViewHolder) arg1.getTag();
}
holder.ChoiceView.setText(listChoices.get(arg0).getChoice());
notifyDataSetChanged();
//holder.IdView.setText(listChoices.get(arg0).getId());
return arg1;
}
static class ViewHolder {
TextView ChoiceView;
//TextView IdView;
}
}
XML Home page
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:id="#+id/LinearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#drawable/customborder"
>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#000000"
>
</ListView>
</RelativeLayout>
</LinearLayout>
XML Poll List
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/forename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Medium Text"
android:textColor="#color/blue"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="TextView" />
<ListView
android:id="#+id/choice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#000000"
>
</ListView>
</LinearLayout>
</LinearLayout>
XML Choice List
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/choice_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Medium Text"
android:textColor="#color/pink"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</LinearLayout>
Activity which display ArrayList
public class debug extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debugg);
//Récuperation de ListView crée
lv = (ListView) findViewById(R.id.listView1);
ArrayList<Choice> list_choice = new ArrayList<Choice>();
Choice choix = new Choice();
choix.setChoice("choix 1");
list_choice.add(choix);
choix = new Choice();
choix.setChoice("choix 2");
list_choice.add(choix);
ArrayList<Poll> resultats = new ArrayList<Poll>();
Poll newsData = new Poll();
newsData.setListChoice(list_choice);
newsData.setForename("Paul");
newsData.setQuestion("Question 1");
resultats.add(newsData);
newsData = new Poll();
newsData.setListChoice(list_choice);
newsData.setForename("Laetitia");
newsData.setQuestion("Question 2");
resultats.add(newsData);
lv.setAdapter(new CustomListAdapter(this, resultats));
}
}
Man, the one and origin solution is:
Set your parent ListView item WRAP_CONTENT height. Next, set fixed height of your included ListView item. Then in getView() method set the height of your included ListView the height equals to parent_array_list.size() * child_list_view_item_height. It might be help you.
Code example:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (listPolls.size() * TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, child_list_view_item_height, displayMetrics)));
holder.ChoiceView.setLayoutParams(params);

UnsupportedOperationException in creating custom ListView in Android

i wanted to have a custom listView so I did this:
Created an Activity:
public class PRS_MainList_Act extends ListActivity {
MainListAdapter mladp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prs__main_list_);
ArrayList<MainMenuItem> menuItems = new ArrayList<MainMenuItem>();
menuItems.add(new MainMenuItem(getResources().getString(R.string.main_list_connectivity), getResources().getString(R.string.main_list_connectivityDesc)));
this.mladp = new MainListAdapter(this, R.layout.man_list_item, R.id.textView1, menuItems);
setListAdapter(mladp);
}
}
Create a class for menu items:
public class MainMenuItem {
private String itemText;
private String itemDescription;
private String itemIMG;
private int itemWeight;
private String itemAssociatedActivity;
public MainMenuItem(String itemText, String itemDescription) {
this.itemText = itemText;
this.itemDescription = itemDescription;
}
public String getItemText() {
return itemText;
}
public void setItemText(String itemText) {
this.itemText = itemText;
}
public String getItemIMG() {
return itemIMG;
}
public void setItemIMG(String itemIMG) {
this.itemIMG = itemIMG;
}
public int getItemWeight() {
return itemWeight;
}
public void setItemWeight(int itemWeight) {
this.itemWeight = itemWeight;
}
public String getItemAssociatedActivity() {
return itemAssociatedActivity;
}
public void setItemAssociatedActivity(String itemAssociatedActivity) {
this.itemAssociatedActivity = itemAssociatedActivity;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
}
Custom array adapter:
public class MainListAdapter extends ArrayAdapter<MainMenuItem> {
ArrayList<MainMenuItem> menuItems;
public MainListAdapter(Context context, int resource,
int textViewResourceId, ArrayList<MainMenuItem> menuItems) {
super(context, resource, textViewResourceId, menuItems);
this.menuItems = menuItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.man_list_item, parent);
}
MainMenuItem it = menuItems.get(position);
if (it != null) {
TextView titleTV = (TextView) view.findViewById(R.id.textView1);
TextView descriptionTV = (TextView) view.findViewById(R.id.textView2);
ImageView iconIV = (ImageView)view.findViewById(R.id.imageView1);
if (titleTV != null) {
titleTV.setText(it.getItemText());
}
if(descriptionTV != null){
descriptionTV.setText(it.getItemDescription());
}
if(iconIV != null){
if(it.getItemText().equals(getContext().getResources().getString(R.string.main_list_connectivity)))
iconIV.setImageResource(R.drawable.network_connections);
}
}
return view;
}
}
and here are my activity layout and item layout:
<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"
tools:context=".PRS_MainList_Act" >
<ListView android:id="#android:id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
Item Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
I got this error saying: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
Thanks in advance for your help.
You can't use this version of the inflate method:
view = vi.inflate(R.layout.man_list_item, parent);
because this will add the inflated View to the parent, which isn't allowed in a ListView. Instead use this version:
view = vi.inflate(R.layout.man_list_item, parent, false);
which will inflate the view but will not add it to the parent. This version is important because it will provide the proper LayoutParams for your inflated view.

Categories

Resources