I am aware that other people have asked this question, but I have looked at other solutions and still can't get it to work.
Adapter code:
private class CustomTextAndImageAdapter extends ArrayAdapter<String> {
private Context context;
private Activity activity;
private ArrayList<String> timeArrayList;
private ArrayList<Bitmap> weatherIconArrayList;
private ArrayList<String> descriptionArrayList;
private ArrayList<String> tempArrayList;
private ArrayList<String> popArrayList;
private ArrayList<String> windSpeedArrayList;
public final void setTimeArrayList(ArrayList<String> timeArrayList)
{
this.timeArrayList = timeArrayList;
}
public final void setDescriptionArrayList(ArrayList<String> descriptionArrayList)
{
this.descriptionArrayList = descriptionArrayList;
}
public final void setTempArrayList(ArrayList<String> tempArrayList)
{
this.tempArrayList = tempArrayList;
}
public final void setPopArrayList(ArrayList<String> popArrayList)
{
this.popArrayList = popArrayList;
}
public final void setWindSpeedArrayList(ArrayList<String> windSpeedArrayList)
{
this.windSpeedArrayList = windSpeedArrayList;
}
public final void setWeatherIconArrayList(ArrayList<Bitmap> weatherIconArrayList)
{
this.weatherIconArrayList = weatherIconArrayList;
}
public CustomTextAndImageAdapter(Context context, Activity activity, int resource)
{
super(context, resource);
this.context = context;
this.activity = activity;
}
#Override
public View getView(int position, View view, ViewGroup parent)
{
Log.d(Constants.LOG_TAG, "getView() method called");
LayoutInflater inflater = activity.getLayoutInflater();
View rowView= inflater.inflate(R.layout.itemlistrow, null, false);
TextView timeTextView = (TextView)rowView.findViewById(R.id.time);
timeTextView.setText(timeArrayList.get(position));
Log.d(Constants.LOG_TAG, "Time text view text = " + timeArrayList.get(position));
ImageView iconImageView = (ImageView) rowView.findViewById(R.id.weatherIcon);
iconImageView.setImageBitmap(weatherIconArrayList.get(position));
TextView descriptionTextView = (TextView)rowView.findViewById(R.id.description);
descriptionTextView.setText(descriptionArrayList.get(position));
TextView tempTextView = (TextView)rowView.findViewById(R.id.temp);
tempTextView.setText(tempArrayList.get(position));
TextView popTextView = (TextView)rowView.findViewById(R.id.pop);
popTextView.setText(popArrayList.get(position));
TextView windSpeedTextView = (TextView)rowView.findViewById(R.id.windSpeed);
windSpeedTextView.setText(windSpeedArrayList.get(position));
return rowView;
}
}
List item layout (itemlistrow.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/weatherIcon"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sunny"
android:id="#+id/description"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="11 C"
android:id="#+id/temp"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "Rain:"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "Wind:"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id = "#+id/pop"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "#+id/windSpeed"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In some of the other solutions, it mentions overriding getCount(). Is this what I am doing wrong? If so, how would I know what to put in for getCount(), as there are multiple different ArrayLists used. Is it a case of picking one of them, as they are all the same length, e.g. timeArrayList.size()?
Using multiple ArrayList objects like that kind of defeats the purpose of using an ArrayAdapter, whose idea is to have a single source of items. Not to mention that the code right now doesn't look nice at all.
I'd suggest to first create a Weather object that will hold your data:
public class Weather {
private String time;
private Bitmap weatherIcon;
private String description;
private String temp;
private String pop;
private String windSpeed;
// build object here, provide getters, etc....
.....
}
Than your adapter can be transformed to something simpler like this:
private class CustomTextAndImageAdapter extends ArrayAdapter<Weather>
{
private LayoutInflater inflater;
public CustomTextAndImageAdapter(Context context, Activity activity, int resource, List<Weather> items)
{
super(context, resource, items);
this.inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View view, ViewGroup parent)
{
View rowView= inflater.inflate(R.layout.itemlistrow, null, false);
TextView timeTextView = (TextView)rowView.findViewById(R.id.time);
timeTextView.setText(getItem(position).getTime());
ImageView iconImageView = (ImageView) rowView.findViewById(R.id.weatherIcon);
iconImageView.setImageBitmap(getItem(position).getWeatherIcon());
........
return rowView;
}
}
Main difference is that it's now an ArrayAdapter<Weather> and that you're passing the arguments directly in the constructor of the adapter. Users of the adapter now have to call just 1 constructor, instead of all the final methods that had to be called before.
The other major difference is that you're passing the items list to the super class. Now your adapter knows it's size (internally getCount() will be == items.size()) so getView() will be called appropriately.
As a final thought - the adapter is still not using the ViewHolder pattern, which you should totally implement! There's been numerous posts for it, so just search a bit and you'll find it.
This is not a good way to populate a ListView using an adapter which populates the data from multiple ArrayList. Generally we use a single source of dataset to be passed to an adapter in case of showing a list in Android.
So in your case, when you'll call the notifyDatasetChanged it shouldn't take effect in the list properly as far as I can guess.
notifyDatasetChanged basically calls the getCount function of the adapter and checks if the size of the ArrayList associated with the adapter is changed or not. If the size of the ArrayList is changed, it refreshes the ListView and the getView function gets called.
In your case, I don't see any getCount function though. getCount usually returns the size of the ArrayList associated with the adapter.
So I would suggest, using a single ArrayList to be passed to the adapter. You can merge multiple ArrayList and can use one joined HashMap in your case too. Its your decision, exactly how you can pass a single list of your dataset to the adapter to populate them into a ListView.
Related
I have a page in which I'm taking the START TIME and END TIME from DATABASE.
Let's say the START TIME is 7:00 and END TIME is 22:00
I want to use this START TIME and END TIME to show in my page as textview like 7:00 8:00 9:00 and sooo on till 22:00 as textview
Also I have an imageview that will also increase when the text increases.
How can I achieve this?
Also I want the result text in Horizontal Scroll View with Imageview at top and text view as bottom of each imageview
char first = StartTime.charAt(0);
int StartTimeint = Integer.parseInt(String.valueOf(first));
int l;
for( l = StartTimeint; l<=22; l++){
Log.d("SeatsPage", "Time is "+l);
}
timeofseats.setText(Integer.toString(l));
This is I have done so far but I'm getting 23 as a result, the textview is not increasing
This is my XML File
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/llMain"
android:layout_height="match_parent"
tools:context=".SeatsPagewithDB.SeatsPage">
<ImageView
android:id="#+id/imageView11"
android:layout_width="150px"
android:layout_height="150px"
android:layout_marginStart="28dp"
android:layout_marginEnd="326dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/seat" />
<TextView
android:id="#+id/timeofseats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="334dp"
android:background="#FF0000"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="7:00"
android:textColor="#fff"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView11" />
</android.support.constraint.ConstraintLayout>
This is the result I am getting as layout
This what I want programmatically
The XML code that you write in your layout.xml file to create the UI is for static UI only. What you are asking is to create views dynamically during runtime. Although you can definitely create views using java code on a click of a button or something. But it is better to code less for the UI whenever possible and keep it separated from the program code. Instead use the tools given to us by the framework we are using.
In Android those tools include stuff like ListView, GridView and the newer and better RecyclerView. These views help you add other views dynamically to your UI in runtime. You define one of them or more (depending on your UI needs) once in your layout.xml and configure them using java code like any other view.
This is how you can use RecyclerView to achieve your goal. I can't explain everything how RecyclerView works and what each line of code does as it will make a very long post but I have tried to highlight main things briefly.
1. Add RecyclerView in your layout file.
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
2. Create another layout file and define the template UI of the item that the RecyclerView is going to display. RecyclerView will populate each item that it holds with this layout.
item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView_alarm"
android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/alarm" />
<TextView
android:id="#+id/textView_Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#FF0000"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:text="Time"
android:textColor="#android:color/background_light"
android:textSize="24sp" />
</LinearLayout>
3. Create a ViewHolder class that extends from RecyclerView.ViewHolder. View holder is a RecyclerView related concept. In short it works as a wrapper around the view of a single item and aids in binding new data to the view of the item. Create a bind() function inside view holder to make your life easier.
EDIT: I have updated the class by implementing the View.OnClickListener interface, modified the constructor to pass in the context from onCreateViewHolder() and adding a setItemPosition() just for the sake to pass the item position number from onBindViewHolder() all over to here so we can use this position number in our onClick() method of the interface
MyViewHolder.java [UPDATED]
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textView;
private int itemPosition;
private Context mContext;
public MyViewHolder(#NonNull View itemView, Context context) {
super(itemView);
itemView.setOnClickListener(this);
mContext = context;
textView = itemView.findViewById(R.id.textView_Time);
}
void bind(String timeText)
{
textView.setText(timeText);
}
void setItemPosition(int position)
{
itemPosition = position;
}
#Override
public void onClick(View v) {
Toast.makeText(mContext, "You clicked item number: " + itemPosition , Toast.LENGTH_SHORT).show();
}
}
4. Create an Adapter class that extends from RecyclerView.Adapter. Adapter works as a bridge between the UI data and RecyclerView itself. An Adapter tells the RecyclerView what layout file to inflate and how many to inflate. RecyclerView job is to deal with how to inflate it on the UI.
EDIT : Just changed myViewHolder in onCreateViewHolder() to match the modified constructor of MyViewHolder. Added the call to setItemPosition() in the onBindViewHolder().
MyAdapter.java [UPDATED]
public class MyAdapter extends RecyclerView.Adapter {
List<String> timeIntervalList = new ArrayList<>();
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view , parent.getContext());
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
MyViewHolder viewHolder = (MyViewHolder) holder;
viewHolder.setItemPosition(position);
viewHolder.bind(timeIntervalList.get(position));
}
#Override
public int getItemCount() {
return timeIntervalList.size();
}
public void addItem (String timeText)
{
timeIntervalList.add(timeText);
notifyItemInserted(getItemCount());
}
}
In this adapter you will see two functions. OnCreateViewHolder() inflates the view using the template layout file for a single item and OnBindViewHolder() binds new data to the default values of the of the view just created. The data used for binding is stored in a list inside this Adapter called the timeIntervalList. This list will hold your time interval strings so they can be updated on the view.
5. Finally, use this RecyclerView where you want to use it. Like in your MainActivity.java. RecyclerView needs to be told in what fashion to display the items (e.g list , grid etc ) using a LayoutManager. LinearLayoutManager will display items either vertically or horizontally. You can see I am using your logic to increment time from string and adding new views to RecyclerView using the addItem() function of the MyAdapter class.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView myRecyclerView;
private MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myRecyclerView = findViewById(R.id.recyclerView);
myAdapter = new MyAdapter();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this , LinearLayoutManager.HORIZONTAL, false);
myRecyclerView.setLayoutManager(linearLayoutManager);
myRecyclerView.setAdapter(myAdapter);
// This is how you will populate the recycler view
String START_TIME = "7:00";
String END_TIME = "22:00";
char first = START_TIME.charAt(0);
int StartTimeint = Integer.parseInt(String.valueOf(first));
int l;
for( l = StartTimeint; l<=22; l++){
// This is where new item are added to recyclerView.
myAdapter.addItem(l + ":00");
}
}
}
This is the final result.
Change your activity layout XML code as follows,
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/llMain"
android:layout_height="match_parent"
tools:context=".SeatsPagewithDB.SeatsPage">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
...>
<LinearLayout
android:id="#+id/container"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</HorizontalScrollView>
</android.support.constraint.ConstraintLayout>
Move the textview and imageview to another XML file let's call it item_view.xml (you can name it whatever you wish). we are doing so because the root view of this file will be reused.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView11"
android:layout_width="150px"
android:layout_height="150px"
app:srcCompat="#drawable/seat"/>
<TextView
android:id="#+id/timeofseats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="7:00"
android:textColor="#fff"
android:textSize="20dp"/>
</LinearLayout>
Now make following changes in your Java file
LinearLayout container = findViewById(R.id.container); // or rootView.findViewById() for custom View and Fragment
char first = StartTime.charAt(0);
int StartTimeint = Integer.parseInt(String.valueOf(first));
for(int l = StartTimeint; l<=22; l++){
Log.d("SeatsPage", "Time is "+l);
View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_view, null);
TextView timeofseats = view.findViewById(R.id.timeofseats);
timeofseats.setText(Integer.toString(l));
container.addView(view);
}
I have a main activity (ActivityMain.java) that I would like to use to navigate between four fragments. In one of these fragments, I'm attempting to place a CardView in conjunction with a RecyclerView to create a vertical list of cards. However, so far I've been unable to get any of the cards to display when I run the app. The CardView will display perfectly in Android Studio's design preview, but when an actual device/emulator is used it disappears.
I've tried to manually set the visibility of the CardView through Java, but it continued to stay invisible. I believe that the fragment's layout could be covering the CardView's layout, but I'm still very new to Android development so I'm not completely sure what the problem could be.
Below I've pasted the classes and XML files that are likely to be associated with my problem.
AdapterMainFeed.java
public class AdapterMainFeed extends RecyclerView.Adapter<AdapterMainFeed.ViewHolderMainFeed> {
private ArrayList<Article> listArticlesMain = new ArrayList<>();
private LayoutInflater inflater;
public AdapterMainFeed(Context context) {
inflater = LayoutInflater.from(context);
}
public void setArticlesMain(ArrayList<Article> listArticlesMain) {
this.listArticlesMain = listArticlesMain;
notifyDataSetChanged();
}
#Override
public ViewHolderMainFeed onCreateViewHolder(ViewGroup container, int i) {
View layout = inflater.inflate(R.layout.view_main_feed, container, false);
Article article1 = new Article("asdf", "ghj", "klm", new Date(0));
Article article2 = new Article("sdfg", "hjk", "lmn", new Date(0));
Article article3 = new Article("dfgh", "jkl", "mno", new Date(0));
listArticlesMain.add(article1);
listArticlesMain.add(article2);
listArticlesMain.add(article3);
return new ViewHolderMainFeed(layout);
}
#Override
public void onBindViewHolder(ViewHolderMainFeed viewHolderMainFeed, int i) {
Article currentArticle = listArticlesMain.get(i);
viewHolderMainFeed.articleTitle.setText(currentArticle.getTitle());
viewHolderMainFeed.articleAuthor.setText(currentArticle.getAuthor());
viewHolderMainFeed.articleWebsite.setText(currentArticle.getWebsite());
DateFormat formatter = DateFormat.getDateTimeInstance();
final String timePosted = formatter.format(currentArticle.getTimePosted());
viewHolderMainFeed.articleTime.setText(timePosted);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return listArticlesMain.size();
}
static class ViewHolderMainFeed extends RecyclerView.ViewHolder {
TextView articleTitle;
TextView articleAuthor;
TextView articleWebsite;
TextView articleTime;
public ViewHolderMainFeed(View itemView) {
super(itemView);
articleTitle = (TextView) itemView.findViewById(R.id.mainArticleTitle);
articleAuthor = (TextView) itemView.findViewById(R.id.mainArticleAuthor);
articleWebsite = (TextView) itemView.findViewById(R.id.mainArticleWebsite);
articleTime = (TextView) itemView.findViewById(R.id.mainArticleTime);
}
}
}
view_main_feed.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context="com.convergeapp.converge.ActivityMain">
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
card_view:cardCornerRadius="7dp"
card_view:cardBackgroundColor="#color/colorPurpleSeance"
android:id="#+id/mainArticleCard"
android:layout_width="match_parent"
android:layout_height="300dp"
android:padding="8dp"
android:clickable="true">
<RelativeLayout
android:id="#+id/mainArticleLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<TextView
android:id="#+id/mainArticleTitle"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
<TextView
android:id="#+id/mainArticleAuthor"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_below="#id/mainArticleTitle"/>
<TextView
android:id="#+id/mainArticleWebsite"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_below="#+id/mainArticleTime"/>
<TextView
android:id="#+id/mainArticleTime"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
After playing around with some changes, I finally discovered the solution. What I did was add the Article objects to the list in the main fragment's onCreateView method. Additionally, I instantiated CardView in the ViewHolder, though that didn't help me see the cards initially.
So, if you're ever in a similar predicament and can't figure out the solution, try to actually create the objects before setting them.
You need to call notifyDataSetChanged(); inside onCreateViewHolder after adding the new articles so that the itemcount is updated
I am working on an Android application in which I have one container called as Section and there can be Note objects inside it. The use-case is that a user can put multiple notes in a section and organize them. Currently I am to display the section names retrieved from the server with a background image.
Now my problem is how can I display the multiple notes received from the server inside the section.
I understand that this can be achieved by FrameLayout, but a dynamic Note count is what my problem is.
Please note that the count of notes can vary, depending upon user.
Here is the original screenshot of how sections look currently :
Now when you would add notes, it ideally should look like this :
Each of those blocks inside the section contains Note objects. To display its contents, I want to show a note block kind of image and just few words
of the note contents.
Currently I have code to retrieve the Notes from the server, sections can be displayed, but I really have no idea how to proceed because notes can be dynamic. Here is my code so far.
public class GroupSectionActivity extends Activity {
private SectionServiceImpl sectionService = new SectionServiceImpl();
private NoteServiceImpl noteService = new NoteServiceImpl();
private static volatile List<RestSection> restSectionList = new ArrayList<>();
private static volatile List<RestNote> restNoteList = new ArrayList<>();
private static volatile Long groupAccountId;
private static volatile Integer canvasid;
ListView listView;
SectionLazyAdapter sectionLazyAdapter;
static final String msectionname = "msectionname";
static final String msectionid = "msectionid";
Button addSectionButton;
EditText sectionName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sectionlayout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
groupAccountId = extras.getLong("groupid");
canvasid = extras.getInt("canvasid");
}
restSectionList = this.sectionService.getSectionByCanvas(canvasid);
ArrayList<HashMap<String, String>> restSectionArrayList = new ArrayList<HashMap<String, String>>();
for (RestSection restSection : restSectionList) {
HashMap<String, String> sectionDisplay = new HashMap<>();
sectionDisplay.put("msectionid", String.valueOf(restSection.getMsectionid()));
sectionDisplay.put("msectionname", restSection.getMsectionname());
restSectionArrayList.add(sectionDisplay);
}
listView = (ListView) findViewById(R.id.seclist);
sectionLazyAdapter = new SectionLazyAdapter(this, restSectionArrayList);
listView.setAdapter(sectionLazyAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int sectionId = restSectionList.get(position).getMsectionid();
Log.d("Sectionid is ", String.valueOf(sectionId));
/*Intent intent = new Intent(GroupSectionActivity.this, GroupSectionActivity.class);
intent.putExtra("groupid", groupAccountId);
intent.putExtra("sectionid", sectionId);
startActivity(intent);
finish();*/
}
});
BaseAdapter to manage the guys :
public class SectionLazyAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public SectionLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_group_section, null);
TextView sectionName = (TextView)vi.findViewById(R.id.sectionname); // title
// ImageView sectionImage=(ImageView)vi.findViewById(R.id.sectionimage); // thumb image
HashMap<String, String> sectionList = new HashMap<String, String>();
sectionList = data.get(position);
// Setting all values in listview
sectionName.setText(sectionList.get(GroupSectionActivity.msectionname));
return vi;
}
}
activity_group_section.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">
<ImageView
android:id="#+id/sectionimage"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:scaleType="fitXY"
android:src="#drawable/sectionbackground"
/>
</FrameLayout>
<TextView
android:id="#+id/sectionname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textView"
android:visibility="visible"
android:gravity="center"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
sectionlayout.xml :
<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"
tools:context="{relativePackage}.${activityClass}" >
<ListView
android:id="#+id/seclist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/sectionAddButton">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sectionAddButton"
android:layout_alignParentTop="true"
android:background="#drawable/sectionbackground"
android:text="Add Section" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sectionNameTextField"
android:layout_alignBottom="#+id/sectionAddButton"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/sectionAddButton"
android:hint="Section Name"
android:gravity="center"
android:layout_toRightOf="#+id/sectionAddButton" />
</RelativeLayout>
I hope the question is clear, if there is anything missing, kindly let me know.
If you want to display the notes in a dynamic way, you should implement a GridView inside each container, if you set the right margin to each note inside the Grid, the component will dimension itself to fit your section.
The GridView adapter is really simple, works just like the ListView adapter, you will just need to define the number of columns, you can do this in the XML, or programmatically in your Java code.
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"/>
First let me point out that Thomaz is right and you should use a GridView.
It's the right way to go both for your needs and ease of use, but more importantly for it's ability to recycle it's views.
If you won't use any form of view recycling you might get out of memory exception.
But now you face another problem: you want it to be shown in sections.
Why is that a problem? Because:
A) Both the ListView and the GridView do recycling with their child views, and now that each child view of the ListView is a single GridView, which holds inside of it more Views, it's a pretty complex thing to manage. No impossible, but pretty complex.
B) Because of the fact that both the ListView and the GridView are scrollable (and because of that fact are recyclable) there is an issue of scrolling inside scrolling that needs to be resolved.
Luckily I cam across an answer: SuperSLiM (Formally StickyGridHeaders).
This should provide you with an easy solution which suites your needs.
Good luck.
I've been dealing with this for a few weeks now. I've already seen all other related questions and it does not help. I'm trying to populate a custom ListView and can't for the life of me get it to work. I'll post all the relevant information hoping someone will notice my mistake.
Activity Layout:
<?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="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#000000">
<ListView
android:id="#+id/deviceListView"
android:layout_width="400px"
android:layout_height="fill_parent"
android:textColor="#ffffff"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
</LinearLayout>
Custom Row layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#000000">
<TextView android:id="#+id/textId"
android:textSize="50sp"
android:text="ID"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView android:id="#+id/textTimestamp"
android:textSize="16sp"
android:text="Timestamp"
android:textColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
android:layout_height="wrap_content"/>
<TextView android:id="#+id/textCoordinates"
android:textSize="16sp"
android:text="Coordinates"
android:textColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/textDistance"
android:textSize="16sp"
android:text="Distance"
android:textColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
Adapter model:
public class DeviceList {
public static ArrayList<Device> list;
public static void loadModel(int quantity) {
ArrayList<Device> listTmp = new ArrayList<Device>();
for (int i = 0; i < quantity; i++) {
listTmp.add(new Device(System.currentTimeMillis(), i, new float[]{0, 0}, System.currentTimeMillis() / (i + 1)));
}
list = listTmp;
}
public static Device GetById(int id){
Device tmp = null;
for(Device device : list){
if (device.getID() == id){
tmp = device;
}
}
return tmp;
}
}
Adapter:
public class DeviceArrayAdapter extends ArrayAdapter<Device> {
private Context context;
private int rowResourceId;
private String[] ids;
public DeviceArrayAdapter(Context context, int rowResourceId, String[] devices) {
super(context, rowResourceId);
this.context = context;
this.ids = devices;
this.rowResourceId = rowResourceId;
}
#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.device_row, parent, false);
TextView idTextview = (TextView) rowView.findViewById(R.id.textId);
TextView timeStampTextview = (TextView) rowView.findViewById(R.id.textTimestamp);
TextView coordinatesTextview = (TextView) rowView.findViewById(R.id.textCoordinates);
TextView distanceTextview = (TextView) rowView.findViewById(R.id.textDistance);
int id = Integer.parseInt(ids[position]);
timeStampTextview.setText(Long.toString(DeviceList.GetById(id).getTimestamp()));
idTextview.setText(DeviceList.GetById(id).getID());
coordinatesTextview.setText(DeviceList.GetById(id).getCoordinates()[0] + "," + DeviceList.GetById(id).getCoordinates()[1]);
distanceTextview.setText(DeviceList.GetById(id).getDistance() + "");
return rowView;
}
}
And finally the Activity's onCreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setContentView(R.layout.activity_main);
// ArrayList<Device> list = createDummyDeviceList(5);
DeviceList.loadModel(5);
String[] ids = new String[DeviceList.list.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
ListView listView = (ListView) findViewById(R.id.deviceListView);
DeviceArrayAdapter adapter = new DeviceArrayAdapter(this, R.layout.device_row, ids);
listView.setAdapter(adapter);
}
Note: I'm sorry to post like this but I'm desperate. I've already debugged it up to the last line and everything is loaded and there are no Exceptions. But it just won't populate.
[EDIT]
Together with the selected answer I also had different numbered arrays and ids. The ids I generated started from 1 and not 0.
You never pass the dataset to the super class. Change
super(context, rowResourceId);
with
super(context, rowResourceId, devices);
this way the getCount of the ArrayAdapter, returns the devices length and the getView would be invoked. Also to avoid waste of memory and better performance, you should inflate the convertView only once.
Edit. The super is expecting an Array or ArrayList of Device objects. Instead your devices in a String array. Your choice should be consistent. You can either change
extends ArrayAdapter<Device>
with
extends ArrayAdapter<String>
or pass as paramter a Device[] as parameter to your custom Adapter. For instance
public DeviceArrayAdapter(Context context, int rowResourceId, Device[] devices) {
Check sources of ArrayAdapter http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r2.1/android/widget/ArrayAdapter.java#ArrayAdapter.getCount%28%29
In your case you should override method getCount().
What I am trying to accomplish is to have a checkbox in each row, having the ability to check the box separately (for batch deleting) and being able to select the entire row to view data associated with the list item.
I have done a checkbox with a textview but that only lets be select the box and I cant click on the list item to view that items data. I also used checkedTextView but that checks the box where ever you click on the row calling the onListItemClick and thats not what I want either. Is there some what I can separate checking the box from clicking a listview item?
Pretty much trying to do what the gmail app does when selecting messages to delete and view
this is my row layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/nameCheckTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:paddingTop="5dp"
android:paddingLeft="15dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
creating listview
#Override
public void onActivityCreated(Bundle state){
super.onActivityCreated(state);
lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setItemsCanFocus(false);
setEmptyText("No Bowlers");
registerForContextMenu(getListView());
populateList();
}
EDIT:
my populate method
public void populateList(){
String[] fields = new String[] {BowlersDB.NAME};
//mAdapter = new CheckAdapter(getActivity(),R.layout.check_listview,null,fields,new int[] {R.id.nameCheckTV});
mAdapter = new SimpleCursorAdapter(getActivity(),R.layout.check_listview,null,fields,
new int[] {R.id.nameCheckTV});
setListAdapter(mAdapter);
getLoaderManager().initLoader(0,null,this);
}
The issue is that Android doesn't allow you to select list items that have elements on them that are focusable. Try modifying the checkbox on the list item:
android:focusable="false"
I had a strange workaround with this issue. Here is my solution.
Use this for your ListView. Product is just a model object to hold your data in this case:
public class CatalogItemAdapter extends ArrayAdapter<Product> //
{
private ArrayList<Product> products;
private Activity activity;
public CatalogItemAdapter(Context context, int textViewResourceId,
ArrayList<Product> items, Activity activity) //
{
super(context, textViewResourceId, items);
this.products = items;
this.activity = activity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) //
{
Product product = products.get(position);
if (convertView == null) //
{
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.catalog_item_stub, null, false);
}
}
}
Somewhere in your onResume(), put this:
listView = (ListView) activity.findViewById(R.id.CatalogProducts);
m_adapter = new CatalogItemAdapter(activity,
R.layout.catalog_item_stub, products, activity);
if (products == null)
products = new ArrayList<Product>();
listView.setAdapter(m_adapter);
R.layout.catalog_item_stub is a layout stub created in XML like so (put the appropriate items in it for you, like the checkbox):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="#+id/catalog_item_stub"
android:layout_width="match_parent" android:layout_height="90dp"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dp">
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent" android:weightSum="5"
android:gravity="center_vertical|right">
<TextView android:layout_width="0dp" android:layout_height="match_parent"
android:text="product_title" android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/ProductTitle" android:padding="5dp"
android:layout_weight="2.5" android:textColor="#000000" />
<CheckBox android:padding="5dp" android:layout_height="match_parent"
android:text="select" android:layout_width="0dp" android:id="#+id/chkSelect"
android:layout_weight="1.5" android:textColor="#000000"
android:gravity="right" />
</LinearLayout>
Hopefully this helps! Holler if you need any clarification.
The gmail app uses its own view called CanvasConversationHeaderView that manages its subviews. This method is probably more heavy-weight than what you are looking for.
An easier method would be to make the checkbox not "focusable" (as Alex Lockwood suggests) and then attach an onClick in the XML.
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:focusable="false"
android:onClick="onCheckboxClicked"/>
Then in your activity code add
public void onCheckboxClicked(View view) {
RelativeLayout rl = (RelativeLayout)view.getParent();
Log.d(TAG, "Checkbox clicked! getTag returned: " + rl.getTag());
}
EDIT: How to add a tag from SimpleCursorAdapter.bindView
private class MyCursorAdapter extends SimpleCursorAdapter {
public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//Log.d(TAG, "Cursor pos: " + cursor.getPosition());
String name = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
view.setTag(name);
super.bindView(view, context, cursor);
}
}
Note: I set the tag to the View from the bindView call, which is the RelativeLayout at the root of your xml. Look at the onCheckboxClicked method to see how I got the tag.
You need to set an onItemClickListener for your ListView that will start another activity with the info of the row selected when the row is clicked (outside the CheckBox of course). I would recommend having your Activity implement AdapterView.OnItemClickListener which requires the method
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
Inside this method you can launch an Activity with details corresponding to the data in the row selected.
Hopefully I understood your question correctly.