I'm trying to create gridview with images using Picasso library. I'm creating fragment with gridview and set adapter to gridview, but can not see anything on display.
Here is my adapter code:
public class GridViewAdapter extends ArrayAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageUrls;
public GridViewAdapter(Context context, String[] imageUrls) {
super(context, R.layout.grid_item, imageUrls);
this.context = context;
this.imageUrls = imageUrls;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = inflater.inflate(R.layout.grid_item, parent, false);
}
Picasso
.with(context)
.load(imageUrls[position])
.fit() // will explain later
.into((ImageView) convertView);
return convertView;
}
}
Here is the code of my fragment
public class ViewMoviesFragment extends Fragment {
GridViewAdapter adapter;
public ViewMoviesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] eatFoodyImages = {
"http://i.imgur.com/rFLNqWI.jpg",
"http://i.imgur.com/C9pBVt7.jpg",
"http://i.imgur.com/rT5vXE1.jpg",
"http://i.imgur.com/aIy5R2k.jpg",
"http://i.imgur.com/MoJs9pT.jpg",
"http://i.imgur.com/S963yEM.jpg",
"http://i.imgur.com/rLR2cyc.jpg",
"http://i.imgur.com/SEPdUIx.jpg",
"http://i.imgur.com/aC9OjaM.jpg",
"http://i.imgur.com/76Jfv9b.jpg",
"http://i.imgur.com/fUX7EIB.jpg",
"http://i.imgur.com/syELajx.jpg",
"http://i.imgur.com/COzBnru.jpg",
"http://i.imgur.com/Z3QjilA.jpg",
};
View v= inflater.inflate(R.layout.grid_fragment, container, false);
GridView gridview = (GridView) v.findViewById(R.id.poster_view);
gridview.setAdapter(new GridViewAdapter(getActivity(), eatFoodyImages));
return v;
}
}
My activity code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new ViewMoviesFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
}
main_activity.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
grid_item.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
grid_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/poster_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2">
</GridView>
</FrameLayout>
When I run my app I get just white window. AndroidManifest.xml have internet permission access. Can anyone help me to show images in gridview?
The problem is in your GridViewAdapter
Picasso
.with(context)
.load(imageUrls[position])
.fit() // will explain later
.into((ImageView) convertView);
convertView is a Framelayout
Related
I am trying to add gridview for my layout.
The MainActivity contains 5 number of tabs , where first tab is AlbumsActivity.
AlbumsActivity
public class AlbumsActivity extends Fragment{
public AlbumsActivity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_albums, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
}
ImageAdapter.java
I am using this class adapter to populate the grids in AlbumsActivity.
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.splas,
R.drawable.abc,
};
// Constructor
public ImageAdapter(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(150, 150));
return imageView;
}
}
grid_layout.xml
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="3"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
activity_albums.xml
This is layout file for AlbumsActivity , where i want to show grids in page.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.example.android.musiclist.AlbumsActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/ald"
android:textSize="20sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"/>
</LinearLayout>
I think you are doing it wrong.
MainActivity - 5 Tabs and one framelayout
AlbumsActivity (Fragment) - Activity_Albums.xml (TextView, GridView)
ImageAdapter (BaseAdapter) - Custom Layout (ImageView)
3 -> 2 (Gridview) -> 1
if not you have to create, set parameters and inject gridview with custom layout to main layout programatically
//Try this
activity_albums.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.example.android.musiclist.AlbumsActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/ald"
android:textSize="20sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"/>
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
AlbumsActivity
public class AlbumsActivity extends Fragment{
private View view;
private FrameLayout fl;
private GridView gv;
public AlbumsActivity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_albums,container,false);
fl = view.findViewById(R.id.frameLayout);
gv = findViewById(R.id.grid_view);
gv.setAdapter(new ImageAdapter(this));
fl.addView(gv);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Or Something similar, I am too lazy to type everything now. just google search "android custom arrayadapter" and you will find tons of examples. It's really simple
I have created tabbed activity with two tab (edittext in tab1,listview in tab2),and I pass data in tab1 to listview in tab2, how to set title for listview
please help
my 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="store.exercise.com.store.MainActivity$PlaceholderFragment">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
fragment one:
public class FragmentOne extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_one, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
fragment two :
public class FragmentTwo extends Fragment {
ListView listView;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
}
protected void displayReceivedData(String message) {
arrayList.add(message);
adapter.notifyDataSetChanged();
}
}
my ViewPagerAdapter :
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new FragmentOne();
} else if (position == 1) {
fragment = new FragmentTwo();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = " مهمة جديدة ";
} else if (position == 1) {
title = " المهام ";
}
return title;
}
}
make sure you have the following on your activity_view.xml where you have your viewpager
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/center_section_tab_bar_header_height"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
and in your activity class add the following line to setup the viewpager with the tab layout header
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(yourviewpager);
after which it sets up the header for your tabs as mentioned in your code
I have a main Activity containing a parent Fragment, which in turn contains a child Fragment. I am trying to make a TextView in the child Fragment visible/invisible dynamically.
activity_main.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the Activity"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/parent_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_parent.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the parent fragment"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/child_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_child.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the child fragment"
android:id="#+id/textView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="But make this text visible dynamically!"
android:id="#+id/make_this_text_visible"
android:visibility="invisible"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String PARENT_TAG = "parent_tag";
private ParentFragment mParentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
mParentFragment = ParentFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.parent_container, mParentFragment, PARENT_TAG).commit();
}
else {
mParentFragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(PARENT_TAG);
}
}
}
ParentFragment.java
public class ParentFragment extends Fragment {
public static final String CHILD_TAG = "child_tag";
private ChildFragment mChildFragment;
private List<Integer> mList;
public static ParentFragment newInstance() {
Bundle args = new Bundle();
ParentFragment fragment = new ParentFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
mList = new ArrayList<Integer>();
if (savedInstanceState == null) {
mChildFragment = ChildFragment.newInstance();
getChildFragmentManager().beginTransaction().replace(R.id.child_container, mChildFragment, CHILD_TAG).commit();
}
else {
mChildFragment = (ChildFragment) getChildFragmentManager().findFragmentByTag(CHILD_TAG);
}
getChildFragmentManager().executePendingTransactions(); //doesn't seem to do anything!
doStuff();
return view;
}
void doStuff() {
mList.add(4); //pretend this is actually querying a database.
//for simplicity it just receives a single 4.
if (mList.size() > 0) { //the list is not empty, display the text!
mChildFragment.setTextVisible(); //error! the textivew of the child fragment is null right now
}
else {
mChildFragment.setTextInvisible(); //error! the textivew of the child fragment is null right now
}
}
}
ChildFragment.java
public class ChildFragment extends Fragment {
private TextView mTextView;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
return view;
}
public void setTextVisible() {
mTextView.setVisibility(View.VISIBLE);
}
public void setTextInvisible() {
mTextView.setVisibility(View.INVISIBLE);
}
}
How can I ensure that the child fragment is formed by the time I call doStuff() in the ParentFragment?
What I would do is keep the state of the text view visibility so it can be updated properly once the view has been created if it hasn't been already. Instead of separate methods for setTextVisible() and setTextInvisible have a single method setTextVisibile(boolean isVisible) and implement it as follows:
public class ChildFragment extends Fragment {
private TextView mTextView;
private boolean mIsTextVisible;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
setTextVisible(mIsTextVisible);
return view;
}
public void setTextVisible(boolean isVisible) {
mIsTextVisible = isVisible;
if(mTextView != null) {
mTextView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
}
}
and then in the parent fragment you can call doStuff() without worrying about the current state of the views in the ChildFragment since mIsTextVisible is properly set. If the mTextView is null at the time setTextVisible() is called the visibility will still be properly set in onCreateView().
Just take care to save and restore the mIsTextVisible flag when the fragment is recreated such as when the device is rotated.
Alternative Answer Using A Callback
Using callbacks update the ParentFragment to implement
ChildFragment.OnViewCreatedListener and its method.
public class ParentFragment extends Fragment
implements ChildFragment.OnViewCreatedListener {
#Override
public void onViewCreated() {
doStuff();
}
}
And then in ChildFragment
public class ChildFragment extends Fragment {
public interface OnViewCreatedListener {
void onViewCreated();
}
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
if(getParentFragment() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getParentFragment()).onViewCreated();
} else if (getActivity() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getActivity()).onViewCreated();
}
return view;
}
}
I am trying to implement the Pull to refresh feature in Android.
For this, I ended up using SwipeRefresLayout from Support library.
But it is not working as I wanted to.
I am needed to implement it inside fragment.
here is the code for fragment_home.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/group_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="45dp" />
</android.support.v4.widget.SwipeRefreshLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="bottom"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id" >
</com.google.android.gms.ads.AdView>
</FrameLayout>
</LinearLayout>
And this is the fragment placed inside the MainActivity.java
public static class HomeFragment extends Fragment {
public static final String ARG_CATEGORY_NUMBER = "category_number";
private UiLifecycleHelper uiHelper;
public int currentimageindex = 0;
private SwipeRefreshLayout swipeLayout;
public HomeFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
//SWIPE TO REFRESH
swipeLayout = (SwipeRefreshLayout) container.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener((OnRefreshListener) getActivity());
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
ListView hlvCategory = (ListView) rootView
.findViewById(R.id.group_content);
AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
HomeJsonData hjd = new HomeJsonData(getActivity(), hlvCategory,
mAdView, mDrawerList);
hjd.execute();
return rootView;
}
//SWIPE TO REFRESH
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
}
But this gives out the error as like it was unable to find the class for SwipeRefresh Layout.
Can you suggest me how can i implement it here??
Here in your fragment i found the problem is with set up the refresh listener
public static class HomeFragment extends Fragment implements OnRefreshListener{
public static final String ARG_CATEGORY_NUMBER = "category_number";
private UiLifecycleHelper uiHelper;
public int currentimageindex = 0;
private SwipeRefreshLayout swipeLayout;
public HomeFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
//SWIPE TO REFRESH
swipeLayout = (SwipeRefreshLayout) container.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
ListView hlvCategory = (ListView) rootView
.findViewById(R.id.group_content);
AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
HomeJsonData hjd = new HomeJsonData(getActivity(), hlvCategory,
mAdView, mDrawerList);
hjd.execute();
return rootView;
}
//SWIPE TO REFRESH
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
}
and make sure you have added supportV4 library
try as above this will help you,happy coding :)
Please refer this links, this may help
https://developer.android.com/samples/SwipeRefreshLayoutBasic/src/com.example.android.swiperefreshlayoutbasic/SwipeRefreshLayoutBasicFragment.html
http://antonioleiva.com/swiperefreshlayout/
You should implement the OnRefreshListener in your Fargment
public static class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener
and set swipeLayout.setOnRefreshListener(this);
Hi All I am Using a GridView Tool From The Android To Display The Image As A menu
I am Using this Code in A class I Name It ImageAdapter extends BaseAdapter
I've Use This Code Bellow
package com.example.gridviewtest;
import com.example.gridviewtest.R;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.content.Context;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public Integer[] mThumbIds =
{
R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7, R.drawable.pic8, R.drawable.pic9
};
public ImageAdapter(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(200, 200));
return imageView;
}
}
I try to use a
imageView.setText("Something");
but it doesn't Works With Me
the require is to add a caption under a picture in a cell
Can You Help Me On This ...
Best Regards ...
You could use a custom adapter (as for a listView):
public class CustomAdapter extends ArrayAdapter<Integer> {
Activity context;
ArrayList<Integer> objects;
public CustomAdapter(Activity context, ArrayList<Integer> objects) {
super(context, R.layout.row, objects);
this.context = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row, parent, false);
}
ImageView i = (ImageView) convertView.findViewById(R.id.icon);
i.setBackgroundResource(objects.get(position));
TextView t = (TextView) convertView.findViewById(R.id.title);
t.setText("title");
return convertView;
}
}
And of course you will set this it as an adapter for the gridView.
EDIT: Of course instead of ArrayAdapter<Integer> you could be extending ArrayAdapter<YourHolder>.
class YourHolder {
public int ID;
public String title;
}
EDIT 2: Adding a functional piece of code.
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=".MainActivity" >
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:gravity="center_horizontal"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:padding="10dp"
android:background="#600000ff"
/>
</RelativeLayout>
grid_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#6000ff00"
android:padding="4dp">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="label"
android:layout_gravity="center_horizontal"/>
<FrameLayout
android:id="#+id/holder"
android:layout_width="100dp"
android:layout_height="100dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
</FrameLayout>
</LinearLayout>
CustomAdapter.class
public class CustomAdapter extends ArrayAdapter<Integer> {
private Activity context;
private ArrayList<Integer> objects;
public CustomAdapter(Activity context, ArrayList<Integer> objects) {
super(context, R.layout.grid_item_layout, objects);
this.context = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater i = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = (View) i.inflate(R.layout.grid_item_layout, parent, false);
}
TextView t = (TextView) convertView.findViewById(R.id.label);
ImageView i = (ImageView) convertView.findViewById(R.id.image);
t.setText("label " + position);
i.setImageResource(objects.get(position));
return convertView;
}
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView g = (GridView) findViewById(R.id.grid_view);
CustomAdapter adapter = new CustomAdapter(this, getData());
g.setAdapter(adapter);
}
public ArrayList<Integer> getData(){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(R.drawable.pic1);
// add 2 - 11
list.add(R.drawable.pic12);
return list;
}
}
Final look:
Note: From my experience when there are a lot of pictures in the gridView scrolling becomes slow and laggy, however it's not the topic of your question, so in case it's also a problem, please see Lazy load of images in ListView