I wish to display albums in grid with Album art, album name and number of songs.
These are my xml layouts:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/content_frame"
android:layout_height="match_parent"
android:background="#color/metalList">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid"
android:layout_width="fill_parent"
android:numColumns="auto_fit"
android:layout_height="wrap_content"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:layout_gravity="right|top"/>
</FrameLayout>
and for individual items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="160dp"
android:layout_height="200dp"
android:orientation="vertical"
android:background="#color/metalList"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:elevation="4dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/albumart"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_gravity="top"
android:layout_margin="0dp"
android:src="#drawable/musicicon"
/>
<TextView
android:id="#+id/album_name"
android:layout_height="25dp"
android:layout_width="match_parent"
android:textColor="#color/metalTextB"
android:layout_below="#id/albumart"
android:layout_marginLeft="5dp"
android:textSize="16sp"
android:typeface="sans"
android:text="Album"
android:scrollHorizontally="true"
android:ellipsize="end"
android:maxLines="1"/>
<TextView
android:id="#+id/songs_num"
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_below="#id/album_name"
android:layout_marginLeft="5dp"
android:textColor="#color/metalTextS"
android:textSize="10sp"
android:text="artist"
android:typeface="sans"
android:scrollHorizontally="true"
android:ellipsize="end"
android:maxLines="1"/>
</LinearLayout>
Here are the codes for the Fragment and Activity
Albums.java
public class Albums extends Fragment implements LoaderManager.LoaderCallbacks {
AlbumsAdapter mAdapter;
private static final String ARG_POSITION = "position";
private int position;
public static Albums newInstance(int position) {
Albums f = new Albums();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.albums, container, false);
GridView grid = (GridView) this.getActivity().findViewById(R.id.grid);
mAdapter = new AlbumsAdapter(getActivity(), null);
grid.setAdapter(mAdapter);
return myFragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
}
static final String[] ALBUM_SUMMARY_PROJECTION = { MediaStore.Audio.Albums._ID,MediaStore.Audio.Albums.ALBUM_ART, MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ARTIST};
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String select = null;
return new CursorLoader(getActivity(), MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,ALBUM_SUMMARY_PROJECTION, select, null, null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
public class AlbumsAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public AlbumsAdapter(Context context, Cursor c) {
super(context, c);
mInflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView albumArt = (ImageView) view.findViewById(R.id.albumart);
albumArt.setScaleType(ImageView.ScaleType.FIT_XY);
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
Bitmap img = BitmapFactory.decodeFile(path);
if(img !=null)
albumArt.setImageBitmap(img);
else{
Bitmap bit = getDefaultAlbumArt(context);
albumArt.setImageBitmap(bit);
}
TextView albumTitle = (TextView) view.findViewById(R.id.album_name);
albumTitle.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM)));
TextView artistName = (TextView) view.findViewById(R.id.songs_num);
artistName.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ARTIST)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.grid_item, parent, false);
return view;
}
public Bitmap getDefaultAlbumArt(Context context) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try {
bm = BitmapFactory.decodeResource(context.getResources(),
R.drawable.musicicon, options);
} catch (Error ee) {
} catch (Exception e) {
}
return bm;
}
}
AlbumsAdapter.java
public class AlbumsAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public AlbumsAdapter(Context context, Cursor c) {
super(context, c);
mInflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView albumArt = (ImageView) view.findViewById(R.id.albumart);
albumArt.setScaleType(ImageView.ScaleType.FIT_XY);
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
Bitmap img = BitmapFactory.decodeFile(path);
if(img !=null)
albumArt.setImageBitmap(img);
else{
Bitmap bit = getDefaultAlbumArt(context);
albumArt.setImageBitmap(bit);
}
TextView albumTitle = (TextView) view.findViewById(R.id.album_name);
albumTitle.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM)));
TextView artistName = (TextView) view.findViewById(R.id.songs_num);
artistName.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ARTIST)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.grid_item, parent, false);
return view;
}
public Bitmap getDefaultAlbumArt(Context context) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try {
bm = BitmapFactory.decodeResource(context.getResources(),
R.drawable.musicicon, options);
} catch (Error ee) {
} catch (Exception e) {
}
return bm;
}
}
I am getting a "java.lang.NullPointerException" with these codes.
Can you please change same as below ?
View myFragmentView = inflater.inflate(R.layout.albums, container, false);
GridView grid = (GridView) this.getActivity().findViewById(R.id.grid);
to
View myFragmentView = inflater.inflate(R.layout.albums, container, false);
GridView grid = (GridView) myFragmentView.findViewById(R.id.grid);
Reason:
In fragment you have to bind child view to fragment view.
Done
Related
setOnItemClickListener() not working on gridView in Fragment
I have a gridview inside A Fragment I hae set a onItemClick for that , however it does not work
I have tried android:descendantFocusability="blocksDescendants" but still its not clicked
here is the code
public class ImageGalfrag extends Fragment {
private Cursor cursor;
private int columnIndex;
ImageView thumbV;
ImageButton videoICON;
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
// #Override
// public void onCreate(Bundle savedInstanceState) {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.gallery_gridview, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//setContentView(R.layout.gallery_gridview);
try {
String[] projection = {MediaStore.Images.Thumbnails._ID};
cursor = getActivity().managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
MediaStore.Images.Thumbnails.IMAGE_ID);
View v = getView();
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView sdcardImages = (GridView) v.findViewById(R.id.PhoneImageGrid);
sdcardImages.setAdapter(new ImageAdapter(getActivity()));
sdcardImages.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
String[] projection = {MediaStore.Images.Media.DATA};
cursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
String imagePath = cursor.getString(columnIndex);
Toast.makeText(getActivity(), "" + imagePath, Toast.LENGTH_SHORT).show();
ImageAdd(imagePath);
Intent ImageIntent = new Intent(getActivity(), ZoomImageView.class);
ImageIntent.putExtra("ImageName", imagePath);
getActivity().startActivity(ImageIntent);
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public void ImageAdd(String imagePath){
try {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
bitmapArray.add(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
private class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount() {
return cursor.getCount();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
View grid = null;
try {
LayoutInflater inflater = getActivity().getLayoutInflater();
if (convertView == null) {
try {
cursor.moveToPosition(position);
int imageID = cursor.getInt(columnIndex);
//grid = new View(mContext);
grid = inflater.inflate(R.layout.gallery_view, null);
//TextView textView = (TextView) grid.findViewById(R.id.grid_text);
thumbV = (ImageView) grid.findViewById(R.id.thumbImage);
thumbV.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
videoICON = (ImageButton) grid.findViewById(R.id.videoICON);
//textView.setText("");
} catch (Exception e) {
e.printStackTrace();
}
} else {
grid = (View) convertView;
}
} catch (Exception e) {
e.printStackTrace();
}
return grid;
}
}
}
and the Layout is
<?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:descendantFocusability="blocksDescendants"
>
<GridView
android:id="#+id/PhoneImageGrid"
android:numColumns="2"
android:gravity="center"
android:columnWidth="250dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></GridView>
</RelativeLayout>
Grid Item is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_gallery1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:id="#+id/fragment_gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#455569"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/thumbImage"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_gravity="center_horizontal"
android:background="#CCCCCC"
android:scaleType="fitXY"
android:layout_margin="5dp"
android:src="#mipmap/ic_launcher" />
<ImageButton
android:id="#+id/videoICON"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#+id/thumbImage"
android:layout_gravity="center_horizontal"
android:layout_marginTop="0dp"
android:background="#00000000"
android:scaleType="fitXY" />
</LinearLayout>
</LinearLayout>
Don't use an ItemClickListener.
In your getView() method, in your adapter. Do this:
#Override
public View getView(final int position ...
grid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do something
}});
Listing all the songs read form external storage. On clicking a song it should go to SecondActivity.java
MainActivity.java
public class MainActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.example.shubham.hymnattune";
private List peers = new ArrayList();
private MainActivity.MediaCursorAdapter mediaAdapter = null;
private String currentFile = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
}
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra(EXTRA_MESSAGE,currentFile);
startActivity(intent);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long duratioInMs = Long.parseLong(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) duratioInMs / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
};
Receive the song selected in MainActivity.java and play it.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
//private MainActivity.MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekBar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;
private final Handler handler = new Handler();
// private final IntentFilter intentFilter = new IntentFilter();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
selectedFile = (TextView) (findViewById(R.id.selectedfile));
seekBar = (SeekBar) (findViewById(R.id.seekbar));
playButton = (ImageButton) (findViewById(R.id.play));
prevButton = (ImageButton) (findViewById(R.id.prev));
nextButton = (ImageButton) (findViewById(R.id.next));
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekBar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
playButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
}
Intent intent=getIntent();
currentFile=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
startPlay(currentFile);
}
This is my main layout file. containing a list of songs from external storage.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.shubham.hymnattune.MainActivity">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"/>
</LinearLayout>
This is my xml file of second activity which is used for playing a song.
second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.shubham.hymnattune.SecondActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:background="#android:drawable/screen_background_light"
android:id="#+id/linear2"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/selectedfile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="middle"
android:gravity="center_horizontal"
android:singleLine="true"
android:text="No File Selected"
android:textColor="#android:color/black" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
try this
ListView list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new AdapterView.onItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Intent intent=new Intent(this,SecondActivity.class);
startActivity(intent);
}
});
I have used a code inside my adaptor class to implement on item click.. Check this code
public class LazyAdapter extends BaseAdapter {
private VideoActivity mainactivity;
private String[] result,imageId,title;
private static LayoutInflater inflater=null;
Context context;
public LazyAdapter(VideoActivity mainactivity, String[] videourls, String[] imgurls, String [] explist) {
context = mainactivity;
result = videourls;
imageId=imgurls;
title = explist;
inflater = (LayoutInflater)mainactivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(mainactivity.getApplicationContext());
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.listview, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
Glide.with(context)
.load(imageId[position])
.into(holder.img);
holder.tv.setText(title[position]);
// imageLoader.DisplayImage(result[position], holder.img);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+title[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, VideoActivity2.class);
intent.putExtra("imgid",title[position]);
intent.putExtra("videourl",result[position]);
context.startActivity(intent);
}
});
return rowView;
}
}
In this code I also have added a code to pass data on clicking each item in the list view.. Hope this one helps you
I have a custom gridView and inside it i am having two images in a relative layout . Now when i click on the gridView i want the visibility of my images to change.
MainActivity:
public class Main extends Fragment implements OnMapReadyCallback{
GridView gridview,video_gridview;
GridViewAdapter adapter;
View v;
public Main() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_main,
container, false);
gridview = (GridView)v.findViewById(R.id.sub_notify_gridView);
gridview.setNumColumns(3);
adapter = new GridViewAdapter(getActivity(),FilePathStrings,
FileNameStrings,Image_Status,time);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int
position, long id) {
//here i need to know which image has been clicked
}
});
return v;
}
MainActivity Layout:
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".35"
android:id="#+id/sub_notify_gridView">
<!--<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridViewImageid"/>-->
</GridView>
Cusotm GridView Adapter:
public class GridViewAdapter extends BaseAdapter {
// Declare variables
private Activity context;
private String[] filepath;
private String[] imageStatus;
private String Imgtime;
String[] separated;
private static LayoutInflater inflater = null;
public GridViewAdapter(FragmentActivity activity, String[] fpath, String[] fname, String[] image_status, String time) {
context = activity;
filepath = fpath;
imageStatus = image_status;
Imgtime = time;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return filepath.length;
}
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.gridview_item, null);
//TextView text = (TextView) vi.findViewById(R.id.text);
final ImageView image = (ImageView) vi.findViewById(R.id.image);
ImageView upload_image = (ImageView) vi.findViewById(R.id.upload_image);
TextView time = (TextView) vi.findViewById(R.id.textView);
time.setText(Imgtime);
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setPadding(5, 3, 5, 2); //itrb
//text.setText(filename[position]);
Bitmap ThumbImage =ThumbnailUtils.extractThumbnail
(BitmapFactory.decodeFile(filepath[position]),
128, 128);
if(imageStatus[position].equals("0")){
upload_image.setVisibility(View.VISIBLE);
}
if (filepath[position] == null){
image.setImageResource(R.drawable.imageicon);
}
else{
if (position > 4){
image.setImageBitmap(ThumbImage);
}
else{
image.setImageBitmap(ThumbImage);
}
}
return vi;
}
GridView_item Layout File:
<?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"
xmlns:custom="http://schemas.android.com/tools"
android:padding="5dip">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_alignBottom="#+id/image"
android:layout_alignRight="#+id/image"
android:layout_alignEnd="#+id/image"
android:paddingRight="5dp"
android:paddingBottom="1.5dp"
android:id="#+id/textView" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="5dp"
android:paddingBottom="1.5dp"
android:id="#+id/upload_image"
android:visibility="gone"
android:src="#drawable/accept_icon"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I have a GridView that is implemented within an Activity and a Fragment, and contain its own Adapter. It works great, until scrolling, when I try to scroll it appears to leave a background of the first items loaded.
Here's the code I am implementing:
Activity Class
public class FavoriteActivity extends ActionBarActivity {
private final String LOG_TAG = FavoriteActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new FavoriteListFragment())
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
FavoriteListFragment fragment = (FavoriteListFragment)getSupportFragmentManager().findFragmentById(R.id.container);
if ( null != fragment ) {
fragment.onRestartLoader();
}
}
}
Fragment Class
public class FavoriteListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
public static final String LOG_TAG = FavoriteListFragment.class.getSimpleName();
private static final int LOADER = 0;
private static final String SELECTED_KEY = "selected_position";
private ResultListAdapter mAdapter;
private GridView mGridView;
private int mPosition = ListView.INVALID_POSITION;
public static final String[] SMCONTENT_COLUMNS = {
SMDBContract.SMContentEntry.COLUMN_TITLE,
};
static final int COL_TITLE = 0;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
mAdapter = new ResultListAdapter(getActivity(), null, 0);
mAdapter.setIsFavoriteView(true);
View rootView = inflater.inflate(R.layout.fragment_favorite, container, false);
mGridView = (GridView) rootView.findViewById(R.id.listview_sm_content_favorite);
mGridView.setAdapter(mAdapter);
if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
mPosition = savedInstanceState.getInt(SELECTED_KEY);
}
return rootView;
}
void onRestartLoader() {
getLoaderManager().restartLoader(LOADER, null, this);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// When tablets rotate, the currently selected list item needs to be saved.
// When no item is selected, mPosition will be set to Listview.INVALID_POSITION,
if (mPosition != ListView.INVALID_POSITION) {
outState.putInt(SELECTED_KEY, mPosition);
}
super.onSaveInstanceState(outState);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String favs = Utility.getFavoritesIds(getActivity());
Uri resultSearchURI = SMDBContract.SMContentEntry
.buildSMContentMultiple(SMDBContract.CATEGORY_SERIE, favs);
Log.d(LOG_TAG,"PREFS URI: "+resultSearchURI);
return new CursorLoader(getActivity(),
resultSearchURI,
SMCONTENT_COLUMNS,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
mAdapter.setCursor(data);
if (mPosition != ListView.INVALID_POSITION) {
mGridView.smoothScrollToPosition(mPosition);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
Adapter
public class ResultListAdapter extends CursorAdapter {
private Context mContext;
private Cursor mCursor;
public ResultListAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
mContext = context;
mCursor = c;
}
public Cursor getCursor() {
return mCursor;
}
public void setCursor(Cursor mCursor) {
this.mCursor = mCursor;
}
public static class ViewHolder {
public final ImageView iconView;
public final TextView titleView;
public ViewHolder(View view) {
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
titleView = (TextView) view.findViewById(R.id.list_item_title_textView);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
if (viewHolder.iconView != null) {
Picasso.with(context)
.load(cursor.getString(ResultListFragment.COL_POSTER))
.fit()
.centerInside()
.into(viewHolder.iconView);
}
if (viewHolder.titleView != null)
viewHolder.titleView.setText(cursor.getString(ResultListFragment.COL_TITLE));
}
}
Activity Layout
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:name=".FavoriteListFragment"
tools:context=".FavoriteListFragment"
tools:layout="#android:layout/list_content" />
Fragment Layout
<FrameLayout
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="![enter image description here][1].FavoriteListFragment">
<GridView
android:id="#+id/listview_sm_content_favorite"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</FrameLayout>
Grid Item Layout
<?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">
<FrameLayout
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_gravity="center"
>
<ImageView
android:id="#+id/list_item_icon"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#mipmap/ic_launcher"/>
</FrameLayout>
<TextView
android:id="#+id/list_item_title_textView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:fontFamily="sans-serif-light"
android:layout_gravity="center"
android:textAppearance="?android:textAppearanceMedium"
android:text="My Item Title"/>
</LinearLayout>
UPDATE:
I just found out that by removing this code from the FavoriteActivity.onCreate the error stops... but why!? can somebody tell me
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new FavoriteListFragment())
.commit();
}
Remove following lines from your Grid Item Layout:
from ImageView remove:
android:src="#mipmap/ic_launcher"
from TextView remove:
android:text="My Item Title"
I am extending my class to ListFragment. Below I posted the relative.
My issue is, I didn't get any error in runtime, but in Output it still loading the page.
Output:
Administration.java:
public class Administration extends ListFragment {
int[] img = { R.drawable.project, R.drawable.user, R.drawable.group,
R.drawable.roles, R.drawable.news, R.drawable.document };
private String item[] = { "Project", "Users", "Group",
"Roles and Permission", "News", "Documents" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setDividerHeight(2);
getListView().setAdapter(new BindDataAdapter(getActivity(), img, item));
}
#SuppressWarnings("deprecation")
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
for (int a = 0; a < l.getChildCount(); a++) {
l.getChildAt(a).setBackgroundColor(Color.TRANSPARENT);
}
}
}
I didn't use any layout in listFragment.I use the layout in BindDataAdapter.java
BindDataAdapter.java:
public class BindDataAdapter extends BaseAdapter {
Activity mLocal;
int[] imgArray;
String titleA[];
LayoutInflater mLayoutInflater;
public BindDataAdapter(Activity administration, int[] imageArray, String[] title) {
mLocal = administration;
imgArray = imageArray;
titleA = title;
mLayoutInflater = (LayoutInflater) administration
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return imgArray.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
private class Holder {
ImageView image;
TextView textView;
}
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = null;
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.activity_list, null);
holder = new Holder();
holder.image = (ImageView) convertView.findViewById(R.id.iamge);
holder.textView = (TextView) convertView.findViewById(R.id.text1);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.image.setBackgroundResource(imgArray[position]);
holder.textView.setText(titleA[position]);
return convertView;
}
}
activity_list.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/whitelist"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/iamge"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_margin="4dp"
android:contentDescription="#string/app_name" >
</ImageView>
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="20dp"
android:padding="#dimen/padding_medium"
android:paddingLeft="10dp"
android:text="#string/hello_world"
android:textColor="#android:color/black"
android:textStyle="bold"
/>
</LinearLayout>
I didn't know why it has been loading continuously. Any help is mostly appreciated.Thank you.
Probably showing progress-bar is default in-built progress for ListFragment. So use setListShown to dismiss built-in indeterminant progress-bar after setting adapter for ListView as:
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
.....
setListShown(true);
}