I have the problem that a ListView does not show my custom Array Adapter.
I tested it with an standart ArrayAdapter, which worked. I also tested if the ArrayList with the data exists, which was also the case.
ATM i think it's the Adapter, but i can't find the problem.
Where the List should be shown
public class LiSpellFragment extends Fragment {
private ArrayList<Spell> list;
public ListView lv_spellList;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_li_spell, container, false);
isList();
TestAdapter al = new TestAdapter(getContext(),R.layout.row_test, list);
lv_spellList.setAdapter(al);
return root;
}
void isList(){
if(this.list == null){
ArrayList<Spell> spellArrayList = new ArrayList<>();
Spell spell;
spell = new Spell("Hamlet");
spellArrayList.add(spell);
spell = new Spell("Carl");
spellArrayList.add(spell);
spell = new Spell("Frank");
spellArrayList.add(spell);
}
this.list = spellArrayList;
}
}
}
Custom Adapter Code
public class TestAdapter extends ArrayAdapter<Spell> {
ArrayList<Spell>list = new ArrayList<>();
int resource;
Context context;
public TestAdapter(#NonNull Context context, int resource, ArrayList<Spell> list) {
super(context, resource);
this.list = list;
this.resource = resource;
this.context = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
TextView tv = (TextView) convertView.findViewById(R.id.textView2);
tv.setText(list.get(position).getName());
return convertView;
}
}
XML of the displayed row
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class Spell
public class Spell {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Related
I have a SearchView and a ListView. My goal here is when I search for (for example) Toyota, I got result in the ListView with Toyota, and than when I click on it, Toyota save to another list.
Everything is working well, except the ListView. When I search for something, I get different result. For example if I search for Toyota, I got BMW or Mazda etc. but not Toyota. BUT, if I click on this result Toyota will be saved and not BMW or Mazda despite I click on them.
I think something with the ListView is not good, because in the background evertyhing is working well, but it's shown otherwise.
Here is my xml file:
<SearchView
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
I am using a custom row in my ListView, I don't think its affect any harm, but now I am even questioning my own existence :D So here it is the list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15sp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"
android:layout_centerVertical="true"
android:layout_marginLeft="28sp"
android:textColor="#73c993"/>
</RelativeLayout>
And the ListViewAdapter.java:
public class ListViewAdapter extends ArrayAdapter<String> {
ArrayList<String> list;
Context context;
public ListViewAdapter(Context context, ArrayList<String> items) {
super(context, R.layout.list_row, items);
this.context = context;
list = items;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_row, null);
TextView name = convertView.findViewById(R.id.name);
name.setText(list.get(position));
}
return convertView;
}
}
Finally, my HomeFragment.java:
public class HomeFragment extends Fragment implements SearchView.OnQueryTextListener {
SearchView editsearch;
static ListView listView;
static ListViewAdapter adapter;
static ArrayList<String> cars, selectedCars;
static Context context;
private HomeViewModel homeViewModel;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
return inflater.inflate(R.layout.fragment_home, container, false);
}
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
listView = (ListView) view.findViewById(R.id.list);
cars = new ArrayList<>(Arrays.asList("Toyota", "BMW", "Mazda"));
selectedCars= new ArrayList<>();
context = getContext();
adapter = new ListViewAdapter(context, cars);
listView.setAdapter(adapter);
editsearch = (SearchView) view.findViewById(R.id.search);
editsearch.setOnQueryTextListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = adapter.getItem(position);
if (!(selectedCars.contains(item))) {
addItem(item);
makeToast(item + " added.");
} else {
makeToast(item + " already added.");
}
}
});
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
i want to use card view inside my list view which is inside a fragment to show 2 variable, i already can connect to database and show only one variable "nama_matkul" from json into my list view, but i need to show "nama_matkul" and "sks" so i am creating a cardview but i am confused to make costum adapter for it
this is my json response
{
"error": false,
"matkul_mhs": [{
"nama_matkul": "matkul_3",
"sks": 3
}]}
this is my method inside fragment to initialize list view
public void initListView1(){
Call<MatkulMhs> getMatkulMhs = mApiService.getMatkulMhs(
mPrefs.getUserID());
getMatkulMhs.enqueue(new Callback<MatkulMhs>() {
#Override
public void onResponse(Call<MatkulMhs> call, Response<MatkulMhs> response) {
boolean iserror_ = response.body().getError();
if (iserror_ == false) {
List<Matkul_Mhs> list = new ArrayList<>();
list = response.body().getMatkulMhs();
nama_matkul = new String[list.size()];
for (int i =0;i<list.size();i++) {
nama_matkul[i] = list.get(i).getNamaMatkul();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, nama_matkul);
listview1.setAdapter(adapter);
}
}
this is my cardview (form_mhs_02_cardview.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_margin="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/rounded_sqrwht"
android:padding="10dp"
>
<TextView
android:id="#+id/tv_matkul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mata Kuliah 1 "
android:textSize="25dp"
android:textColor="#color/colorPrimaryDark"
android:textStyle=""
android:singleLine="true"
/>
<TextView
android:id="#+id/tv_sks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3 sks"
android:textSize="20dp"
android:textColor="#color/black"
android:singleLine="true"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
i found this answer from another post but still confuse to change into my needs
,post can be found at custom adapter for listview in fragment Android
public class CustomAdapter extends ArrayAdapter<HashMap<String,String>>
{
private ArrayList<HashMap<String,String>> callLogData;
private Context context;
private int resource;
private View view;
private Holder holder;
private HashMap<String,String> hashMap;
public CustomAdapter(Context context, int resource,ArrayList<HashMap<String, String>> objects)
{
super(context, resource, objects);
this.context=context;
this.resource=resource;
this.callLogData=objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(resource, parent,false);
holder=new Holder();
holder.text_matkul=(TextView)view.findViewById(R.id.tv_matkul);
holder.text_sks=(TextView)view.findViewById(R.id.tv_sks);
hashMap=callLogData.get(position);
Date date=new Date(Long.parseLong(hashMap.get(CallLog.Calls.DATE)));
java.text.DateFormat dateFormat=DateFormat.getDateFormat(context);
java.text.DateFormat timeformat=DateFormat.getTimeFormat(context);
holder.text_matkul.setText(hashMap.get(CallLog.Calls.NUMBER));
holder.text_sks.setText(timeformat.format(date));
return view;
}
public class Holder
{
TextView text_matkul;
TextView text_sks;
}
}
#togan-j-r please have a look at this example on this link https://medium.com/#Pang_Yao/android-fragment-use-recyclerview-cardview-4bc10beac446 and try to implement as per the demo example.
Use your Custom Adapter Class File Before SetAdapter.
CustomAdapter adapter = new CustomAdapter(getActivity(), android.R.layout.simple_list_item_1, nama_matkul);
public void initListView1(){
Call<MatkulMhs> getMatkulMhs = mApiService.getMatkulMhs(
mPrefs.getUserID());
getMatkulMhs.enqueue(new Callback<MatkulMhs>() {
#Override
public void onResponse(Call<MatkulMhs> call, Response<MatkulMhs> response) {
boolean iserror_ = response.body().getError();
if (iserror_ == false) {
List<Matkul_Mhs> list = new ArrayList<>();
list = response.body().getMatkulMhs();
nama_matkul = new String[list.size()];
for (int i =0;i<list.size();i++) {
nama_matkul[i] = list.get(i).getNamaMatkul();
}
CustomAdapter <String> adapter = new CustomAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, nama_matkul);
listview1.setAdapter(adapter);
}
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>> {
private final ArrayList<HashMap<String, String>> callLogData;
private final Context context;
private final int resource;
/*
This TODO code won't cause any issue even if not done.
*/
//TODO : Check below comment
private View view;
//TODO :: NEED TO REMOVE as adapter handle multiple items therefore no meaning in having single field of holder object
private Holder holder;
//TODO :: NEED TO REMOVE same as above. you should get item from based on position provided in getView method no need to keep reference to it
private HashMap<String, String> hashMap;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
callLogData = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Added local instance of holder
View view = inflater.inflate(resource, parent, false);
//Added local instance of holder
Holder holder = new Holder();
holder.text_matkul = (TextView) view.findViewById(R.id.tv_matkul);
holder.text_sks = (TextView) view.findViewById(R.id.tv_sks);
//Added local instance of holder
HashMap<String, String> hashMap = callLogData.get(position);
//Commenting below code
/*
Date date=new Date(Long.parseLong(hashMap.get(CallLog.Calls.DATE)));
java.text.DateFormat dateFormat=DateFormat.getDateFormat(context);
java.text.DateFormat timeformat=DateFormat.getTimeFormat(context);
*/
holder.text_matkul.setText(hashMap.get("nama_matkul"));
holder.text_sks.setText("sks");
return view;
}
public class Holder {
TextView text_matkul;
TextView text_sks;
}
}
public void initListView1() {
Call<MatkulMhs> getMatkulMhs = mApiService.getMatkulMhs(
mPrefs.getUserID());
getMatkulMhs.enqueue(new Callback<MatkulMhs>() {
#Override
public void onResponse(Call<MatkulMhs> call, Response<MatkulMhs> response) {
boolean iserror_ = response.body().getError();
if (iserror_ == false) {
List<Matkul_Mhs> list = new ArrayList<>();
list = response.body().getMatkulMhs();
ArrayList<HashMap<String, String>> nama_matkul = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("nama_matkul", list.get(i).getNamaMatkul());
item.put("sks", list.get(i).getSKS());
nama_matkul.add(item);
}
//Note: layout resource changed to your card view and ArrayAdapter to CustomAdapter
CustomAdapter adapter = new CustomAdapter(getActivity(), R.layout.form_mhs_02_cardview, nama_matkul);
listview1.setAdapter(adapter);
}
}
}
}
This is my wordAdapter. It is not showing any result when I open the Fragment. Please help me as I am a novice android developer. The Fragment page is empty and it is also not showing any error while running. So, please tell what am I missing and what is the problem in this code.
public class wordAdapter extends ArrayAdapter<word> {
private Context context;
private List<word> wrd;
private SharedPreference sharedPreference;
public wordAdapter(Context context, List<word> wrd) {
super(context, R.layout.item, wrd);
this.context = context;
this.wrd = wrd;
sharedPreference = new SharedPreference();
}
private class ViewHolder {
TextView productNameTxt;
TextView productTypeTxt;
ImageView favoriteImg;
}
#Override
public int getCount() {
return wrd.size();
}
#Override
public word getItem(int position) {
return wrd.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.productNameTxt = (TextView) convertView
.findViewById(R.id.carname);
holder.productTypeTxt = (TextView) convertView
.findViewById(R.id.cartype);
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.favu);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
word wrdn = (word) getItem(position);
holder.productNameTxt.setText(wrdn.getName());
holder.productTypeTxt.setText(wrdn.getType());
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(wrdn)) {
holder.favoriteImg.setImageResource(R.drawable.fav);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.unfav);
holder.favoriteImg.setTag("grey");
}
return convertView;
}
/*Checks whether a particular product exists in SharedPreferences*/
private boolean checkFavoriteItem(word checkwrdn) {
boolean check = false;
List<word> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (word wrdn : favorites) {
if (wrdn.equals(checkwrdn)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(word wrdn) {
super.add(wrdn);
wrd.add(wrdn);
notifyDataSetChanged();
}
#Override
public void remove(word wrdn) {
super.remove(wrdn);
wrd.remove(wrdn);
notifyDataSetChanged();
}
}
This is my word file.
public class word {
private String name;
private String type;
public word(String name, String type) {
super();
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
}
This is my Fragment file with the data.
public class Cars extends android.support.v4.app.Fragment implements
AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener {
public static final String ARG_PAGE = "ARG_PAGE";
public static Favourites newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Favourites fragment = new Favourites();
fragment.setArguments(args);
return fragment;
}
Activity activity;
ListView productListView;
List<word> wrds;
wordAdapter wrdAdapter;
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list, container,
false);
findViewsById(view);
setProducts();
wrdAdapter = new wordAdapter(activity, wrds);
productListView.setAdapter(wrdAdapter);
productListView.setOnItemClickListener(this);
productListView.setOnItemLongClickListener(this);
return view;
}
private void setProducts() {
word product1 = new word("Lamborghini Huracan", "Sport");
word product2 = new word("Lamborghini Aventador", "Sport");
word product3 = new word("Jaguar XF", "Luxury Sedan");
word product4 = new word("Audi A4", "Luxury Sedan");
word product5 = new word("Ferrari 488", "Sport");
word product6 = new word("BMW i8", "Hybrid Sport");
word product7 = new word("Audi TT", "Sport");
wrds = new ArrayList<word>();
wrds.add(product1);
wrds.add(product2);
wrds.add(product3);
wrds.add(product4);
wrds.add(product5);
wrds.add(product6);
wrds.add(product7);
}
private void findViewsById(View view) {
productListView = (ListView) view.findViewById(R.id.list_product);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
word product = (word) parent.getItemAtPosition(position);
Toast.makeText(activity, product.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favu);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, wrds.get(position));
button.setTag("red");
button.setImageResource(R.drawable.fav);
} else {
sharedPreference.removeFavorite(activity, wrds.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.unfav);
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
This is my list view.
<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="#EDEDED" >
<ListView
android:id="#+id/list_product"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay" >
</ListView>
</RelativeLayout>
This is the items view.
<?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="wrap_content"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="#+id/pdt_layout_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/carname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp" />
<TextView
android:id="#+id/cartype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/carname"
android:padding="6dp" />
<ImageView
android:id="#+id/favu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:background="#null" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#id/pdt_layout_item"/>
</RelativeLayout>
I'd like to create a ListView and add items dynamically. Here is my code:
CustomAdapter.java:
public class CustomAdapter extends ArrayAdapter<Item>{
Context context;
int layoutResourceId;
LinearLayout linearMain;
ArrayList<Item> data = new ArrayList<Item>();
public CustomAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);
Item myImage = data.get(position);
TextView label = new TextView(context);
label.setText(myImage.name);
linearMain.addView(label);
ImageView image = new ImageView(context);
int outImage = myImage.image;
image.setImageResource(outImage);
linearMain.addView(image);
}
return row;
}
}
Item.java:
public class Item {
int image;
String name;
public Item(int image, String name) {
super();
this.image = image;
this.name = name;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
GallerF.java
ArrayList<Item> imageArry = new ArrayList<Item>();
CustomAdapter adapter;
ListView dataList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_gallery, parent, false);
dataList = (ListView) v.findViewById(R.id.lista);
return v;
}
.....
public void CreateNewListRow(){
imageArry.add(new Item(R.drawable.ek_logo,name));
adapter = new CustomAdapter(getActivity(),R.layout.list,imageArry);
dataList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
list.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lineraMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
</LinearLayout>
activity_gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="hu.redbuttonebb.endi.fragmentek20.GalleryF"
android:background="#drawable/background"
android:id="#+id/linlayout">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/lista"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false" />
</ScrollView>
</LinearLayout>
Now when I run the app it's create one row with the correct picture and name. But when I'd like to create one more then nothing happen. Where do I do it wrong?
Replace your file with this:
ArrayList<Item> imageArry = new ArrayList<Item>();
CustomAdapter adapter;
ListView dataList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_gallery, parent, false);
dataList = (ListView) v.findViewById(R.id.lista);
adapter = new CustomAdapter(getActivity(),R.layout.list,imageArry);
dataList.setAdapter(adapter);
return v;
}
.....
public void CreateNewListRow(){
imageArry.add(new Item(R.drawable.ek_logo,name));
imageArry.add(new Item(R.drawable.ek_logo,name));
imageArry.add(new Item(R.drawable.ek_logo,name));
imageArry.add(new Item(R.drawable.ek_logo,name));
imageArry.add(new Item(R.drawable.ek_logo,name));
adapter.notifyDataSetChanged();
}
Edit your list.xml with below code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lineraMain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp" >
</LinearLayout>
Remove ScrollView, ListView do not require ScrollView:
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="hu.redbuttonebb.endi.fragmentek20.GalleryF"
android:background="#drawable/background"
android:id="#+id/linlayout">
<ListView
android:id="#+id/lista"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false" />
</LinearLayout>
Add this method to Adapter & extends Adapter to BaseAdapter
public class FriendsAdapter extends BaseAdapter {
Activity context;
ArrayList<String> data = new ArrayList<>();
LayoutInflater inflater;
public FriendsAdapter(Activity c) {
context = c;
inflater = LayoutInflater.from(this.context);
}
public void add(String item) {
try {
data.add(item);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public void remove(int position) {
try {
data.remove(data.get(position));
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
#Override
public int getCount() {
return data.size();
}
#Override
public String getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_friends, parent, false);
holder = new ViewHolder();
holder.tvUserName = (TextView) convertView.findViewById(R.id.tvUserName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.tvUserName.setText(data.get(position));
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
TextView tvUserName;
}}
Initializing Adapter
FriendsAdaoter adapter = new FriendsAdapter(this);
list.setAdapter(adapter);
adapter.add("ABCDEFGHIJKL");
You are creating a new Adapter every time you want to add an item. You need to create a method in your adapter and call that method when you add an item, like this:
public class CustomAdapter extends ArrayAdapter<Item>{
Context context;
int layoutResourceId;
LinearLayout linearMain;
ArrayList<Item> data = new ArrayList<Item>();
public CustomAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);
Item myImage = data.get(position);
TextView label = new TextView(context);
label.setText(myImage.name);
linearMain.addView(label);
ImageView image = new ImageView(context);
int outImage = myImage.image;
image.setImageResource(outImage);
linearMain.addView(image);
}
return row;
}
public void addItem(Item item) {
data.add(item);
notifyDataSetChanged();
}
and change your CreateNewListRow to this:
public void CreateNewListRow(){
adapter.addItem(new Item(R.drawable.ek_logo,name));
}
and change your onCreate to this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_gallery, parent, false);
dataList = (ListView) v.findViewById(R.id.lista);
adapter = new CustomAdapter(getActivity(),R.layout.list,imageArry);
dataList.setAdapter(adapter);
return v;
}
Basically I have a list of objects of class Ingredient which looks like this:
class Ingredient {
public int id;
public String name;
public Ingredient(String name) {
this.name = name;
}
}
so each object from list have a name.
Now to use ArrayAdapter I need to have a List of strings filled with names.
Is there any way to use ArrayAdapter with my list of Ingredients?
This is how it looks right now
List<Ingredient> ingredientsList= new ArrayList<Ingredient>();
ingredientsList.add(new Ingredient("foo"));
ingredientsList.add(new Ingredient("bar"));
Use the below. You can use a for loop and populate your ingredientsList. The below is just a example
List<Ingredient> ingredientsList= new ArrayList<Ingredient>();
Ingredient i= new Ingredient("foo");
ingredientsList.add(i);
Ingredient i1= new Ingredient("bar");
ingredientsList.add(i1);
Then
ListView lv = (ListView) findViewById(R.id.listview);
// initialize listview
lv.setAdpater(new CustomAdapterArrayAdapter(ActivityName.this,ingredientsList));
// set the custom adapter to listview
You can use a CustomAdapterArrayAdapter inflate a custom layout
public class CustomAarrayAdapter extends ArrayAdapter
{
List<Ingredient> ingredientsList;
public CustomArrayAdapter(Context context, List<Ingredient> list)
{
super(context,0,list);
ingredientList = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row,parent,false);
// inflate custom layout called row
holder = new ViewHolder();
holder.tv =(TextView) convertView.findViewById(R.is.textView1);
// initialize textview
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
Ingredient in = (Ingredient)ingredientsList.get(position);
holder.tv.setText(in.name);
// set the name to the text;
return convertView;
}
static class ViewHolder
{
TextView tv;
}
}
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
ViewHolder is for smooth scrolling and performance
row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="TextView" />
</RelativeLayout>
Edit:
Without using custom adapter
class Ingredient {
public int id;
public String name;
public Ingredient(String name) {
this.name = name;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return this.name.toString();
}
}
Then
public class MainActivity extends Activity {
List<Ingredient> ingredientsList= new ArrayList<Ingredient>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0;i<10;i++)
{
ingredientsList.add(new Ingredient("foo"+i));
}
ArrayAdapter<Ingredient> adapter = new ArrayAdapter<Ingredient>(this,android.R.layout.simple_list_item_1,ingredientsList);
ListView lv= (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
}
}
Then
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
Snap
Extend the array adapter class:
public class MyAdapter extends ArrayAdapter<Ingredient> {
Activity activity;
public MyAdapter(Activity context, int resource,
List<Ingredient> objects) {
super(context, resource, objects);
this.activity = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
Ingredient currentIngredient = getItem(position);
//Do Something
....
}