I've read various SO threads on the topic but none of them seem to apply to my code.
I'm trying to populate a fragment with a ListView with my custom NearbyAdapter. However, my getView() method never gets called (as demonstrated by my logs not showing up). The view itself seems to be appropriately attached to my fragment, as demonstrated by the button in the view showing up, but not the ListView.
Relevant NearbyListFragment.java code:
public class NearbyListFragment extends ListFragment {
private int mImageSize;
private boolean mItemClicked;
private NearbyAdapter mAdapter;
private List<Place> places;
private LatLng mLatestLocation;
private static final String TAG = "NearbyListFragment";
public NearbyListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "NearbyListFragment created");
View view = inflater.inflate(R.layout.fragment_nearby, container, false);
return view;
}
//TODO: Do asynchronously?
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//Load from data source (NearbyPlaces.java)
mLatestLocation = ((NearbyActivity) getActivity()).getmLatestLocation();
//FIXME: Hardcoding mLatestLocation to Michigan for testing
//mLatestLocation = new LatLng(44.182205, -84.506836);
places = loadAttractionsFromLocation(mLatestLocation);
mAdapter = new NearbyAdapter(getActivity(), places);
ListView listview = (ListView) view.findViewById(R.id.listview);
//setListAdapter(mAdapter);
listview.setAdapter(mAdapter);
Log.d(TAG, "Adapter set to ListView");
mAdapter.notifyDataSetChanged();
}
private class NearbyAdapter extends ArrayAdapter {
public List<Place> placesList;
private Context mContext;
public NearbyAdapter(Context context, List<Place> places) {
super(context, R.layout.item_place);
mContext = context;
placesList = places;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Place place = (Place) getItem(position);
//FIXME: This never gets called
Log.d(TAG, "Place " + place.name);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_place, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvDesc = (TextView) convertView.findViewById(R.id.tvDesc);
// Populate the data into the template view using the data object
tvName.setText(place.name);
tvDesc.setText(place.description);
// Return the completed view to render on screen
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
The layout file of the fragment, fragment_nearby.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/btn_New">
</ListView>
<Button
android:id="#+id/btn_New"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="20dp"
android:text="Button"
android:width="170dp"
android:layout_alignParentBottom="true" />
</RelativeLayout>
And the layout file of the item, item_place.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<TextView
android:id="#+id/tvDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Desc" />
</LinearLayout>
Edit: Does anyone want to actually include a reason for the downvote? Especially when something like Custom Adapter for List View has 129 upvotes?
The issue is that ArrayAdapter does not know about List places:
Use this to fix it:
private static class NearbyAdapter extends ArrayAdapter<Place> {
public NearbyAdapter(Context context, List<Place> places) {
super(context, R.layout.item_place, places);
mContext = context;
placesList = places;
}
}
P/s: in this case, I think you need more control to set your place data to your view. Consider using BaseAdapter instead of ArrayAdapter.
Add following to your adapter:
#Override
public int getCount() {
return placesList.size();
}
After this you most likely encounter error with getItem so you will need to override that as well to return your object from the list.
You have to override getCount() method in ArrayAdapter to initialized listview like this:
#Override
public int getCount() {
return placesList.size();
}
Related
I copied the following code from the MainActivity to a separate fragment, but I can't get findViewById to work:
I get "cannot resolve method findViewById(int)"
these are the related files:
**Also as a beginner, could you let me know if there's a general problem with my code that needs to fixed?
MyFragment.java:
public class MyFragment extends Fragment {
public myFragment() {
// Required empty public constructor
}
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my, container, false);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
//placeholder data
String[] myDataset = new String[16];
myDataset[0] = "Data0";
myDataset[1] = "Data1";
myDataset[2] = "Data2";
myDataset[3] = "Data3";
myDataset[4] = "Data4";
myDataset[5] = "Data5";
myDataset[6] = "Data6";
myDataset[7] = "Data7";
myDataset[8] = "Data8";
myDataset[9] = "Data9";
myDataset[10] = "Data10";
myDataset[11] = "Data11";
myDataset[12] = "Data12";
myDataset[13] = "Data13";
myDataset[14] = "Data14";
myDataset[15] = "Data15";
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
}
MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView upTv;
public TextView downTv;
public View layout;
public MyViewHolder(View v) {
super(v);
layout = v;
upTv = (TextView)v.findViewById(R.id.upTv);
downTv = (TextView)v.findViewById(R.id.downTv);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.upTv.setText(mDataset[position]);
holder.downTv.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
}
fragment_my.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:scrollbars="vertical"/>
</android.support.constraint.ConstraintLayout>
my_text_view.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher_background" />
<TextView
android:id="#+id/downTv"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:text="downTv"
android:textSize="12sp" />
<TextView
android:id="#+id/upTv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="upTv"
android:textSize="16sp" />
</RelativeLayout>
Here's your problem:
return inflater.inflate(R.layout.fragment_my, container, false);
You cannot add more code after the return statement. You will need to take the reference of the inflated view and use it to find the reference of child views.
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
// other code
return rootView;
A really good way to use fragments is to initialize certain variables(e.g- activity,context,root view etc) associated with the parent activity when you switch to a fragment.
for example you can do sth like,
private Context context;
private MainActivity activity; //Let MainActivity is your parent activity
private View view; //fields kept inside the fragment class,now we need to keep them initialized
//initialize activity/context from onAttach
#Override
public void onAttach(Context c) {
super.onAttach(c);
Activity a;
context=c;
if (c instanceof Activity){
a=(Activity) c;
if(a instanceof MainActivity)
activity=(MainActivity) a;
}
}
//initialize view from onViewCreated
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.view=view;
}
now you can use them wherever u want inside the fragment class without triggering any nullptrs and other stuff
e.g- you can go
this.view.findViewById(your_resId);
this.activity.getSupportFragmentManager();
etc and a lot of other stuffs when you need ,using these fields you initialized
also specifically in this case of using recyclerView dont forget to call,
adapter.notifyDataSetChanged() whenever you think the list you are showing in the recyclerView went through some change.
I do not have enough reputation to comment so i am writing this as answer to your comment.
You need to notify adapter using below code.
mAdapter.notifyDataSetChanged();
I am new to android programming and this task is really need for my school project. Please kindly help me.
I've string array List - (retrieved from csv)
list = new ArrayList<>(Arrays.asList("111,222,333,444,555,666".split(",")));
myList.setAdapter(new ArrayAdapter<String>(getActivity(),R.layout.cell,list));
The result is showing only line by line text of arrayList. I want to add button to each generated line by line to delete clicked row.
Please how can I do this. Thank you for understanding my problem.
You have to create a custom layout xml which having a single item then you will add your button to this layout along with any other items.
CustomLayout.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" >
<TextView
android:id="#+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call" />
</RelativeLayout>
Now after creating custom item layout you need listview which holds all items.
MainActivity.xml
.
.
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
.
.
Now in java file just set adapter with our custom layout xml
.
.
list = new ArrayList<String>(Arrays.asList("111,222,333,444,555,666".split(",")));
listview.setAdapter(new MyCustomAdapter(list, context) );
.
.
Custom adapter Class
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.CustomLayout, null);
}
//Handle TextView and display string from your list
TextView tvContact= (TextView)view.findViewById(R.id.tvContact);
tvContact.setText(list.get(position));
//Handle buttons and add onClickListeners
Button callbtn= (Button)view.findViewById(R.id.btn);
callbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
.
}
});
return view;
}
}
We have need ListviewActivity for listing your data
SchoolAdapter which is custom adapter to inflate each individual row
activity_listview which is layout for ListviewActivity
view_listview_row which is required for each individual row
Now create all file as below
For ListviewActivity,
public class ListviewActivity extends AppCompatActivity {
private ListView mListview;
private ArrayList<String> mArrData;
private SchoolAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mListview = (ListView) findViewById(R.id.listSchool);
// Set some data to array list
mArrData = new ArrayList<String>(Arrays.asList("111,222,333,444,555,666".split(",")));
// Initialize adapter and set adapter to list view
mAdapter = new SchoolAdapter(ListviewActivity.this, mArrData);
mListview.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
For SchoolAdapter,
public class SchoolAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mArrSchoolData;
public SchoolAdapter(Context context, ArrayList arrSchoolData) {
super();
mContext = context;
mArrSchoolData = arrSchoolData;
}
public int getCount() {
// return the number of records
return mArrSchoolData.size();
}
// getView method is called for each item of ListView
public View getView(int position, View view, ViewGroup parent) {
// inflate the layout for each item of listView
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.view_listview_row, parent, false);
// get the reference of textView and button
TextView txtSchoolTitle = (TextView) view.findViewById(R.id.txtSchoolTitle);
Button btnAction = (Button) view.findViewById(R.id.btnAction);
// Set the title and button name
txtSchoolTitle.setText(mArrSchoolData.get(position));
btnAction.setText("Action " + position);
// Click listener of button
btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Logic goes here
}
});
return view;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}}
For activity_listview,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#D1FFFF"
android:orientation="vertical">
<ListView
android:id="#+id/listSchool"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#0000CC"
android:dividerHeight="0.1dp"></ListView>
For view_listview_row,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="7.5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="7.5dp">
<TextView
android:id="#+id/txtSchoolTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="2dp"
android:text="TextView"
android:textColor="#android:color/black"
android:textSize="20dp" />
<Button
android:id="#+id/btnAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Click Me" />
At last but not least, do not forgot to add your activity in manifest.xml
Create a custom list view in another file with the only content of each item in the list.
Then create a Custom Adapter extending BaseAdapter and bind it.
Please refer to this website for example.
https://looksok.wordpress.com/tag/listview-item-with-button/
OR
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
I am beginner of Android programming and need little help.
I have an array of objects that should be shown in listview. Here is a code of class:
public class Car {
public String img;
public String thumbnail;
public String manufacturer;
public String model;
public int price;
public String description;
}
Thumbnail is a string variable that contains URL of thumbnail to be shown.
I also have array of a few Car objects called "cars" declared in my DataStorage class.
I want only 2 things of every object to be shown in my customized listview: thumbnail (from internet) and model.
I created layout item.xml, which should represent one item of listview:
<?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="100dp"
android:background="#android:color/holo_blue_dark">
<ImageView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:text="left"
android:id="#+id/image_tmb"
android:layout_gravity="left|center_vertical"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_dark">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:paddingBottom="10dp"
android:id="#+id/name"
android:layout_weight="1"
android:textSize="23dp"/>
</LinearLayout>
</LinearLayout>
TextView should be filled with model and Imageview should be filled with thumbnail.
I also created class MyAdapter which should fill listview:
public class MyAdapter extends BaseAdapter {
private Context myContext;
public MyAdapter(Context context) {
this.myContext = context;
}
#Override
public int getCount() {
return DataStorage.cars.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
//Here I should customize my view but don't know how.
}
I created listview element in activity_main.xml and delcared it in MainActivity:
ListView lv=(ListView) findViewById(R.id.lv);
So, how would I do my task?
A simple pattern would look something like this
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
// Inflate the view if it doesn't already exist
if (view == null) {
LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
// Get your current Car object
Car c = getItem(i);
// Initialize the views
ImageView image = (ImageView) view.findViewById(R.id.image_tmb);
TextView name = (TextView) view.findViewById(R.id.name);
// Fill the views according to the car's properties
/* NOTE: I'm not going to go in depth to explain how to set
an ImageView image from a URL, as it is an entirely different question,
so I'll put a link to this library below */
Picasso.with(myContext).load(c.thumbnail).into(image);
name.setText(c.model);
}
You'll need to modify getItem to actually get the item, instead of returning null..
#Override
public Object getItem(int position) {
return DataStorage.cars[position];
}
Then, set up your adapter in your Activity/Fragment/Whatever, like this
MyAdapter mAdapter = new MyAdapter(this);
lv.setAdapter(mAdapter);
If you're going to be doing a lot with images and don't want to write your own implementation, Picasso is a really easy library to use.
i want to combine two LinearLayout, both have different TextView arrangement in them, in a single ListView. so the final look should be like below:
and i run it with my code, but the app wouldn't start. below are my code.
Activity class:
public class MainActivity extends Activity {
// Create list of items
String[] publicModeItems = {
"AAAAA",
"BBBBB"
};
String[] publicModeParameters = {
"YES",
"NO"
};
String[] publicModeResetExe = {
"CCCCC",
"DDDDD"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
private void populateListView() {
CustomList adapter1 = new CustomList(this, publicModeItems, publicModeParameters);
// Build adapter
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
this, // context for the activity
R.layout.text_view_test, // layout to use (create)
publicModeResetExe); // items to display
// Configure the list view
ListView list = (ListView) findViewById(R.id.PublicModeListView);
list.setAdapter(adapter1);
list.setAdapter(adapter2);
}
private class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] publicModeItems;
private final String[] publicModeParameters;
public CustomList(Activity context,
String[] publicModeItems,
String[] publicModeParameters) {
super(context, R.layout.text_views_1, publicModeItems);
this.context = context;
this.publicModeItems = publicModeItems;
this.publicModeParameters = publicModeParameters;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutinflater = context.getLayoutInflater();
View rowView = layoutinflater.inflate(R.layout.text_views_1, null, true);
TextView txtPublicModeItems = (TextView) rowView.findViewById(R.id.PublicModeItems);
TextView txtPublicModeParameters = (TextView) rowView.findViewById(R.id.PublicModeParameters);
txtPublicModeItems.setText(publicModeItems[position]);
txtPublicModeParameters.setText(publicModeParameters[position]);
return rowView;
}
}
}
text_views_1 xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/PublicModeLayoutForTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/PublicModeItems"
android:layout_width="200sp"
android:layout_height="wrap_content"
android:textColor="#drawable/text_color_change" />
<TextView
android:id="#+id/PublicModeOpenBracket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="["
android:textColor="#drawable/text_color_change" />
<TextView
android:id="#+id/PublicModeParameters"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:gravity="end"
android:textColor="#drawable/text_color_change" />
<TextView
android:id="#+id/PublicModeCloseBracket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="]"
android:textColor="#drawable/text_color_change" />
</LinearLayout>
text_view_test xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#drawable/text_color_change" >
</TextView>
activity_main xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/PublicModeListViewLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/black"
android:baselineAligned="true"
android:orientation="vertical"
tools:context="com.example.mycalendar.MainActivity" >
<LinearLayout
android:id="#+id/PublicModeListViewLayout02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/custom_border"
android:padding="5dp" >
<ListView
android:id="#+id/PublicModeListView"
android:layout_width="308dp"
android:layout_height="wrap_content"
android:choiceMode="singleChoice"
android:listSelector="#color/yellow"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
</LinearLayout>
Problem : I just run my code just now, and only 'CCCCC' and 'DDDDD' is showing. so do you have any idea on this?
You should inherit your list adapter from BaseAdapter rather than ArrayAdapter.
Rewrite adapter's getView() method to inflate layout according position, like below.
public View getView(int position, View convertView, ViewGroup parent) {
...
View rootView = null;
if (position == 0 || position == 1) {
rootView = layoutinflater.inflate(R.layout.text_views_1, null, true);
} else {
rootView = layoutinflater.inflate(R.layout.text_views, null, true);
}
...
return rootView;
}
You set the list adapter twice
list.setAdapter(adapter1);
list.setAdapter(adapter2);
in this case the current adapter is the second, not them both.
Use ListView with SimpleAdapter or a custom adapter and that will solve all your problems, check out this for SimpleAdapter tutorial to learn a the basics and this tutorial to learn how you can make multiple views instead of just 1. This tutorial is about creating custom adapter
BTW, I have few comments on your code and xml layout
First, there is no need for 2 TextViews for your bracket, you can easily add them programmatically to the String[] or even to YES/NO TextView.
Second, You're not using a ViewHolder in your CustomList adapter and this is not a good practice as every time you scroll your list, it creates new view although it can use already existing one.
I already solve this problem. but it seems not so convenient to use this method.
public class PublicModeActivity extends Activity {
// Create list of items
String[] publicModeItems = {
"AAAAA",
"BBBBB"
};
String[] publicModeParameters = {
"YES",
"NO"
String[] publicModeResEx = {
"",
"",
"CCCCC",
"DDDDD"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
private void populateListView() {
CustomList adapter = new CustomList(this, publicModeItems, publicModeParameters, publicModeResEx);
// Configure the list view
ListView list = (ListView) findViewById(R.id.PublicModeListView);
list.setAdapter(adapter);
}
private class CustomList extends BaseAdapter {
private final Activity context;
private final String[] publicModeItems;
private final String[] publicModeParameters;
private final String[] publicModeResEx;
public CustomList(Activity context,
String[] publicModeItems,
String[] publicModeParameters,
String[] publicModeResEx) {
super();
this.context = context;
this.publicModeItems = publicModeItems;
this.publicModeParameters = publicModeParameters;
this.publicModeResEx = publicModeResEx;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutinflater = context.getLayoutInflater();
View rowView = null;
Log.i("PublicModeActivity", "" + position);
if (position < 2) {
rowView = layoutinflater.inflate(R.layout.text_views_1, null, true);
TextView txtPublicModeItems = (TextView) rowView.findViewById(R.id.PublicModeItems);
TextView txtPublicModeParameters = (TextView) rowView.findViewById(R.id.PublicModeParameters);
txtPublicModeItems.setText(publicModeItems[position]);
txtPublicModeParameters.setText(publicModeParameters[position]);
} else {
rowView = layoutinflater.inflate(R.layout.text_view_test, null, true);
TextView txtPublicModeResEx = (TextView) rowView.findViewById(R.id.PublicModeResEx);
txtPublicModeResEx.setText(publicModeResEx[position]);
}
return rowView;
}
#Override
public int getCount() {
return 4;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
}
}
I need to put that blank string "", to match the number of row with the upper layout (text_views_1) even-though those blank string are use in different layout. so it is not so convenient especially when you want to display so many data. If someone here have much simpler method than this. feel free to share with me/us. i'm eager to learn. thank you!
Please note, this is really weird.
For some reason, the method setChoiceMode (ListView.CHOICE_MODE_SINGLE) no results.
I use it like this:
list = (ListView) findViewById(R.id.list);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setOnItemClickListener(OnItemClickListenerObject);
list.setAdapter(adapter);
The fact is that after I put the method setChoiceMode (), nothing has changed, RadioButtons not appeared.
I'm using a custom adapter and I have no problems with it? But I do not understand why Radiobuttons not shown.
Any ideas? (If you need additional code, ask and I'll post it.)
My adapter code:
public class ContactAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<Contact> contacts;
private View view;
public ContactAdapter(Context context, ArrayList<Contact> contacts) {
this.contacts = contacts;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return contacts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private Contact getContact(int position) {
return (Contact) getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.contact_item, parent, false);
}
Contact c = getContact(position);
((TextView) view.findViewById(R.id.lv_name)).setText(c.getName() + " " + c.getSurname());
((ImageView) view.findViewById(R.id.lv_img)).setImageBitmap(c.getPhoto());
return view;
}
}
Below shows the layout that I use for ListView item.
<?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="wrap_content"
android:orientation="horizontal"
android:layout_margin="8dp">
<ImageView
android:id="#+id/lv_img"
android:layout_width="75dp"
android:layout_height="75dp"
android:src="#drawable/default_user"
android:layout_weight="0"/>
<TextView
android:id="#+id/lv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="16dp"
android:layout_gravity="center_vertical"
android:textSize="24sp"/>
</LinearLayout>
Setting the choice mode does not automatically make radio buttons appear. All it does is add behavior which toggles a ListView row's Checkable or activation state. It's still up to the row's View to decide how to react to that. You'll need to create your own layout to inflate for a row that supports the activation state or the Checkable interface.
Android does provide some simple pre-made views that you can use. Here's just a couple you can choose from:
android.R.layout.simple_list_item_activated_1.xml
android.R.layout.simple_list_item_checked.xml