Can't get TextView's value in LinearLayout - java

In ListView I have list of LinearLayouts(LL). Each LinearLayout(LL) have 2 LinearLayouts(LL1 and LL2). And the second LinearLayout(LL2) haveTextView I want get TextView's value in LinearLayout via OnButtonCliclListener
Here is code of my Adapter:
int resource;
TextView tt;
LinearLayout LL;
LinearLayout LL2;
LinearLayout LL1;
TextView currentText;
public Vk_row_adapter(Context _context, List<? extends Map<String, ?>> data, int _resource, String[] from, int[] to) {
super(_context, data, _resource, from, to);
this.results = data;
context = _context;
resource = _resource;
}
#Override
public View getView(int position, View view, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(resource, parent, false);
LL= (LinearLayout)v.getRootView();
LL1 = (LinearLayout)LL.getChildAt(0);
LL1.setOnClickListener(onButtonClickListener);
LL2 = (LinearLayout)LL.getChildAt(1);
LL2.setOnClickListener(onButtonClickListener);
currentText = (TextView)LL2.getChildAt(0);
tt = (TextView) v.findViewById(R.id.vk_name);
tt.setText((CharSequence) results.get(position).get(ATTRIBUTE_NAME_TEXT_NAME));
//other elements
return v;
}
private View.OnClickListener onButtonClickListener = new View.OnClickListener()
{
Toast.makeText(context, currentText.getText(), Toast.LENGTH_LONG).show();
};
It gives me only the last TextView's text. I know why. But I don't know to make it correctly. Any ideas?

Really...
You have one variable storing the current text for LL2 and non storing it for LL1, yet you are using the same onclicklistener for both...
There are several solutions here, lets go with the make a second variable and onclicklistener for simplicity

Here is my sollution
public class Vk_row_adapter extends SimpleAdapter {
final String ATTRIBUTE_NAME_TEXT_NAME = "text_name";
final String ATTRIBUTE_NAME_TEXT_RAITING = "text_place";
final String ATTRIBUTE_NAME_IMAGE = "image";
private List<? extends Map<String, ?>> results;
Context context;
String Name=null;
int resource;
TextView tt;
LinearLayout LL;
LinearLayout LL2;
LinearLayout LL1;
TextView currentText;
public Vk_row_adapter(Context _context, List<? extends Map<String, ?>> data, int _resource, String[] from, int[] to) {
super(_context, data, _resource, from, to);
this.results = data;
context = _context;
resource = _resource;
}
#Override
public View getView(int position, View view, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(resource, parent, false);
LL= (LinearLayout)v.getRootView();
LL.setOnClickListener(onButtonClickListener);
tt = (TextView) v.findViewById(R.id.vk_name);
tt.setText((CharSequence) results.get(position).get(ATTRIBUTE_NAME_TEXT_NAME));
TextView bt = (TextView) v.findViewById(R.id.vk_raiting);
bt.setText((CharSequence) results.get(position).get(ATTRIBUTE_NAME_TEXT_RAITING));
ImageView vt = (ImageView)v.findViewById(R.id.vk_photo);
vt.setImageBitmap((android.graphics.Bitmap) results.get(position).get(ATTRIBUTE_NAME_IMAGE));
return v;
}
private View.OnClickListener onButtonClickListener = new View.OnClickListener()
{
#Override
public void onClick(View view) {
LinearLayout asd = (LinearLayout)view;
LL2 = (LinearLayout)asd.getChildAt(1);
currentText = (TextView)LL2.getChildAt(0);
new AlertDialog.Builder(context)
.setTitle(currentText.getText())
.setMessage("Перейти на страницу Вконтакте?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton("Да",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
}).create().show();
}
};
private String getName()
{
int i = Top_Tab2.VkRowListView2.indexOfChild(tt);
return String.valueOf(i);
}
}

Related

How go give data from another activity to a custom ListView adapter?

I am using a custom ListView adapter, and I want the symbols to change accordingly to what is pressed in the "Settings" activity (ListView with the custom adapter is in "Home" activity). I send data to the "Home" activity using SharedPreferences, yet it seems I can't do that in the adapter. How to do that?
public class ShowcaseAdapter extends ArrayAdapter<Coin>{
private static final String TAG = "PersonalListAdapter";
private Context mContext;
int mResource;
private boolean EUROIsChecked;
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
private SharedPreferences getSharedPreferences(String sharedPrefs, int modePrivate) {
}
EUROIsChecked = sharedPreferences.getBoolean(CHECKBOXEURO, false);
public ShowcaseAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Coin> objects) {
super(context, resource, objects);
this.mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String name = getItem(position).getName();
String price = getItem(position).getPrice();
String change = getItem(position).getChange();
String number = getItem(position).getNumber();
Coin coin = new Coin(name, price, change, number);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView tvName = (TextView) convertView.findViewById(R.id.name_box);
TextView tvPrice = (TextView) convertView.findViewById(R.id.price_box);
TextView tvChange = (TextView) convertView.findViewById(R.id.change_box);
TextView tvNumber = (TextView) convertView.findViewById(R.id.number_box);
double pricedouble = Double.parseDouble(price);
pricedouble = Math.round(pricedouble * 10000.0) / 10000.0;
tvName.setText(name);
tvPrice.setText(String.valueOf(pricedouble) + "$");
tvNumber.setText(number);
Log.d("DEBUG", change);
double changenum;
changenum = Double.parseDouble(change);
if(changenum >= 0){
tvChange.setTextColor(Color.rgb(52,124,60));
tvName.setTextColor(Color.rgb(52,124,60));
}
else{
tvChange.setTextColor(Color.RED);
tvName.setTextColor(Color.RED);
}
tvChange.setText(change + "%");
return convertView;
}
}

Android: Checkbox in listview (how to create OnCheckedChangeListener in Adapter)

I'm creating a To-do list application and I have a question regarding to using checkboxes and its listeners in List Adapter. My single row in listview contains three TextViews and one Checkbox. I want to change background of single row when user "check" the checkbox. I have read that i should put checkbox listener in my adapter class and so I did it. Now is the problem - when i add few rows to my listview and left the checkbox unchecked for all of them all works fine, but when I add a row, check the checkbox and try to add another one I get error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
Below is code of my adapter. Thank you for any advice. I'm just starting with Android programming so thank you for understanding in advance.
public class ToDoAdapter extends ArrayAdapter<ToDoTask> {
ArrayList<ToDoTask> objects;
Context context;
int resource;
public ToDoAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<ToDoTask> objects) {
super(context, resource, objects);
this.objects = objects;
this.context = context;
this.resource = resource;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view = convertView;
ToDoHolder toDoHolder = null;
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row, parent, false);
toDoHolder = new ToDoHolder();
toDoHolder.rowTitle = (TextView) view.findViewById(R.id.rowTitle);
toDoHolder.rowDesc = (TextView) view.findViewById(R.id.rowDesc);
toDoHolder.rowDate = (TextView) view.findViewById(R.id.rowDate);
toDoHolder.rowIsDone = (CheckBox) view.findViewById(R.id.rowCheckBoxDone);
toDoHolder.rowIsDone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if(checked){
parent.getChildAt(position).setBackgroundColor(Color.parseColor("#8FE370"));
}
else
parent.getChildAt(position).setBackgroundColor(Color.WHITE);
}
});
view.setTag(toDoHolder);
} else {
toDoHolder = (ToDoHolder) view.getTag();
}
ToDoTask object = objects.get(position);
toDoHolder.rowTitle.setText(object.getTitle());
toDoHolder.rowDesc.setText(object.getDescription());
toDoHolder.rowDate.setText(object.getDate());
toDoHolder.rowIsDone.setChecked(object.getDone());
return view;
}
static class ToDoHolder {
TextView rowTitle;
TextView rowDesc;
TextView rowDate;
CheckBox rowIsDone;
}
}
Below is my MainActivity class which get details of single row element from "AddToDoTask" class.
public class MainActivity extends AppCompatActivity {
private final int requestCode = 1;
ArrayList<ToDoTask> lista = new ArrayList<>();
ToDoAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.buttonAdd);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new ToDoAdapter(this, R.layout.row, lista);
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AddToDoTask.class);
startActivityForResult(intent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String title, description, date;
Boolean isDone;
if (requestCode == 1) {
if (null != data) {
title = data.getStringExtra("title");
description = data.getStringExtra("description");
date = data.getStringExtra("date");
isDone = data.getBooleanExtra("done", false);
lista.add(new ToDoTask(title, description, date, isDone));
adapter.notifyDataSetChanged();
}
}
}
}
public class ToDoAdapter extends ArrayAdapter<ToDoTask> {
private ArrayList<ToDoTask> objects;
private Context context;
private int resource;
private SparseBooleanArray checkedPositions = new SparseBooleanArray();
public ToDoAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<ToDoTask> objects) {
super(context, resource, objects);
this.objects = objects;
this.context = context;
this.resource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ToDoHolder toDoHolder;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.row, parent, false);
toDoHolder = new ToDoHolder();
toDoHolder.rowTitle = (TextView) convertView.findViewById(R.id.rowTitle);
toDoHolder.rowDesc = (TextView) convertView.findViewById(R.id.rowDesc);
toDoHolder.rowDate = (TextView) convertView.findViewById(R.id.rowDate);
toDoHolder.rowIsDone = (CheckBox) convertView.findViewById(R.id.rowCheckBoxDone);
convertView.setTag(toDoHolder);
} else {
toDoHolder = (ToDoHolder) convertView.getTag();
}
toDoHolder.rowTitle.setTag(position);
toDoHolder.rowIsDone.setTag(convertView);
toDoHolder.rowIsDone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
View view = (View) compoundButton.getTag();
TextView title = (TextView) view.findViewById(R.id.rowTitle);
int pos = (int) title.getTag();
if (checked) {
checkedPositions.put(pos, true);
view.setBackgroundColor(Color.parseColor("#8FE370"));
} else {
checkedPositions.put(pos, false);
view.setBackgroundColor(Color.WHITE);
}
}
});
ToDoTask object = objects.get(position);
toDoHolder.rowTitle.setText(object.getTitle());
toDoHolder.rowDesc.setText(object.getDescription());
toDoHolder.rowDate.setText(object.getDate());
toDoHolder.rowIsDone.setChecked(object.getDone() || checkedPositions.get(position));
return convertView;
}
private class ToDoHolder {
private TextView rowTitle;
private TextView rowDesc;
private TextView rowDate;
private CheckBox rowIsDone;
}
}
You must add a layout in your row xml file and put layout in toDoHolder and just change the layouts background color. You can access child views like
layout.findViewByID(int ID);

spinner cannot be selected , its inside listview (Android)

i have two problems
1. spinner cannot be selected.
2. getting the spinner item if selected
i tried lots of things but dunno really what's with it if someone would help me i'd be really thankful
here's the code:
`
public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final List values;
public MobileArrayAdapter(Context context, List values) {
super(context, R.layout.req_row, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.req_row, parent, false);
TextView req_date = (TextView) rowView.findViewById(R.id.req_date);
TextView request_time = (TextView) rowView.findViewById(R.id.request_time);
TextView task = (TextView) rowView.findViewById(R.id.tsk);
TextView issue = (TextView) rowView.findViewById(R.id.issue);
TextView employee_name = (TextView) rowView.findViewById(R.id.emp_name);
TextView contactno = (TextView) rowView.findViewById(R.id.contact);
TextView department = (TextView) rowView.findViewById(R.id.dep);
TextView comment = (TextView) rowView.findViewById(R.id.comment);
// final Spinner empSpinner = (Spinner) rowView.findViewById(R.id.spinner);
HashMap<String, String> m = new HashMap<String, String>();
m = (HashMap) values.get(position);
req_date.setText(m.get("req_date"));
request_time.setText(m.get("req_time"));
task.setText("TSK/"+m.get("id"));
issue.setText(m.get("Issue"));
employee_name.setText(m.get("Emp_Name"));
contactno.setText(m.get("Contact_No"));
department.setText(m.get("Department"));
comment.setText(m.get("Comment"));
final Spinner empSpinner = (Spinner) rowView.findViewById(R.id.spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
R.layout.support_simple_spinner_dropdown_item, specialistsList);
dataAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
empSpinner.setAdapter(dataAdapter);
empSpinner.setSelection(position);
empSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
sp = empSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
Button send = (Button) rowView.findViewById(R.id.snd_tsk);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Send().execute();
}
});
return rowView;
}
}
`

Android-Studio I get no display in video thumbnail getView method

I need to display the video in thumbnails style but i get no display, if anyone know what i'am done wrong please give me an idea to follow.
I get the idea in this tutorial
http:android-er.blogspot.com/2011/05/display-video-thumbnail-in-listview.html
public class RemarksAdapter extends ArrayAdapter<RemarksInformation> {
Context context;
LayoutInflater inflater;
List<RemarksInformation> remarksInformationList;
public RemarksAdapter(Context context, int resourceId, List<RemarksInformation> remarksInformationList) {
super(context, resourceId, remarksInformationList);
this.context = context;
this.remarksInformationList = remarksInformationList;
inflater = LayoutInflater.from(context);
}
static class RemarksHolder{
TextView remarks;
TextView image_name;
TextView image_path;
TextView video_name;
TextView video_path;
TextView date_send;
TextView time_send;
TextView remarks_by;
RelativeLayout image_wrapper;
RelativeLayout video_wrapper;
ImageView thumbnail;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
RemarksHolder holder = null;
View v = convertView;
if(v == null){
v = inflater.inflate(R.layout.item_view_remarks, null);
holder = new RemarksHolder();
holder.remarks = (TextView)v.findViewById(R.id.txt_remarks);
holder.date_send = (TextView)v.findViewById(R.id.txt_date_send);
holder.time_send = (TextView)v.findViewById(R.id.txt_time_send);
holder.image_name = (TextView)v.findViewById(R.id.image_name);
holder.image_path = (TextView)v.findViewById(R.id.image_path);
holder.video_name = (TextView)v.findViewById(R.id.video_name);
holder.video_path = (TextView)v.findViewById(R.id.video_path);
holder.remarks_by = (TextView)v.findViewById(R.id.remarks_by);
holder.image_wrapper = (RelativeLayout)v.findViewById(R.id.image_wrapper);
holder.video_wrapper = (RelativeLayout)v.findViewById(R.id.video_wrapper);
holder.thumbnail = (ImageView)v.findViewById(R.id.vid);
v.setTag(holder);
}else{
holder = (RemarksHolder)v.getTag();
}
holder.remarks.setText(remarksInformationList.get(position).getRemarks());
holder.image_name.setText(remarksInformationList.get(position).getImage_name());
holder.image_path.setText(remarksInformationList.get(position).getImage_path());
holder.video_name.setText(remarksInformationList.get(position).getVideo_name());
holder.video_path.setText(remarksInformationList.get(position).getVideo_path());
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(remarksInformationList
.get(position).getVideo_path(), Thumbnails.MICRO_KIND);
holder.thumbnail.setImageBitmap(bmThumbnail); //Get no display
holder.date_send.setText(remarksInformationList.get(position).getDate_send());
holder.time_send.setText(remarksInformationList.get(position).getTime_send());
holder.remarks_by.setText(remarksInformationList.get(position).getRemarks_by());
holder.image_wrapper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
holder.video_wrapper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
return v;
}

Integrating current ListView with a Custom Adapter with ListView to allow multiple views

The current project I have includes a ListView with a Custom Adapter. However, I am now interested in adding multiple types of views to my ListView but after several attempts I have been unable to add the two sources of code together to successfully integrate them.
Article on ListView with multiple views: ListView Article for multiple views
The custom adapter in my current code retrieves the data from another class called getData which is referenced by "data".
Code from article (ListView with multiple views):
public class MultipleItemsList extends ListActivity {
private MyCustomAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();
for (int i = 1; i < 50; i++) {
mAdapter.addItem("item " + i);
if (i % 4 == 0) {
mAdapter.addSeparatorItem("separator " + i);
}
}
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_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList mData = new ArrayList();
private LayoutInflater mInflater;
private TreeSet mSeparatorsSet = new TreeSet();
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();
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : 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;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
}
Current code (ListView with custom adapter):
FragmentA.java
package com.example.newsapp;
public class FragmentA extends Fragment{
getData data = getData.getMyData();
public Integer ArticleID;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_a, container, false);
ListView listView = (ListView)V.findViewById(R.id.list)
CustomList adapter = new
CustomList(getActivity(), data.Headline.toArray(new String[data.Headline.size()]), data.Description.toArray(new String[data.Description.size()]), data.BitmapList.toArray(new Bitmap[data.BitmapList.size()]), data.ArticleID.toArray(new Integer[data.ArticleID.size()]));
listView.setAdapter(adapter);
listView.setOnItemClickListener(this); //Removed on click item event code.
return V;
}
CustomList.java
package com.example.newsapp;
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Bitmap[] pictureid;
public CustomList(Activity context,
String[] Headline, String[] Description, Bitmap[] BitmapList, Integer[] ArticleID) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = BitmapList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageBitmap(pictureid[position]);
return rowView;
}
}
Edit:
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Bitmap[] pictureid;
public CustomList(Activity context,
String[] Headline, String[] Description, Bitmap[] BitmapList, Integer[] ArticleID) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = BitmapList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
int viewType = getItemViewType(position);
View rowView = null;
switch(viewType) {
case 0:
LayoutInflater inflater = context.getLayoutInflater();
rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageBitmap(pictureid[position]);
case 1:
LayoutInflater inflater2 = context.getLayoutInflater();
rowView= inflater2.inflate(R.layout.single_row_loadmore, null, true);
}
return rowView;
}
#Override
public int getViewTypeCount() {
return 2; // TODO make this a static final
}
#Override
public int getItemViewType(int position) {
return position % 2; // 0 or 1
}
}
First, a bit of an aside: you should create a class that encapsulates a headline, description, etc. and use an array/collection of those objects to back your adapter. It will be far easier than managing many disparate arrays of things, especially if one day you decide you need another attribute of an Article (its category, for example).
class Article {
int id;
String headline;
String description;
Bitmap picture;
}
With regard to your ListView, the magic happens in the methods getItemViewType() and getViewTypeCount(). In getViewTypeCount() you return the maximum number of row types -- the article you posted uses two row types and so returns 2. In getItemViewType() you return a value between zero and (viewTypeCount - 1) -- in the article, his implementation can return 0 or 1 because his viewTypeCount is 2.
How you decide which row type applies to each item is entirely up to you. If, for example, you wanted to simply alternate view types on every row, you can do this:
#Override
public int getViewTypeCount() {
return 2; // TODO make this a static final
}
#Override
public int getItemViewType(int position) {
return position % 2; // 0 or 1
}
In other applications you would probably inspect the item at the given position to help you determine what should be returned in getItemViewtype().
The reason this functionality exists is that getView() provides a parameter (called convertView) that is a row which has been recycled. In order to give you an appropriate convertView, ListView needs to first know what row type it was. When you want to implement getView() for an adapter with multiple row types, it generally looks something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int viewType = getItemViewType(position);
switch(viewType) {
case 0:
return setUpOneViewType(position, convertView, parent);
case 1:
return setUpAnotherViewType(position, convertView, parent);
}
}
Note the cases for the switch statement correspond to the possible values that can be returned from getItemViewType(). These could be static final members.
I highly suggest watching The World of ListView. That video covers this topic as well as how to properly use convertView in your adapter implementation.

Categories

Resources