I have a Gridview where I set some items from an array of string.
The code works fine, but I have a problem with it.
Everytime I add items, it "add" 10 of them and instead of jumping to the item 11, it go back to the first one. So the final result is something like:
1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 1
12. 2
...
As I've seen, when I navigate up/down it restart loading the data from the beggining.
Could somebody help me please? I don't know where the problem can be.
CustomGridViewActivity.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 android.widget.TextView;
import com.squareup.picasso.Picasso;
public class CustomGridViewActivity extends BaseAdapter {
private Context mContext;
private final String[] gridViewString;
private final String[] gridViewImageId;
public CustomGridViewActivity(Context context, String[] gridViewString, String[] gridViewImageId) {
mContext = context;
this.gridViewImageId = gridViewImageId;
this.gridViewString = gridViewString;
}
#Override
public int getCount() {
return gridViewString.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View gridViewAndroid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
gridViewAndroid = new View(mContext);
gridViewAndroid = inflater.inflate(R.layout.gridview_layout, null);
TextView textViewAndroid = (TextView) gridViewAndroid.findViewById(R.id.android_gridview_text);
ImageView imageViewAndroid = (ImageView) gridViewAndroid.findViewById(R.id.android_gridview_image);
textViewAndroid.setText(gridViewString[i]);
Picasso
.with(mContext)
.load(gridViewImageId[i])
.fit() // will explain later
.into((ImageView) imageViewAndroid);
//imageViewAndroid.setImageResource(gridViewImageId[i]);
} else {
gridViewAndroid = (View) convertView;
}
return gridViewAndroid;
}
}
gridview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/android_custom_gridview_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="#+id/android_gridview_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="15dp" />
<TextView
android:id="#+id/android_gridview_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="12sp" />
</LinearLayout>
content_main.xml:
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="90dp"
android:gravity="center"
android:numColumns="auto_fit"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
Common.java:
//SearchPanel
static String[] gridViewString = new String[30];
static String[] gridViewImages = new String[30];
MainActivity.java:
public void Search() {
//GridView
CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(MainActivity.this, Common.gridViewString, Common.gridViewImages);
androidGridView=(GridView)findViewById(R.id.grid_view);
androidGridView.setAdapter(adapterViewAndroid);
androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int i, long id) {
Toast.makeText(MainActivity.this, "GridView Item: " + Common.gridViewString[+i], Toast.LENGTH_LONG).show();
}
});
}
(JUST IN CASE, the data from the "Common" file is added by JSON and it's all different)
In your adapter's getView() method move the lines where you set the text and setup Picasso outside of the if-else block:
if (convertView == null) {
...
} else {
...
}
textViewAndroid.setText(gridViewString[i]);
Picasso
.with(mContext)
.load(gridViewImageId[i])
.fit() // will explain later
.into((ImageView) imageViewAndroid);
return gridViewAndroid;
Right now you're setting the text and image only when the row is being freshly built(convertView being null). As that row view will be recycled(used) for other rows as well, you end up with the old information as you aren't setting up the previously constructed row with new data.
Related
I created a listview with a custom adapter that allows me to have a list of items with checkboxes next to each item.
So I would like to look at the checkbox for the corresponding item in the list and see if it is checked and if it is, then set the value of boolean whiskey = false to true and so on for the other booleans.
It is very possible I have code in the wrong class or xml file, I've been trying to piece together things I've found on the internet. I'm new to android studio so its proving very difficult. I do have about a years worth of java experience though. I have all my code written in a working program on Eclipse, I am just having a hell of a time figuring out how to implement it into a working app.
Thanks in advance.
customAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class customAdapter extends BaseAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public customAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
public void setChecked(boolean isChecked){
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity2_listview, null);
}
//Handle TextView and display string from your list
TextView label = (TextView)view.findViewById(R.id.label);
label.setText(list.get(position));
//Handle buttons and add onClickListeners
CheckBox callchkbox = (CheckBox) view.findViewById(R.id.cb);
callchkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//update isChecked value to model class of list at current position
list.get(position).setChecked(isChecked);
}
});
return view;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
Main2Activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import android.widget.CheckBox;
public class Main2Activity extends AppCompatActivity {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ListView listView = (ListView) findViewById(R.id.userIngredients);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(userIngredients));
listView.setAdapter(new customAdapter(list, Main2Activity.this));
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity"
android:id="#+id/linearLayout">
<ListView
android:layout_width="419dp"
android:layout_height="558dp"
android:id="#+id/userIngredients"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
tools:layout_conversion_absoluteHeight="731dp"
tools:layout_conversion_absoluteWidth="411dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="374dp"
android:layout_height="60dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Check Your Ingredients"
android:textSize="24sp"
app:fontFamily="#font/cinzel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
activity2_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/label"
android:layout_width="323dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
i think you can do it with a BaseAdapter as well, but i suggest to use a RecyclerView instead.
I used support-v4 and recyclerview-v7 libs as following:
(Make sure that you are not developing AndroidX - check your gradle.properties of the entire project. It is very similar but uses other libraries though.)
build.gradle
android {
compileSdkVersion 28
buildToolsVersion '28.0.3'
...
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
...
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check Your Ingredients"
android:textAlignment="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_chooser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</android.support.v7.widget.RecyclerView>
</android.widget.RelativeLayout>
In the activity2_listview you might want to do more design to the xml. It looks very basic now.
activity2_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/listviewtextlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/listviewcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the main class we implement a callback-listener for our custom onItemAction function. We pass the listener with adapter.setActionListener(this); and add the adapter to the RecyclerViewer.
MainActivity.java
public class MainActivity extends AppCompatActivity implements CustomAdapter.ItemActionListener {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
CustomAdapter adapter;
RecyclerView.LayoutManager layoutManager;
RecyclerView recyclerListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
recyclerListView = (RecyclerView) findViewById(R.id.recycler_chooser);
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(userIngredients));
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerListView.setHasFixedSize(false);
layoutManager = new LinearLayoutManager(this);
recyclerListView.setLayoutManager(layoutManager);
System.out.println("list.size() " + list.size());
adapter = new CustomAdapter(list,MainActivity.this);
adapter.setActionListener(this);
recyclerListView.setAdapter(adapter);
} catch (Exception e){
e.printStackTrace();
}
}
// callback listener for your items
#Override
public void onItemAction(View view, CustomAdapter.CustomActions customAction, int position) {
final String itemName = adapter.getItem(position);
System.out.println(customAction + ": You clicked " + itemName + " on row number " + position);
switch(itemName){
case "Whiskey":
if(customAction== CustomAdapter.CustomActions.CHECK){
Whiskey=true;
}
else{
Whiskey=false;
}
System.out.println("Whiskey set to: " + Whiskey);
break;
case "Bourbon":
if(customAction== CustomAdapter.CustomActions.CHECK){
Bourbon=true;
}
else{
Bourbon=false;
}
System.out.println("Bourbon set to: " + Bourbon);
break;
//case xyz
// and so on
default:
System.out.println("Not programmed yet: " + itemName);
}
}
}
As said above i removed the BaseAdapter and replaced it with the RecyclerView. We had to implement a custom ViewHolder-class that contains each row in our RecyclerViewList. Within the ViewHolder we can call the method on our listener whenever a checkbox-change event occurs.
CustomAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
//------ helper class for the viewholder
enum CustomActions{
CHECK,UNCHECK
}
// Provide a reference to the views for each row
public class CustomViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public CheckBox mCheckBox;
public CustomViewHolder(View v) {
super(v);
// the view element v is the whole linear layout element
CheckBox.OnCheckedChangeListener checkboxListenerForOneEntry = new CheckBox.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if (mItemActionListener != null) {
if(isChecked){
// this compoundbutton view element will be the checkbox
mItemActionListener.onItemAction(view, CustomActions.CHECK, getAdapterPosition());
}else{
mItemActionListener.onItemAction(view, CustomActions.UNCHECK, getAdapterPosition());
}
}
}
};
mTextView = v.findViewById(R.id.listviewtextlabel);
mCheckBox = v.findViewById(R.id.listviewcheckbox);
mCheckBox.setOnCheckedChangeListener(checkboxListenerForOneEntry);
}
}
//------
private ArrayList<String> list;
private Context context;
private LayoutInflater mInflater;
private ItemActionListener mItemActionListener;
public CustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
this.mInflater = LayoutInflater.from(this.context);
}
// allows clicks events to be caught
void setActionListener(ItemActionListener itemActionListener) {
this.mItemActionListener = itemActionListener;
}
// parent activity will implement this method to respond to click events
public interface ItemActionListener {
void onItemAction(View view, CustomActions customAction, int position);
}
// Create new views (invoked by the layout manager)
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = mInflater.inflate(R.layout.activity2_listview, parent, false);
return new CustomViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(list.get(position));
}
#Override // Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
return getCount();
}
public int getCount() {
return list.size();
}
public String getItem(int pos) {
return list.get(pos);
}
}
Feel free to use the code as you like.
For more info about the RecyclerView see the google docs: https://developer.android.com/guide/topics/ui/layout/recyclerview
I need to show text below every image in grid view. I have been able to put the images in grid view but how to put text below it? Below I'm posting the code snippets.
fragment_facility_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<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="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
FacilityAdapter.class
package com.androidbelieve.HIT_APP;
/**
* Created by Akash on 2/13/2016.
*/
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class FacilityAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.bank, R.drawable.bus,
R.drawable.girlshostel , R.drawable.guesthouse,
R.drawable.gym , R.drawable.library,R.drawable.sports
};
public String[] mThumbNames = {
"Bank", "Bus Service","Guest House", "GYM","Fac1","Fac2"
};
// Constructor
public FacilityAdapter(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) {
View gridView;
gridView = new View(mContext);
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
return imageView;
}
}
Thank You
I would rather suggest that instead of creating ImageView dynamically at run time and return that from your getView() method, you should create an xml for your each of the list items. Below is the sample xml with ImageView and TextView
<?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">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"/>
</LinearLayout>
Also you should follow ViewHolder Patternto make your GridView memory efficient. Your getView() method will look alike this
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.yourxml,
null);
holder.textview= (TextView) convertView.findViewById(R.id.text);
holder.imageview= (ImageView) convertView.findViewById(R.id.image);
holder.imageView.getLayoutParams().width = yourImageWidth;
holder.imageView.getLayoutParams().height = yourImageHeight;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageView.setImageResource(mThumbIds[position]);
holder.textview.setText(mThumbNames[position]);
return convertView;
}
static class ViewHolder {
ImageView imageView;
TextView textView;
}
Try to extend this:
SimpleAdapter
or use it by default like:
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.bank, R.drawable.bus,
R.drawable.girlshostel , R.drawable.guesthouse,
R.drawable.gym , R.drawable.library,R.drawable.sports
};
public String[] mThumbNames = {"Bank", "Bus Service","Guest House", "GYM","Fac1","Fac2"};
Simple adapter= new SimpleAdapter(mContext, List<?> your_list, R.layout.your_layout_file, from, to);
You also have to make a layout file and define how the image and text you would like to look for each gridview item like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/this_image_id_have_to_be_used_in_your_to_array"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/this_text_id_have_to_be_used_in_your_to_array"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"/>
</LinearLayout>
Hope it helps!!!
I have created an android application using GridView having three columns. The application is working fine but the problem is that the gridview columns are not completely filling with the view like as shown below.
In html we can put in terms of 100% to make as responsive based on resolution how can we make the same in android
main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="60px"
android:gravity="center"
android:horizontalSpacing="5px"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="5px" />
mygrid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="80px"
android:layout_height="100px"
android:background="#444444" >
</ImageView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textColor="#669966"
android:textStyle="bold" >
</TextView>
</LinearLayout>
mygridActivity.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class mygridActivity extends Activity {
private GridView g;
Integer[] img = { R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher };
String[] labels = { "Android", "Calender", "Sweety's Home", "New Calender",
"Home", "Star", "GTalk", "Mick", "No Entry" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
g = (GridView) findViewById(R.id.gridView1);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(), "Pic : " + (arg2 + 1), 1)
.show();
}
});
}
public class ImageAdapter extends BaseAdapter {
Context mGrid;
public ImageAdapter(Context g) {
this.mGrid = g;
}
public int getCount() {
return img.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 view;
if (convertView == null) {
view = new View(mGrid);
LayoutInflater Inf = getLayoutInflater();
view = Inf.inflate(R.layout.mygrid, null);
} else {
view = convertView;
}
ImageView iv = (ImageView) view.findViewById(R.id.imageView1);
TextView tv = (TextView) view.findViewById(R.id.textView1);
iv.setImageResource(img[position]);
tv.setText(labels[position]);
return view;
}
}
}
Please add the gravity to views within linear layout make it as center rather just making only TextView as center
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center">
//your code
</LinearLayout>
Updates Based on comments
To understand difference between dip/dp and px you can check http://developer.android.com/guide/topics/resources/more-resources.html#Dimension and http://developer.android.com/guide/practices/screens_support.html#density-independence Alternativley you can specify width and height in dimens.xml and values-sw720dp/dimens.xml for mobile and tablet respectively
To handle multiple screen please follow this
I am trying to add a checkbox in a customized listview but don't know how.
I have the following codes:
ListObject.java
package br.com.eduvm.xurrascalc;
public class ListObject {
private String texto;
private int iconeRid;
public ListObject() {
}
public ListObject(String texto, int iconeRid) {
this.texto = texto;
this.iconeRid = iconeRid;
}
public int getIconeRid() {
return iconeRid;
}
public void setIconeRid(int iconeRid) {
this.iconeRid = iconeRid;
}
public String getTexto() {
return texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
}
ListAdapter.java
package br.com.eduvm.xurrascalc;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<ListObject> itens;
public ListAdapter(Context context, ArrayList<ListObject> itens) {
// Itens que preencheram o listview
this.itens = itens;
// responsavel por pegar o Layout do item.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return itens.size();
}
public ListObject getItem(int position) {
return itens.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
ListObject item = itens.get(position);
view = mInflater.inflate(R.layout.itens_lista, null);
((TextView) view.findViewById(R.id.text)).setText(item.getTexto());
((ImageView) view.findViewById(R.id.imagemview)).setImageResource(item.getIconeRid());
return view;
}
}
List.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:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5sp" >
<ImageView
android:id="#+id/imagemview"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5sp"
android:gravity="center_vertical"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
How could I do to insert a checkbox in the items in this list?
This would be the layout for each individual row in your list
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/lstChkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lstText"
android:textSize="30px"
android:layout_weight="1" />
<ImageView
android:id="#+id/listImage"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
You main list activity layout will look something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:choiceMode="multipleChoice"
/>
Your class which extends BaseAdapter getView method will somethings like this:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vHolder = null;
if (convertView != null)
vHolder = (ViewHolder) convertView.getTag(); // convertView is been recycled
else {
convertView = (View) mInflater.inflate(R.layout.list_item, null); // Set content of new View with list_item.xml
vHolder = new ViewHolder();
vHolder.checkBox = ((CheckBox) convertView.findViewById(R.id.lstChkbox)); // Getting pointers
vHolder.textView = ((TextView) convertView.findViewById(R.id.lstText));
vHolder.imageView = ((ImageView) convertView.findViewById(R.id.listImage));
vHolder.checkBox.setOnCheckedChangeListener(this); // Setting Listeners
convertView.setTag(vHolder);
}
vHolder.checkBox.setId(position); // This is part of the Adapter APi
vHolder.textView.setId(position); // Do not delete !!!
vHolder.imageView.setId(position);
if (mItems.get(position).getChecked()) { // Setting parameters for the View from our mItems list
vHolder.checkBox.setChecked(true);
} else {
vHolder.checkBox.setChecked(false);
}
vHolder.textView.setText(mItems.get(position).getText());
vHolder.imageView.setImageDrawable(mItems.get(position).getmImage());
return convertView;
}
public static class ViewHolder {
CheckBox checkBox;
TextView textView;
ImageView imageView;
}
/*
* Ok for this test but Toast are going to show every time the row comes into View
*/
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "Checked");
int position = buttonView.getId();
if (isChecked) {
mItems.get(position).setChecked(true);
Toast.makeText(context, mItems.get(position).getText(), Toast.LENGTH_LONG).show();
} else {
mItems.get(buttonView.getId()).setChecked(false);
}
}
Just add a checkbox to the layout itens_lista.xml.
Just adding a checkbox is easy. Do you want to do anything more to ti.
Add a CheckBox View to your custom row layout.
i'd like to start by saying that im quite new to android developing.
my question is how can i change my below examples to allow text on both the left and right side of each list item.
my aim is to have each list item have an item description on the left, and a numeric value for that description on the right.
all i have up to now is a list that shows the values which i want showing on the left of each item.
main java activity (NewtestActivity.java):
public class NewtestActivity extends Activity {
String[] exampleList = {
"Item 1",
"Item 2",
"Item 3",
"Test 4",
"Item 5",
"Test 6",
"Item 7",
"Test 8"
//etc etc
};
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get an instance of your listview in code
ListView listview = (ListView) findViewById(R.id.list);
// Set the listview's adapter
listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, exampleList));
}
}
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="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="280dp"
android:layout_height="fill_parent"
>
<ImageView
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_marginLeft="5dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:layout_marginLeft="5dp"
android:text="#string/app_name"
/>
</LinearLayout>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="200dp"
/>
</LinearLayout>
thanks for any help (:
With no direct link to your question, you can improve your xml code and your first LinearLayout (header), by using the attribute android:drawableLeft and android:drawablePadding of your TextView.
This accords you to place your icon on the left of your appName TextView.
Extend ArrayAdapter
Edit android.R.layout.simple_list_item_1 to contain the layout you
want
Check this example
Define Custom Adapter like this and define your custum layout xml file as per your need.
import java.util.Vector;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class YourAdapter extends BaseAdapter{
private Context mContext;
private Vector mValuestobeShown;
private Vector mValuetext;
private Vector mValueNumber;
public YourAdapter (Context context, Vector text,Vector item, Vector number){
mContext = context;
mValuetext = text;
mValuestobeShown = item;
mValueNumber = number;
}
public int getCount() {
if(null != mValuestobeShown){
return mValuestobeShown.size();
}
return 0;
}
public Object getItem(int position) {
if(position < mValuestobeShown.size())
return mValuestobeShown.get(position);
else
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
if(convertView == null){
LayoutInflater li =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.your_custom_layout, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.txt);
holder.item = (TextView) convertView.findViewById(R.id.item);
holder.num = (TextView) convertView.findViewById(R.id.num);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
try{
holder.item.setText(mValueType.get(position).toString());
//set other values.....
}catch(Exception e){ }
return convertView;
}
class ViewHolder {
TextView text;
TextView item;
TextView num;
}
}