I want to display Arraylist items in Gridview. My Arraylist is like this :
1 Hello Hello
2 Hello Hello
If I bind it to a gridview control like this :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, event_list);
gridview.setAdapter(adapter);
event_List is my Arraylist. Through this approach I get a complete Arraylist row or record in a cell of gridview . I want to display each item like "Hello" of Arraylist in each cell of gridview. Like 1 in one cell , "Hello" in another cell and so on.
Thanks in advance
Seems You need to use BaseAdapter, because default ArrayAdapter is not able to accomplish dividing of ArrayList element into number of elements.
So, it would look like the following:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final GridView grid = (GridView) findViewById(R.id.gridView);
final ArrayList<String> items = new ArrayList<String>();
items.add("1 , Hello11 , Hello12");
items.add("2 , Hello21 , Hello22");
grid.setAdapter(new GridAdapter(items));
}
// Assume it's known
private static final int ROW_ITEMS = 3;
private static final class GridAdapter extends BaseAdapter {
final ArrayList<String> mItems;
final int mCount;
/**
* Default constructor
* #param items to fill data to
*/
private GridAdapter(final ArrayList<String> items) {
mCount = items.size() * ROW_ITEMS;
mItems = new ArrayList<String>(mCount);
// for small size of items it's ok to do it here, sync way
for (String item : items) {
// get separate string parts, divided by ,
final String[] parts = item.split(",");
// remove spaces from parts
for (String part : parts) {
part.replace(" ", "");
mItems.add(part);
}
}
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(final int position) {
return mItems.get(position);
}
#Override
public long getItemId(final int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View view = convertView;
if (view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
final TextView text = (TextView) view.findViewById(android.R.id.text1);
text.setText(mItems.get(position));
return view;
}
}
}
Will produce grid with six items. See more in corresponding Android Guide for Grid View.
Or you maybe use this:
MainActivity.java:
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> values=new ArrayList<String>();
values.add("Home");values.add("About");values.add("Contact");values.add("Help");values.add("Index");
values.add("Home");values.add("About");values.add("Contact");values.add("Help");values.add("Index");
GridView myGrid=(GridView)findViewById(R.id.grid);
myGrid.setAdapter(new ArrayAdapter<String>(this,R.layout.cell,values));
}
}
Your activity_main.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mySelection" />
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/grid"
android:columnWidth="75dip"
android:gravity="center"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="75dip">
</GridView>
Create a new xml file in layout folder and name it cell.xml and put this in it:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp">
Now run and enjoy. This is output:
Related
how can i make a listView that only contains images and nothing else. i am new to the listView and all that adapter stuff. i succeed in making a listView containing text only but unable to do this with images.
this is what i have done so far.
My MainActivity Class
public class MainActivity extends AppCompatActivity {
ListView listView;
ImageView imageView;
int[] imageIds = {R.drawable.chrysanthemum, R.drawable.desert, R.drawable.hydrangeas, R.drawable.jellyfish};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, R.layout.imageview, imageIds);
listView.setAdapter(adapter);
}
}
Main XML code
<RelativeLayout 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="com.example.danishrizvi.myapplication.MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
ImageView Layout File
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
the error arises in this line ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, R.layout.imageview, imageIds); that is Unable to Resolve Constructor.
so far what i have learned about my mistake by searching on the internet is that i might need a custom adapter or something similar to get my job done but was unable to know that how to implement and how that works.
layout_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ImageAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> arrayList;
public ImageAdapter(Context mContext, ArrayList<String> arrayList) {
this.mContext = mContext;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.layout_adapter, parent, false);
ImageView imgAdapter = (ImageView) convertView.findViewById(R.id.img_adapter);
Glide.with(mContext).load(arrayList.get(position)).into(imgAdapter);
return convertView;
}
}
Use this in activity like this,
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("image url");
arrayList.add("image url");
arrayList.add("image url");
ImageAdapter imageAdapter = new ImageAdapter(this, arrayList);
listView.setAdapter(imageAdapter);
sample code is here:
https://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Ii is showing row with image and text. So you can modified it according to your requirement.
So I have a Listview full of rows, each with a textview and a spinner. I use an ArrayAdapter to fill in each row. There is a single layout for all the rows.
I want to have a button underneath all the rows that I can press so that it saves all the selections of the spinners in a Text file.
My problem though is I dont know how to reference the spinners anymore since I use the single layout approach. I no longer have unique IDs: (spinner1, spinner2, spinner3, etc.) for each one because they are filled in row by row.
Any advice on how to approach this problem so I can reference each spinner and call their "get text" method?
The more detail the better, thanks in advance!
This is how I would do it: If the model object type of your array doesn't have a variable for the current spinner selection, you need to update your model or extend your Adapter so that you can capture the current selection of the spinner for that item.
In your adapter's getView(), when you create the spinner, add an OnItemSelectedListener to it that updates the model for its corresponding item in the array.
Then when the save button is pressed, you simply loop through the items in the adapter's array and get all the current spinner values.
Here is a code example:
MainActivity.java
package com.example.spinnerdemo;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final String[] mValues = {
"Strongly Agree",
"Agree",
"Neutral",
"Disagree",
"Strongly Disagree"
};
public static class MyModel {
public String text;
public int spinnerVal;
public MyModel(String txt, int val) {
text = txt; spinnerVal = val;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<MyModel> items = createItemList();
ListView listView = (ListView) findViewById(R.id.listView1);
final MyListAdapter adapter = new MyListAdapter(this, items);
listView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// here is where we get all the spinner values
Log.d(TAG, "------- save button clicked");
for (MyModel model : items) {
Log.d(TAG, model.text + " : " + mValues[model.spinnerVal]);
}
Log.d(TAG, "-------");
}
});
}
public static class MyListAdapter extends ArrayAdapter<MyModel> {
public MyListAdapter(Context context, List<MyModel> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
final MyModel model = (MyModel) getItem(position);
TextView textView = (TextView) convertView.findViewById(R.id.textView1);
textView.setText(model.text);
Spinner spinner = (Spinner) convertView.findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(parent.getContext(),
android.R.layout.simple_spinner_dropdown_item,
android.R.id.text1, mValues));
// here is where the spinner gets the value from the model
spinner.setSelection(model.spinnerVal);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// here is where we update the model with the current position of the spinner
model.spinnerVal = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return convertView;
}
}
private List<MyModel> createItemList() {
List<MyModel> items = new ArrayList<MyModel>();
// initialize with "Neutral" spinner setting
items.add(new MyModel("question 1", 2));
items.add(new MyModel("question 2", 2));
items.add(new MyModel("question 3", 2));
items.add(new MyModel("question 4", 2));
items.add(new MyModel("question 5", 2));
return items;
}
}
activity_main.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="com.example.spinnerdemo.MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Save" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
I followed all the steps from various sources for getting listviews to work but my one
doesn't seem to display anything. This list view code(shown below) is activated with a tab fragment manager I won't put that here as to not bog you all down with code as there's a lot here already. It is most likely a problem with the ListFragment itself but I suppose it could be the adapter.
What happens is nothing gets displayed at all just the searchview that I have put in the main xml layout. I can switch freely between tabs with no crashes but just nothing displays in any of my listviews. I have another list which is a friends list(not included in this code snippet) and that uses a generic view holder interface and that one does not work either which suggests the problem is most likely in my ListFragment but I just can't pinpoint it. Any help is appreciated and I hope some can learn something from this, Thank you.
This is my adapter for the settings category list
package codeblox.com.listfragmentexample;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import codblox.com.listfragmentexample.R;
public class SettingsAdapter extends ArrayAdapter<Settings.SettingsCategories>
{
private final Activity context;
String[] text;
ArrayList<Settings.SettingsCategories> itemsCopy;
class ViewHolder
{
public TextView txt;
public CheckBox state;
public ImageView settingImg;
public EditText input;
public ToggleButton toggle;
public Button settingInfo; // click it to show what the setting does
}
public SettingsAdapter(Context context, ArrayList<Settings.SettingsCategories> items)
{
super(context, R.layout.settings_category_row, items);
this.context = (Activity) context;
this.itemsCopy = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = new ViewHolder();
int viewType = this.getItemViewType(position);
if(convertView == null)
{
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.settings_category_row, parent, false);
// initialize the view holder
holder = new ViewHolder();
holder.settingImg = (ImageView) convertView.findViewById(R.id.settingCategoryImg);
holder.txt = (TextView) convertView.findViewById(R.id.settingCategoryName);
convertView.setTag(holder);
} else {
// recycle the already inflated view
holder = (ViewHolder) convertView.getTag();
}
// fill data
holder = (ViewHolder) convertView.getTag();
String s = getItem(position).toString();
holder.txt.setText(itemsCopy.get(position).getSettingText());
holder.settingImg.setImageResource(itemsCopy.get(position).getImgResId());
return convertView;
}
}
This is my list fragment
package codeblox.com.listfragmentexample
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import codeblox.com.listfragmentexample.R;
public class Settings extends ListFragment implements View.OnLongClickListener
{
private ListView settingsList;
private ArrayList<SettingsCategories> mItems;
private ArrayAdapter<SettingsCategories> settingsAdapter;
private int numCategories;
String[] CategoryArray = new String[] {"Privacy and Security","Account","Networks","Camera Options","Storage","Accesibility","Features"};
int[] resIds = new int[] {R.drawable.security_settings_icon,R.drawable.account_settings_icon,
R.drawable.network_settings_icon,R.drawable.camera_settings_icon,R.drawable.storage_settings_icon,
R.drawable.accessibility_settings_icon,R.drawable.feature_settings_icon,};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View settingsView = inflater.inflate(R.layout.settings, container, false);
settingsList = (ListView)settingsView.findViewById(android.R.id.list);
// initialize the items list
return settingsView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
public Settings()
{
this.numCategories = CategoryArray.length;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public boolean onLongClick(View v)
{
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Object i = l.getItemAtPosition(position);
}
public class SettingsCategories
{
private String settingText;
private int imgResId;
SettingsCategories(String settingText,int imgResId)
{
this.settingText = settingText;
this.imgResId = imgResId;
}
public String getSettingText()
{
return this.settingText;
}
public int getImgResId()
{
return this.imgResId;
}
}
}
and finally these are my xml layouts (the first one is the main view and the second one is the view of a single item in the list
<?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="fill_parent"
android:orientation="vertical"
>
<SearchView
android:id="#+id/searchFunction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</SearchView>
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
this represents an individual item in the list
<?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"
>
<ImageView
android:layout_width="52dp"
android:layout_height="52dp"
android:id="#+id/settingCategoryImg"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="52dp"
android:text=""
android:id="#+id/settingCategoryName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/settingCategoryImg"
/>
</RelativeLayout>
You are setting null adapter so it is not refreshing.
you are commented initialization part
check in the following method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
Your are using ListFragement and again inflating layout. that is not a good idea. when you are extending listfragment then inflating the layout is not required and and modify above method like:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
//setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
I am new to android programming and am looking to implement a gallery which has a grid view that then pushes on to a view pager but I am having a few problems getting this to work. I have it working currently just using a static Image Adapter but am not sure how to change this to use a view pager instead. I also want to be able to add my own titles to each screen but I wasn't sure how to do this or whether it had to be the image name that would appear?
The code I have at the moment is...
the .xml with the grid view
<?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:background="#3d3d3e" >
<GridView
android:id="#+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/phone"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
</RelativeLayout>
the grid view .java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class Marble extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.marble);
GridView gridView = (GridView) findViewById(R.id.gridview1);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter1(this));
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity1.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
}
the image adapter .java
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter1 extends BaseAdapter {
private Context mContext;
// Keep all Images in array
Integer[] mThumbIds = {
R.drawable.arabescato, R.drawable.biancocarrara,
R.drawable.botticinoclassico, R.drawable.calacattaoro,
R.drawable.cremamarfil, R.drawable.cremavalencia,
R.drawable.emperadordark, R.drawable.jurabeige,
R.drawable.neromarquina, R.drawable.perlatoolympo,
R.drawable.rojoalicante
};
// Constructor
public ImageAdapter1(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(265, 265));
return imageView;
}
}
and finally the image activity .java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class FullImageActivity1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter1 imageAdapter1 = new ImageAdapter1(this);
ImageView imageView = (ImageView) findViewById(R.id.fullimage);
imageView.setImageResource(imageAdapter1.mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
All help on this will be massively appreciated as I'm absolutely stumped!
Thanks in advance!
Before you proceed, add the android.support.v4 jar file to your project.
You need 2 things: the ViewPager in your layout, and an adapter that extends PagerAdapter
First change your full_image.xml layout to this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Then create an adapter that extends PagerAdapter (required by ViewPager)
public class ImagePagerAdapter extends PagerAdapter {
private List<ImageView> images;
public ImagePagerAdapter(List<ImageView> images) {
this.images = images;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = images.get(position);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(images.get(position));
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
}
In your FullImageActivity1 class:
public class FullImageActivity1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// Loop through the ids to create a list of full screen image views
ImageAdapter1 imageAdapter1 = new ImageAdapter1(this);
List<ImageView> images = new ArrayList<ImageView>();
for (int i = 0; i < imageAdapter1.getCount(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imageAdapter1.mThumbIds[i]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
images.add(imageView);
}
// Finally create the adapter
ImagePagerAdapter imagePagerAdapter = new ImagePagerAdapter(images);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(imagePagerAdapter);
// Set the ViewPager to point to the selected image from the previous activity
// Selected image id
int position = getIntent().getExtras().getInt("id");
viewPager.setCurrentItem(position);
}
}
The general idea is to create an adapter that extends PagerAdapter to supply data to the ViewPager. For more information, you can visit Android Docs on PagerAdapter
I have created a Dynamic LinearLayout and I want to add these layouts to ListView. The code is as follows:
DynamicLayout code:
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DynamicContentLayout extends LinearLayout{
private Context context;
private int linearLayoutMargin;
public DynamicContentLayout(Context context) {
super(context);
this.context = context;
linearLayoutMargin = (int) context.getResources().getDimension(R.dimen.xlarge_margin_padding_fixed);
initViews();
}
private void initViews() {
LinearLayout.LayoutParams layout_lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout_lp.setMargins(linearLayoutMargin, linearLayoutMargin, linearLayoutMargin, linearLayoutMargin);
this.setLayoutParams(layout_lp);
this.setOrientation(LinearLayout.VERTICAL);
this.addView(headerTitle("My Text"));
}
private TextView headerTitle(String title) {
TextView txtView = new TextView(context);
txtView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
txtView.setPadding(6, 6, 6, 6);
txtView.setText(title);
txtView.setBackgroundColor(context.getResources().getColor(R.color.red));
txtView.setTextColor(context.getResources().getColor(R.color.white));
return txtView;
}
}
ListAdpaterCode:
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class ListViewAdapter extends ArrayAdapter<DynamicContentLayout> {
private Context context;
private ArrayList<DynamicContentLayout> layoutList = null;
public ListViewAdapter(Context context, int textViewResourceId, ArrayList<DynamicContentLayout> layoutList) {
super(context, textViewResourceId, layoutList);
this.context = context;
this.layoutList = layoutList;
}
#Override
public int getCount() {
return layoutList.size();
}
#Override
public DynamicContentLayout getItem(int position){
return layoutList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DynamicContentLayout entry = (DynamicContentLayout) layoutList.get(position);
convertView = (View) entry;
return convertView;
}
}
Finally the code in the MainActivity where I am setting the Adapter:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
ArrayList<DynamicContentLayout> contents = new ArrayList<DynamicContentLayout>();
contents.add(new DynamicContentLayout(getApplicationContext()));
contents.add(new DynamicContentLayout(getApplicationContext()));
contents.add(new DynamicContentLayout(getApplicationContext()));
ArrayAdapter<DynamicContentLayout> arrayAdapter = new ArrayAdapter<DynamicContentLayout>(getApplicationContext(), android.R.layout.simple_list_item_1, contents);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
Xml Layout:
<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"
>
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:background="#color/blue"
android:layout_height="fill_parent"
android:alwaysDrawnWithCache="true"
android:clickable="true"
android:layout_alignParentTop="true"
android:divider="#color/grey"
android:drawingCacheQuality="auto"
android:fastScrollEnabled="true"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:scrollbars="none" >
</ListView>
</RelativeLayout>
Now, when I run , there is no error reported. But I couldn't see listItems layouts. What I can see is name of the class only. for example: "com.myexample.dynamicontentoverview.DynamicContentLayout#405193d0" as the row of the listItem instead of the Layout.
There is one more point I want to add. I cannot use XMl Layout as my views inside my DynamicLinearLayout can increase/decrease for certain rows.
Please suggests something.
Thanks.
You got the concept of custom listViews all wrong.
You should define your custom layout in an xml layout.
The type of your array adapter shouldn't be a layout. It should be the object type you are trying to populate the listView with.
Check out this tutorial to get a better idea of the steps you should do.
You are using ArrayAdapter as your adapter for the ListView instead of your own ListViewAdapter which extends ArrayAdapter< DynamicContentLayout>
What you are seeing now is your objects toString representation, because, well, thats what the ArrayAdapter does.