I divide my screen in two parts, one of the parts contain five buttons and another part contain seven ImageView with images. Now I want that ImageView rotate infinite,means, after last image, again images start to come. My XML is
<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:orientation="horizontal"
android:baselineAligned="true"
tools:context="in.example.splitapp.MainActivity" >
<ScrollView
android:id="#+id/scrollView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout1"
android:orientation="vertical"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_green_dark">
<Button android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:text="DOG"/>
<Button android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button1"
android:text="CAT"/>
<Button android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button2"
android:text="COW"/>
<Button android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button3"
android:text="RAT"/>
<Button android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button4"
android:text="PARROT"/>
</RelativeLayout>
</ScrollView>
<ScrollView
android:id="#+id/scrollView2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout2"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_purple"
>
<ImageView android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/dog"
android:text="DOG"/>
<ImageView android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView1"
android:background="#drawable/cat"
android:text="CAT"/>
<ImageView android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView2"
android:background="#drawable/cow"
android:text="COW"/>
<ImageView android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView3"
android:background="#drawable/rat"
android:text="RAT"/>
<ImageView android:id="#+id/imageView5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView4"
android:background="#drawable/parrot"
android:text="PARROT"/>
<ImageView android:id="#+id/imageView6"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView5"
android:background="#drawable/horse"
android:text="HORSE"/>
<ImageView android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView6"
android:background="#drawable/fish"
android:text="FISH"/>
</RelativeLayout>
</ScrollView>
</LinearLayout>
I want that ImageView side scrolling infinite means these five images repeated always.
This is my MainActivity:
public class MainActivity extends Activity implements OnScrollListener {
List<String> animalNameList = new ArrayList<String>();
ArrayList<Integer> animalImageList = new ArrayList<Integer>();
ImageAdapter imageAdapter;
NameAdapter nameAdapter = null;;
boolean flag = false;
ListView listView;
ListView listView1;
ListView upperListView;
RelativeLayout parentLayout;
LinearLayout childLayout;
int index = 0;
UpdateAdapter updateAdapter = null;
ArrayList<DataSplit> array = new ArrayList<DataSplit>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animalNameList.add("CAT");
animalNameList.add("DOG");
animalNameList.add("COW");
animalNameList.add("RAT");
animalNameList.add("PARROT");
animalNameList.add("HORSE");
animalNameList.add("FISH");
animalImageList.add(R.drawable.horse);
animalImageList.add(R.drawable.parrot);
animalImageList.add(R.drawable.fish);
animalImageList.add(R.drawable.rat);
animalImageList.add(R.drawable.dog);
animalImageList.add(R.drawable.cat);
animalImageList.add(R.drawable.cow);
parentLayout = (RelativeLayout)findViewById(R.id.parentRelative);
childLayout = (LinearLayout)findViewById(R.id.childLinearLayout);
nameAdapter = new NameAdapter(MainActivity.this,
-1, animalNameList);
listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(nameAdapter);
imageAdapter = new ImageAdapter(MainActivity.this, -1, animalImageList);
listView1 = (ListView)findViewById(R.id.listView2);
CircularListAdapter circularAdapter = new CircularListAdapter(imageAdapter);
listView1.setDivider(null);
listView1.setAdapter(circularAdapter);
listView1.setOnScrollListener(this);
upperListView = (ListView)findViewById(R.id.upperListView);
listView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if(flag)
{
}
}
});
}
class NameAdapter extends BaseAdapter {
private List<String> animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
List<String> animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
button.setId(position);
button.setText(animalName.get(position));
}
return convertView;
}
public int getCount()
{
int size = animalName.size();
return size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
class ImageAdapter extends ArrayAdapter<Integer> {
private ArrayList<Integer> animalImage;
private Activity context;
public ImageAdapter(Activity context, int textViewResourceId,
ArrayList<Integer> animalImage) {
super(context, textViewResourceId);
this.animalImage = animalImage;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
//view.setBackgroundResource(animalImage[position]);
view.setBackgroundResource(animalImage.get(position));
return view;
}
public int getCount()
{
int size = animalImage.size();
return size;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int childInt = view.getChildAt(0).getId();
//String img1Text = this.getResources().getResourceEntryName(animalImage[childInt]);
String img1Text = this.getResources().getResourceEntryName(animalImageList.get(childInt));
//String buttonText = animalName[index];
String buttonText = animalNameList.get(index);
if(img1Text.equalsIgnoreCase(buttonText))
{
final String name = animalNameList.get(index);
int image = animalImageList.get(childInt);
DataSplit data = new DataSplit();
data.setAnimalName(name);
data.setAnimalImage(image);
array.add(data);
index++;
flag = true;
if(array.size() == 1)
{
updateAdapter = new UpdateAdapter(MainActivity.this,-1,array);
upperListView.setAdapter(updateAdapter);
upperListView.setVisibility(View.VISIBLE);
}
else
{
updateAdapter.notifyDataSetChanged();
}
listView.post(new Runnable() {
#Override
public void run() {
animalNameList.remove(name);
nameAdapter.notifyDataSetChanged();
}
});
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
class UpdateAdapter extends ArrayAdapter<Integer> {
ArrayList<DataSplit> dataSplit;
private Activity context;
public UpdateAdapter(Activity context, int textViewResourceId,
ArrayList<DataSplit> dataSplit) {
super(context, textViewResourceId);
this.dataSplit = dataSplit;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.addeddata, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
ImageView imageView=(ImageView)convertView.findViewById(R.id.imageView);
String animalName = dataSplit.get(position).getAnimalName();
int imageName = dataSplit.get(position).getAnimalImage();
button.setText(dataSplit.get(position).getAnimalName());
imageView.setBackgroundResource(dataSplit.get(position).getAnimalImage());
}
return convertView;
}
public int getCount()
{
int size = dataSplit.size();
return size;
}
}
}
I created activity_main.xml which contains a parent RelativeLayout and under this a ListView named upperListView and initially set visibility gone. Below this I created a LinearLayout and for this I created two ListView for Name DataSet and Image DataSet. When data matches I create a UpdateAdapter in which I use addeddata.xml, in which a button and ImageView created and when it is a successful match then hidden list view visibility becomes Visible and this "addeddata.xml" loaded in listview. This I perform. It will work perfectly.But when first matches,i.e, CAT name match with the Cat image, data is not deleted from both of listview and CAT name again shown in below the new ListView.
How to manage to complete matches if the application crashes.
This has been discussed in the past, with using circular Listviews:
How to create a closed (circular) ListView?
Closed or circular Horizontal ListView Android
I just want when I scroll ImageView part then if Dog image matches with the right end side Dog name then image stick with the Dog Name Button and rest of the images remain scrolling.
For this here is what you could try:
after scrolling items in list1 and list2, iterate over each item in the shortest listview and check if item1(position) [tag] = item2(position) [tag] (so, if you have a match)
if true:
redraw screen like this: add a new listview at the bottom of the screen (below both listviews). This listview with contain both item1 and item2 (so it's litviewitem xml will be a linear layout with other two linear layouts, one containing the matched pet name and the other the matched pet picture)
remove item1(position) and item2(position) from listview1, listview2 (which means you have to remove, for example, dog name from listview pet names datasource, and dog image from listview pet pictures datasource and reset adapters to listviews)
this way you will continue to be able to scroll and match items from listview1 and listview2 - without the already matching items-, and also have a bottom listview with all the matching elements that cannot be matched any more
Hope this helps!
After spend couple of days I found the perfect solution for my question. I dynamically created the ImageView and also the ListView. Image data are populating in the ListView. After matching the text with right Image, I take that ImageView from the List and set in dynamically created ImageView. Following is my code.
public class MainActivity extends Activity implements OnScrollChangedListener, OnScrollListener{
int index = 0;
ImageView imageView1;
List<Integer> spectrum = new ArrayList<Integer>();
String[] animalName;
ImageView[] imageArray;
Button[] buttonArray;
ListView listView;
SpectrumAdapter spectrumAdapter;
ListView animalImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
animalName = new String[]{"CAT","DOG","COW","RAT","PARROT","HORSE","FISH"};
imageArray = new ImageView[animalName.length];
buttonArray = new Button[animalName.length];
LinearLayout inner1 = (LinearLayout)findViewById(R.id.innerLayout1);
LinearLayout inner2 = (LinearLayout)findViewById(R.id.innerLayout2);
ListView animalList = (ListView)findViewById(R.id.animalList);
NameAdapter nameAdapter = new NameAdapter(MainActivity.this,
-1, animalName);
animalList.setAdapter(nameAdapter);
for(int i=0;i<animalName.length;i++)
{
ImageView imageView = new ImageView(this);
imageView.setId(i);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,150);
imageView.setTag(i);
imageView.setLayoutParams(params1);
imageView.setVisibility(View.GONE);
imageArray[i] = imageView;
inner1.addView(imageView);
}
ListView listView = new ListView(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
listView.setLayoutParams(param);
inner2.addView(listView);
spectrum.add(R.drawable.horse);
spectrum.add(R.drawable.rat);
spectrum.add(R.drawable.cow);
spectrum.add(R.drawable.dog);
spectrum.add(R.drawable.fish);
spectrum.add(R.drawable.parrot);
spectrum.add(R.drawable.cat);
spectrumAdapter = new SpectrumAdapter(MainActivity.this,
-1, spectrum);
CircularListAdapter circularAdapter = new CircularListAdapter(spectrumAdapter);
listView.setAdapter(circularAdapter);
listView.setOnScrollListener(this);
}
class NameAdapter extends BaseAdapter {
private String[] animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
String[] animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
}
Button button=(Button)convertView.findViewById(R.id.button);
button.setText(animalName[position]);
return convertView;
}
public int getCount()
{
int size = animalName.length;
return size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
class SpectrumAdapter extends ArrayAdapter<Integer> {
private List<Integer> spectrum;
public SpectrumAdapter(Context context, int textViewResourceId,
List<Integer> spectrum) {
super(context, textViewResourceId, spectrum);
this.spectrum = spectrum;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
view.setBackgroundResource(spectrum.get(position));
return view;
}
public int getCount()
{
int size = spectrum.size();
return size;
}
}
#Override
public void onScrollChanged() {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
int childInt = view.getChildAt(0).getId();
String img1Text = this.getResources().getResourceEntryName(spectrum.get(childInt));
String bb = animalName[index];
if(bb.equalsIgnoreCase(img1Text))
{
ImageView img = imageArray[index];
img.setBackgroundResource(spectrum.get(childInt));
img.setVisibility(View.VISIBLE);
index++;
}
else
{
}
}
}
This is the perfect solution for the question. Thanks all for the suggestion.
Related
I can not figure out what going wrong with my ListView, because it is too small. I want bigger items like default list views on Android.
SelectContactActivity
public class SelectContactActivity extends Activity {
private ArrayList<Contact> listContacts = new ArrayList<Contact>();
private ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
private ListContactsAdapter adapter;
private Util util = new Util();
private ListView list;
private EditText txt_search;
private ArrayList<Contact> listSearch;
private Handler guiThread;
private Runnable updateTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.mycontacts);
list = (ListView)findViewById(R.id.list);
txt_search = (EditText)findViewById(R.id.txt_search);
final int position = this.getIntent().getIntExtra("position", 0);
listSong = util.getAllSong(this);
listContacts = util.getAllContact(this);
Log.i("LOG", "Size: " + listContacts.size());
adapter = new ListContactsAdapter(this, android.R.layout.simple_list_item_1, listContacts);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
util.assignRingtoneToContact(SelectContactActivity.this,
listSong.get(position), listContacts.get(arg2));
Toast.makeText(
SelectContactActivity.this,
"Ringtone set successfully",
Toast.LENGTH_LONG).show();
finish();
}
});
innitThread();
txt_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
queueUpdate(500);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void queueUpdate(long delayMillisecond) {
guiThread.removeCallbacks(updateTask);
// update data if no change in textSearch after time config
// timer by = milliseconds
guiThread.postDelayed(updateTask, delayMillisecond);
}
private void innitThread() {
guiThread = new Handler();
updateTask = new Runnable() {
#Override
public void run() {
String word = txt_search.getText().toString().trim();
if (word.equalsIgnoreCase("")) {
// if not change set listView first
list.setAdapter(new ListContactsAdapter(SelectContactActivity.this,
android.R.layout.simple_list_item_1, listContacts));
} else
// if txtSearch not null
{
// get data from webservice
getDataByKeywords(word);
// Show on list
listSearch = new ArrayList<Contact>();
// get data from webservice
listSearch = getDataByKeywords(word);
list.setAdapter(new ListContactsAdapter(SelectContactActivity.this, android.R.layout.simple_list_item_1, listSearch));
adapter.notifyDataSetChanged();
}
}
};
}
public ArrayList<Contact> getDataByKeywords(String keyword) {
listSearch = new ArrayList<Contact>();
keyword = keyword.toUpperCase();
for (int i = 0; i < listContacts.size(); i++) {
String contain = listContacts.get(i).getName().toUpperCase();
if (contain.contains(keyword)) {
listSearch.add(listContacts.get(i));
}
}
return listSearch;
}
}
ListContactsAdapter
public class ListContactsAdapter extends ArrayAdapter<Contact>{
private ArrayList<Contact> contacts;
private Context context;
public ListContactsAdapter(Context context, int textViewResourceId,
ArrayList<Contact> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contacts = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView!=null){
convertView.setBackgroundResource(R.drawable.list_selector);
}
TextView textView = getGenericView();
textView.setBackgroundResource(R.drawable.list_selector);
textView.setText(contacts.get(position).getName());
return textView;
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 70);
TextView textView = new TextView(context);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setPadding(16, 0, 0, 0);
textView.setTextSize(18);
textView.setShadowLayer(1, 1, 1, Color.BLACK);
textView.setTextColor(0xffeeeeee);
return textView;
}
}
mycontacts.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="#id/relativeLayoutSearch"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:gravity="center_vertical"
android:paddingLeft="12dp"
android:paddingRight="12dp" >
<EditText
android:id="#id/txt_search"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#drawable/search_bar"
android:hint="#string/hint_apps_search"
android:paddingBottom="12dp"
android:paddingLeft="45.0dip"
android:paddingRight="14dp"
android:paddingTop="12dp"
android:singleLine="true"
android:textSize="15.0sp" />
<Button
android:id="#id/button2"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/zoomicon" />
</RelativeLayout>
<ListView
android:id="#id/list"
style="#style/ContactList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/relativeLayoutSearch"
android:cacheColorHint="#e0000000" />
</RelativeLayout>
styles.xml
<style name="ContactList">
<!-- <item name="android:background">#color/listbg</item> -->
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:cacheColorHint">#e0000000</item>
<item name="android:divider">#color/listdiv</item>
<item name="android:dividerHeight">1.0dip</item>
</style>
This is my code for contact list, and here is a screenshot how this looks, but I want bigger items on list. Any suggestions?
Current listview:
I would start smaller, by revisiting your adapter. The ListView itself is very simple - in your activity layout, you set your ListView to be match_parent for both width and height.
The adapter is the component which creates each row, which in ListAdapter, is initiated by the getView() method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
convertView.setBackgroundResource(R.drawable.list_selector);
}
TextView textView = getGenericView();
textView.setBackgroundResource(R.drawable.list_selector);
textView.setText(contacts.get(position).getName());
return textView;
}
Note what you're doing here is incorrect; you do something to convertView but then you ignore it, and just make a new View. The pattern is more like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
rowView = // create a new View that represents your row
}
// bind the data to rowView, then return it
return rowView;
}
which in your case might be:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView rowView = (TextView) convertView;
if (rowView == null) {
rowView = getGenericView();
rowView.setBackgroundResource(R.drawable.list_selector);
}
rowView.setText(contacts.get(position).getName());
return rowView;
}
See, you only need to create rowView if it's null. Also, the background only needs to be set once (and this can be done in XML if you want).
With creating the row View, I'd recommend starting by inflating a layout that contains a single TextView as the only element.
view_item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
then your getGenericView() can be renamed to createContactRowView():
private TextView createContactRowView(ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
return ((TextView) layoutInflater.inflate(R.layout.view_item_contact, parent, false));
}
From there, you can start to style your row in view_item_contact.xml by adding padding, setting a minimum height, centering the text vertically by applying gravity, etc.
view_item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="48dp"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:background="#drawable/list_selector" />
In almost all cases, I would avoid creating Views programmatically - always inflate them from XML, so you can separate styles and layout from your logic.
below is my code which works fine for showing listview horizontally. how can I change it to gridvew. What changes should I make to change it to gridview? help me please
public class fifthscreen extends Activity {
int IOConnect = 0;
String _response;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
String name;
String url1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new TheTask().execute();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
try {
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
listview.setAdapter(cla);
}
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return fifthscreen.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(fifthscreen.Category_name.get(position));
// imageLoader.DisplayImage(fifthscreen.Category_image.get(position),
activity, holder.imgThumb);
androidAQuery.id(holder.imgThumb).image(fifthscreen.Category_image.get(position), false,
false);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
<!--- fifithscreen.xml--->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_below="#+id/test_button_text5"
android:orientation="vertical" >
<com.example.examplecode.HorizontalListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="120dp"
android:layout_below="#+id/test_button_text5"
android:background="#ffffff"/>
</LinearLayout>
<!--viewitem2.xml--->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView
android:id="#+id/image2"
android:layout_width="90dp"
android:layout_height="70dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/title2"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:textColor="#000"
android:paddingTop="10dp"
android:gravity="center_horizontal"
/>
</LinearLayout>
No change at all. Just set adapter of GridView as your are setting for ListView.
I'd suggest that you use RecyclerView intead.
You might want to refer to the documentation and learn more about it.
I'm sharing my piece of code in which I'm changing my gridview to listview using RecyclerView
If you're using Android Studio then you might need to add dependencies in gradle build. In my case I added as follows:
dependencies {
.
.
.
compile 'com.android.support:recyclerview-v7:24.0.0'
}
First I'm defining a grid cell which is to be used in grid layout
recycler_cell.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView2"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:background="#FF000000"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView2"
android:layout_below="#+id/imageView2"
android:layout_alig=nParentStart="true"
android:layout_alignEnd="#+id/imageView2"
android:gravity="center"/>
</RelativeLayout>
Now I'm defining a list row which is to be used in list layout
recycler_row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:background="#FF000000"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignBottom="#+id/imageView"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/imageView"
android:gravity="center_vertical"
android:background="#FF333333"
android:textColor="#FFF"
android:padding="10dp"/>
</RelativeLayout>
recycler_view_test.xml
And of course define a layout which would contain RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_centerHorizontal="true"
>
</android.support.v7.widget.RecyclerView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Layout"
android:id="#+id/btnChange"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="62dp"/>
</RelativeLayout>
I'm sharing my piece of code but I'd strongly recommend that you go through the documentation and tutorials to understand RecyclerView to its full extent.
public class RecyclerViewTest extends AppCompatActivity
{
final int GRID = 0;
final int LIST = 1;
int type;
RecyclerView recyclerView;
RecyclerView.LayoutManager gridLayoutManager, linearLayoutManager;
MyAdapter adapter;
Button btnChange;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view_test);
// Display contents in views
final List<Person> list = new ArrayList<>();
list.add(new Person("Ariq Row 1"));
list.add(new Person("Ariq Row 2"));
list.add(new Person("Ariq Row 3"));
// Finding views by id
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
btnChange = (Button) findViewById(R.id.btnChange);
// Defining Linear Layout Manager
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
// Defining Linear Layout Manager (here, 3 column span count)
gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
//Setting gird view as default view
type = GRID;
adapter = new MyAdapter(list, GRID);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
//Setting click listener
btnChange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (type == LIST)
{
// Change to grid view
adapter = new MyAdapter(list, GRID);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
type = GRID;
}
else
{
// Change to list view
adapter = new MyAdapter(list, LIST);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
type = LIST;
}
}
});
}
}
//Defining Adapter
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
List<Person> list;
int type;
final int GRID = 0;
final int LIST = 1;
MyAdapter(List<Person> list, int type)
{
this.list = list;
this.type = type;
}
// Inflating views if the existing layout items are not being recycled
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
if (viewType == GRID)
{
// Inflate the grid cell as a view item
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cell, parent, false);
}
else
{
// Inflate the list row as a view item
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
}
return new ViewHolder(itemView, viewType);
}
// Add data to your layout items
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
Person person = list.get(position);
holder.textView.setText(person.name);
}
// Number of items
#Override
public int getItemCount()
{
return list.size();
}
// Using the variable "type" to check which layout is to be displayed
#Override
public int getItemViewType(int position)
{
if (type == GRID)
{
return GRID;
}
else
{
return LIST;
}
}
// Defining ViewHolder inner class
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textView;
final int GRID = 0;
final int LIST = 1;
public ViewHolder(View itemView, int type)
{
super(itemView);
if (type == GRID)
{
textView = (TextView) itemView.findViewById(R.id.textView2);
}
else
{
textView = (TextView) itemView.findViewById(R.id.textView);
}
}
}
}
// Data Source Class
class Person
{
String name;
Person(String name)
{
this.name = name;
}
}
If you end up with the issue to auto fit the number of columns in case of grid layout then you might want to check #s-marks's answer in which he extended the GridLayoutManager class and added his own patch of code, and also my fix if you start having weird column width.
In my case, using his solution I made a class as follows:
class GridAutofitLayoutManager extends GridLayoutManager
{
private int mColumnWidth;
private boolean mColumnWidthChanged = true;
public GridAutofitLayoutManager(Context context, int columnWidth)
{
/* Initially set spanCount to 1, will be changed automatically later. */
super(context, 1);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
public GridAutofitLayoutManager(Context context, int columnWidth, int orientation, boolean reverseLayout)
{
/* Initially set spanCount to 1, will be changed automatically later. */
super(context, 1, orientation, reverseLayout);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
private int checkedColumnWidth(Context context, int columnWidth)
{
if (columnWidth <= 0)
{
/* Set default columnWidth value (48dp here). It is better to move this constant
to static constant on top, but we need context to convert it to dp, so can't really
do so. */
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48,
context.getResources().getDisplayMetrics());
}
else
{
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, columnWidth,
context.getResources().getDisplayMetrics());
}
return columnWidth;
}
public void setColumnWidth(int newColumnWidth)
{
if (newColumnWidth > 0 && newColumnWidth != mColumnWidth)
{
mColumnWidth = newColumnWidth;
mColumnWidthChanged = true;
}
}
#Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
{
int width = getWidth();
int height = getHeight();
if (mColumnWidthChanged && mColumnWidth > 0 && width > 0 && height > 0)
{
int totalSpace;
if (getOrientation() == VERTICAL)
{
totalSpace = width - getPaddingRight() - getPaddingLeft();
}
else
{
totalSpace = height - getPaddingTop() - getPaddingBottom();
}
int spanCount = Math.max(1, totalSpace / mColumnWidth);
setSpanCount(spanCount);
mColumnWidthChanged = false;
}
super.onLayoutChildren(recycler, state);
}
}
Then you simply have to change:
gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
and use your custom grid layout object, here 100 is the width of columns in dp
gridLayoutManager = new GridAutofitLayoutManager(getApplicationContext(), 100);
You can do something like this:
For the layout of the grid/list use a merge:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ViewStub android:id="#+id/list"
android:inflatedId="#+id/showlayout"
android:layout="#layout/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
<ViewStub android:id="#+id/grid"
android:inflatedId="#+id/showlayout"
android:layout="#layout/grid_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</merge>
then define the layout for the list and the grid (and also for their items), and manage the passage between them inflating the layouts, and then use a method like this to change the current view:
private void changeView() {
//if the current view is the listview, passes to gridview
if(list_visibile) {
listview.setVisibility(View.GONE);
gridview.setVisibility(View.VISIBLE);
list_visibile = false;
setAdapters();
}
else {
gridview.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
list_visibile = true;
setAdapters();
}
}
If you need the complete code, it is available in this article:
http://pillsfromtheweb.blogspot.it/2014/12/android-passare-da-listview-gridview.html
Just take a GridView object instead of Listview like :
GridView gridView;
gridView= (GridView) this.findViewById(R.id.gridView1);
And in you getView method of CategoryListAdapter3 do like :
convertView = inflater.inflate(R.layout.your_grid_item_leyout, null);
And at last in onPostExecute of TheTask do like :
gridView.setAdapter(cla);
That's It.
Use GridView instead of below:
Then replace
listview = (HorizontalListView) this.findViewById(R.id.listview2);
to
GridView gridview;
gridview=(GridView) findViewById(R.id.gridview);
Everything else are fine, just set Adapter using GridView object. And you are done.
I have a class witch holds some variables...eg
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
int white = 0xffffffff;
ArrayList<Integer>nextColorArray = new ArrayList<Integer>();
int total_count = 0;
in my onCreate method:
GridView gridview2 = (GridView) findViewById(R.id.colorNext);
gridview2.setAdapter(new ImageAdapter(this));
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
from my adapter i add elements to the grid view to produce 5 colors the show in the gridview UI no problem... o.k
i have a button onclick(not in onCreate) event that increments total_count by 1 each time i click the button...o.k when the total_count is greater than ten i want to add a new element to the array..ok
if (action == MotionEvent.ACTION_DOWN) {
if(total_Count > 10){
nextColorArray.add(0, white);
}...ok
my problem is that the UI gridview is not updating the ui to show the new color...any ideas on how i can update the adapter when a new color is added to the list????
Edit: Since i am not sure how many edit's i made to my post. i edited the question and added the answer here. This works .
public class MainActivity extends Activity {
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
int white = 0xFFFFFFFF;
int total_Count = 0;
int colorPosition = 0;
int colorPickerStart = 0;
Button button;
ImageView imageView;
ImageAdapter ia;
GridView gridview2;
ArrayList<Integer>nextColorArray = new ArrayList<Integer>(10);
ArrayList<Integer>colorPicker = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
//set adapters
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ButtonAdapter(this));
button = (Button) findViewById(R.id.button1);
gridview2 = (GridView) findViewById(R.id.gridview2);
ia = new ImageAdapter(this, nextColorArray);
gridview2.setAdapter(ia);
button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
nextColorArray.add(Color.BLACK);
ia.notifyDataSetChanged();
}
});
//next color elements
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<Integer> a;
public ImageAdapter(Context c, ArrayList<Integer> a) {
mContext = c;
this.a = a;
}
public int getCount() {
return a.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
/*create a new ImageView for each item referenced by the Adapter*/
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {/*if it's not recycled, initialize some attributes*/
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(50, 45));
imageView.setBackgroundColor(nextColorArray.get(colorPosition));
if(colorPosition < 9) colorPosition++;
} else {
imageView = (ImageView) convertView;
}
return imageView;
}
}
/*button adapter*/
public class ButtonAdapter extends BaseAdapter {
private Context mContext;
public ButtonAdapter(Context c) {
mContext = c;
}
public int getCount() {
return nextColorArray .size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
// create a new button for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
button = new Button(mContext);
button.setLayoutParams(new GridView.LayoutParams(128, 128));
total_Count++;
button.setText(""+total_Count);
} else {
button = (Button) convertView;
}
return button;
}// end get view
}// end button adapter
activity_main
<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=".MainActivity" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:columnWidth="0dp"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="20dp"
android:padding="40dp"
android:verticalSpacing="20dp" />
<GridView
android:id="#+id/gridview2"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_above="#+id/button1"
android:layout_alignParentRight="true"
android:layout_marginBottom="74dp"
android:columnWidth="0dp"
android:gravity="center"
android:horizontalSpacing="20dp"
android:numColumns="2"
android:padding="40dp"
android:verticalSpacing="20dp" >
</GridView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
You have to call notifyDataSetChanged() on your adapter in order to refresh its content.
ImageAdapter ia;
GridView gridview2 = (GridView) findViewById(R.id.colorNext);
ia = new ImageAdapter(this);
gridview2.setAdapter(ia);
....
if (action == MotionEvent.ACTION_DOWN) {
if(total_Count > 10){
nextColorArray.add(0, white);
ia.notifyDataSetChanged(); // call notifyDataSetChanged to update your gridview
}
public void notifyDataSetChanged ()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
Example:
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"
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=".MainActivity" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="0dp"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="20dp"
android:padding="40dp"
android:verticalSpacing="20dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
MainActivity
public class MainActivity extends Activity {
ImageAdapter im;
ImageView imageView;
GridView gd;
ArrayList<Integer>nextColorArray = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
final int white = 0xffffffff;
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
gd= (GridView) findViewById(R.id.gridview);
im = new ImageAdapter(this,nextColorArray);
gd.setAdapter(im);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
nextColorArray.add(Color.BLACK);
im.notifyDataSetChanged();
}
});
}
}
ImageAdapter
public class ImageAdapter extends BaseAdapter{
Context mContext;
ArrayList<Integer> a;
public ImageAdapter(Context context,ArrayList<Integer> a) {
mContext=context;
this.a= a;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return a.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View arg1, ViewGroup arg2) {
ImageView imageView;
if (arg1 == null) {
imageView = new ImageView(mContext);
imageView.setPadding(0, 20, 0, 0);
} else {
imageView = (ImageView) arg1;
}
imageView.setBackgroundColor(a.get(position));
return imageView;
}
}
As and when you click black color appears on the screen.
SnapShot
I used the following code create a custom listview ....But the problem with this code it it is selecting only one item..but highlighting many items...i mean ..for example..if i have 8 items in the list..And i can see only 3 items(rest i have to scroll to see)..if i click the first item...it gets highlighted along with the fourth and the 7th item...
public class MainMenu extends Activity {
ListView lmenu;
View v1;
String s;
Class<?> ourclass;
View layout, row;
static int trantype;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menulist);
Menu Menu_data[] = new Menu[] { new Menu("1.White"),
new Menu("2.Blue"), new Menu("3.Purple"), new Menu("4.Red"),
new Menu("5.Yellow"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black") };
MenuAdapter adapter = new MenuAdapter(this, R.layout.menutext,
Menu_data);
lmenu = (ListView) findViewById(R.id.mainmenu);
lmenu.setAdapter(adapter);
lmenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> ada, View v, int position,
long id) {
// TODO Auto-generated method stub
/*
* v.setBackgroundColor(Color.parseColor("#FCD5B5")); if (!(v1
* == null) && v1 != v)
* v1.setBackgroundColor(Color.parseColor("#EEEEEE")); v1 = v;
*/
Intent swipeit = new Intent(getBaseContext(), Swipeit.class);
trantype = position + 1;
startActivity(swipeit);
}
});
findViewById(R.id.BLogout).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
public class Menu {
public String title;
public Menu() {
super();
}
public Menu(String title) {
super();
this.title = title;
}
}
public class MenuAdapter extends ArrayAdapter<Menu> {
Context context;
int layoutResourceId;
Menu data[] = null;
LayoutInflater inflater;
boolean[] arrBgcolor;
private int activeHex, inactiveHex;
public MenuAdapter(Context context, int layoutResourceId, Menu[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
activeHex = Color.parseColor("#FCD5B5");
inactiveHex = Color.parseColor("#EEEEEE");
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arrBgcolor = new boolean[13];
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
try {
MenuHolder holder = null;
row = convertView;
// convertView.setBackgroundColor(Color.BLACK);
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MenuHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.tv1);
row.setTag(holder);
} else {
holder = (MenuHolder) row.getTag();
}
Menu Menu = data[position];
holder.txtTitle.setText(Menu.title);
holder.txtTitle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
resetArrbg();
arrBgcolor[position] = true;
if (arrBgcolor[position]) {
row.setBackgroundColor(activeHex);
} else {
row.setBackgroundColor(inactiveHex);
}
notifyDataSetChanged();
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_LONG).show();
}
return row;
}
private void resetArrbg() {
for (int i = 0; i < arrBgcolor.length; i++) {
arrBgcolor[i] = false;
}
}
public class MenuHolder {
TextView txtTitle;
}
}
}
my xml containing list...
<include
android:id="#+id/header"
android:layout_alignParentTop="true"
layout="#layout/header" />
<RelativeLayout
android:id="#+id/Rlmain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header"
android:orientation="vertical" >
<TextView
android:id="#+id/TMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="8dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="8dp"
android:text="Main Menu"
android:textColor="#000000"
android:textSize="15dp" />
<View
android:id="#+id/Vtop"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_below="#+id/TMain"
android:background="#android:color/darker_gray" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/Vbot"
android:layout_below="#+id/Rlmain"
android:orientation="vertical" >
<ListView
android:id="#+id/mainmenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#E0E0E0"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:dividerHeight="20dp" >
</ListView>
</RelativeLayout>
<View
android:id="#+id/Vbot"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_above="#+id/textView1"
android:background="#android:color/darker_gray" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="© India Transact Services Ltd."
android:textColor="#000000"
android:textSize="15dp" />
</RelativeLayout>
my xml for list....
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LLtv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#EEEEEE"
android:cacheColorHint="#00000000" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:textColor="#000000"
android:textSize="20dp" />
</LinearLayout>
Can please anyone help me and tell where i am going wrong?
What you want can't be achieved with your current setup. You need to implement a custom adapter where you have access to the getView() method. For reasons made clearer in the answer here, what you need to do is use some sort of data-container that will hold the status of an individual row using some indicator and then perform your action based on it's position on the container (which should correspond to its position on the listview)
for example, check out this re-write:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
resetArrbg();
arrBgcolor[position] = true;
if (arrBgcolor[position]) {
v.setBackgroundColor(Color.parseColor("#FCD5B5"));
} else {
v.setBackgroundColor(Color.BLUE);
}
}
boolean[] arrBgcolor = new boolean[list.size()];
private void resetArrbg() {
for (int i = 0; i < arrBgcolor.length; i++) {
arrBgcolor[i] = false;
}
}
Does it make sense now why it can't work with the current set-up? The else part of the method, the part affecting the other views, can never take place because you don't have access to the other positions in the onListItemClick method, but you do in getView(). This is of course, unless you know of a way around this then, by all means, more power to you. all the same i don't think the v1 technique do you any good.
EDIT:
public class MainActivity extends Activity {
ListView lmenu;
View v1;
String s;
Class<?> ourclass;
View layout, row;
static int trantype;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menulist);
Menu Menu_data[] = new Menu[] { new Menu("1.White"),
new Menu("2.Blue"), new Menu("3.Purple"), new Menu("4.Red"),
new Menu("5.Yellow"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black"), new Menu("6.Black"),
new Menu("6.Black"), new Menu("6.Black") };
MenuAdapter adapter = new MenuAdapter(this, R.layout.menutext, Menu_data);
lmenu = (ListView) findViewById(R.id.mainmenu);
lmenu.setAdapter(adapter);
}
public class Menu {
public String title;
public Menu() {
super();
}
public Menu(String title) {
super();
this.title = title;
}
}
public class MenuAdapter extends ArrayAdapter<Menu> {
Context context;
int layoutResourceId;
Menu data[];
LayoutInflater inflater;
boolean[] arrBgcolor;
private int activeHex, inactiveHex;
public MenuAdapter(Context context, int layoutResourceId, Menu[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
activeHex = Color.parseColor("#FCD5B5");
inactiveHex = Color.parseColor("#EEEEEE");
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arrBgcolor = new boolean[data.length];
resetArrbg();
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
final MenuHolder holder;
row = convertView;
// convertView.setBackgroundColor(Color.BLACK);
if (row == null) {
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MenuHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.tv1);
row.setTag(holder);
} else {
holder = (MenuHolder) row.getTag();
}
Menu Menu = data[position];
holder.txtTitle.setText(Menu.title);
if (arrBgcolor[position]) {
row.setBackgroundColor(activeHex);
} else {
row.setBackgroundColor(inactiveHex);
}
holder.txtTitle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
resetArrbg();
arrBgcolor[position] = true;
notifyDataSetChanged();
}
});
return row;
}
private void resetArrbg() {
for (int i = 0; i < arrBgcolor.length; i++) {
arrBgcolor[i] = false;
}
}
public class MenuHolder {
TextView txtTitle;
}
}
}
This happens because of the way ListView reuses Views when populating the list. Lets say you see three rows of the list at any given time. You "highlight" the first row by setting the background color (like you do), and scroll down. When the first row leaves the screen, Android does something smart. Instead of creating a new View for, say, the fifth row, it reuses the View from row one. That's the View you changed the background color of, so row five now got the same background color. Only the data is changed.
As for how to implement a different background color on the selected row, and the selected row only, have a look at this answer. I do believe you got to implement a custom ListAdapter, at least if you're developing for API levels lower than 11.
I am using a list view and an adapter for loading a list,each list item has a TextView,EditText and Image..I set the visibility of the arrow and the Edit text according to the position of the list row,everything works fine when I load the list for the first time...
But when I scroll through the list,visibility of the items keep changing...Kindly help me in this issue...The relevant codes has been attached...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal" android:background="#FFFFFF">
<TextView android:layout_height="wrap_content" android:layout_width="0dip"
android:textSize="20dip" android:layout_weight="1"
android:id="#+id/textview_add_lot_list" android:textColor="#android:color/black"
android:paddingTop="10dip" android:paddingBottom="10dip"
android:paddingLeft="10dip"/>
<EditText android:layout_height="fill_parent" android:layout_width="0dip"
android:layout_weight="1" android:id="#+id/et_add_lot_list"
android:layout_gravity="center_vertical"/>
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content"
android:id="#+id/imageview_arrow_add_lot_list" android:layout_gravity="center_vertical"
android:visibility="invisible" android:src="#drawable/more_reviews_arrow"
android:paddingRight="10dip"/>
</LinearLayout>
Java code activity...
final ArrayList<String> listItems = new ArrayList<String>();
listItems.add("Parking name");
listItems.add("Address");
listItems.add("City");
listItems.add("State");
listItems.add("Zip");
listItems.add("Phone");
listItems.add("Web Address");
listItems.add(" ");
listItems.add("Parking Image");
listItems.add(" ");
listItems.add("Open Hours");
listItems.add(" ");
listItems.add("Web Reviews");
final AddParkingLotAdapter adapter = new AddParkingLotAdapter(mAppContext,0,listItems);
lv.setAdapter(adapter);
Java code...adapter
public class AddParkingLotAdapter extends ArrayAdapter<String> {
private ArrayList<String> mStrings;
private LayoutInflater mInflater;
private AppContext mContext;
private static int NON_EMPTY_ROW = 1;
private static int EMPTY_ROW = 0;
public AddParkingLotAdapter(Context context, int resId, List<String> strings) {
super(context, resId,strings);
mStrings = (ArrayList<String>) strings;
mContext = (AppContext) context;
mInflater = LayoutInflater.from(context);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return mStrings.size();
}
#Override
public String getItem(int position) {
return mStrings.get(position);
}
#Override
public int getItemViewType(int position) {
if(position==7||position==9||position==11){
return EMPTY_ROW;
}else{
return NON_EMPTY_ROW;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView itemTextView = null;
//different inflations for different type rows..
if(getItemViewType(position) == EMPTY_ROW){
if (convertView == null) {
convertView = mInflater.inflate(R.layout.review_empty_row, null);
}
}else if(getItemViewType(position) == NON_EMPTY_ROW){
if (convertView == null) {
convertView = mInflater.inflate(R.layout.add_parkinglist_item, null);
}
itemTextView = (TextView) convertView.findViewById(R.id.textview_add_lot_list);
itemTextView.setText(mStrings.get(position));
if (position==3||position==8||position==10||position==12){
ImageView itemImageView = (ImageView)convertView.findViewById(R.id.imageview_arrow_add_lot_list);
itemImageView.setVisibility(View.VISIBLE);
EditText editText = (EditText)convertView.findViewById(R.id.et_add_lot_list);
editText.setVisibility(View.INVISIBLE);
}
}
return convertView;
}
}
In this code:
if (position==3||position==8||position==10||position==12){
ImageView itemImageView = (ImageView)convertView.findViewById(R.id.imageview_arrow_add_lot_list);
itemImageView.setVisibility(View.VISIBLE);
EditText editText = (EditText)convertView.findViewById(R.id.et_add_lot_list);
editText.setVisibility(View.INVISIBLE);
}
you've got no else clause. That means that if position is 0,1,2,4,5 or 6 you don't explicitly set the visibility of the views and so the visibility will be whatever it was set to when the views were recycled. If convertView is non-null, you always need to reset the visibility of any items whose visibility may be been modified earlier.