how do i add checkbox in my code? so user select multiple pictures using checkbox in gridview what do i do? I just want to add a checkbox in my gridview what do i do?
GridView gridView;
TextView textView;
File currentParent;
File[] currentFiles;
SimpleAdapter simpleAdapter;
File root1;
File root;
root1 = new File("/data/data/com.myexample.lock/files/");
currentParent = root1;
currentFiles = root1.listFiles();
currentFilePath = new String[currentFiles.length];
int count = 0;
for (File f : currentFiles) {
currentFilePath[count] = f.getAbsolutePath();
count++;
}
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
if (currentFiles[position].isDirectory()) {
root = new File("/data/data/com.myexample.lock/files/" +
FileName(currentFilePath[position]) + "/");
currentFiles = root.listFiles();
inflateListView(currentFiles);
} else if (currentFiles[position].isFile()) {
openFile(currentFiles[position]);
}
}
});
private void inflateListView(File[] files) {
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
for (int i = 0; i < files.length; i++) {
Map<String, Object> listItem = new HashMap<String, Object>();
if (files[i].isDirectory()) {
listItem.put("icon", R.drawable.folder);
listItem.put("fileName", files[i].getName()+
"("+files[i].list().length+")");
} else {
listItem.put("icon", files[i]);
}
listItems.add(listItem);
}
simpleAdapter = new SimpleAdapter(this,
listItems, R.layout.line,new String[] {
"icon", "fileName" }, new int[] { R.id.icon, R.id.file_name });
}
line.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"
android:background="#ffffff"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/file_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/icon"
android:paddingLeft="5dp"
android:textColor="#000000"
android:textSize="12dp" />
</RelativeLayout>
Use custom adapter for your gridView. In the getView method you can inflate any layout you want for the cell
This the example of how i made a custom listview with Imageview and TextView. I did this because i also wanted to delete multiple items selected in the listview.
This is my java code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DeleteData extends Activity {
Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
manage_reload_list();
listOfItemsToDelete = new ArrayList<Integer>();
iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
iv_delete.setClickable(true);
iv_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
}
else {
showDialog(
"Warning",
"Are you sure you want to delete these categories ? This will erase all records attached with it.");
}
}
});
lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category category = (Category) imageView.getTag();
if (category.getChecked() == false) {
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageView.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
}
private void showDialog(final String title, String message) {
AlertDialog.Builder adb = new Builder(DeleteData.this);
adb.setTitle(title);
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
String btn = "Ok";
if (title.equals("Warning")) {
btn = "Yes";
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (title.equals("Warning")) {
for (int i : listOfItemsToDelete) {
// -------first delete from category table-----
// database.delete("category", "cat_id=?",
// new String[] { i + "" });
// ---------delete from category_fields
database.delete("category_fields", "cat_id=?",
new String[] { i + "" });
// --------now fetch rec_id where cat_id =
// i-----------------
cursor = database.query("records_data",
new String[] { "rec_id" }, "cat_id=?",
new String[] { i + "" }, null, null, null);
if (cursor.getCount() == 0)
cursor.close();
else {
ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
while (cursor.moveToNext())
al_tmp_rec_id.add(cursor.getInt(0));
cursor.close();
for (int i1 : al_tmp_rec_id) {
database.delete("records_fields_data",
"rec_id=?", new String[] { i1 + "" });
database.delete("record_tag_relation",
"rec_id=?", new String[] { i1 + "" });
}
// ---------delete from records_data-------
database.delete("records_data", "cat_id=?",
new String[] { i + "" });
cursor.close();
}
}
showDialog("Success",
"Categories, with their records, deleted successfully.");
} else {
database.close();
listOfItemsToDelete.clear();
manage_reload_list();
lv_delete_data.setAdapter(listAdapter);
}
}
});
AlertDialog ad = adb.create();
ad.show();
}
protected void manage_reload_list() {
loadDatabase();
categoryList = new ArrayList<Category>();
// ------first fetch all categories name list-------
cursor = database.query("category", new String[] { "cat_id",
"cat_description" }, null, null, null, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(), "No categories found.",
Toast.LENGTH_SHORT).show();
cursor.close();
} else {
while (cursor.moveToNext()) {
categories = new Category[] { new Category(cursor.getInt(0),
cursor.getString(1)) };
categoryList.addAll(Arrays.asList(categories));
}
cursor.close();
}
listAdapter = new CategoryArrayAdapter(this, categoryList);
}
static class Category {
String cat_name = "";
int cat_id = 0;
Boolean checked = false;
Category(int cat_id, String name) {
this.cat_name = name;
this.cat_id = cat_id;
}
public int getId() {
return cat_id;
}
public String getCatName() {
return cat_name;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
public void toggleChecked() {
checked = !checked;
}
}
static class CategoryViewHolder {
ImageView imageViewCheck;
TextView textViewCategoryName;
public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
imageViewCheck = iv_check;
textViewCategoryName = tv_category_name;
}
public ImageView getImageViewCheck() {
return imageViewCheck;
}
public TextView getTextViewCategoryName() {
return textViewCategoryName;
}
}
static class CategoryArrayAdapter extends ArrayAdapter<Category> {
LayoutInflater inflater;
public CategoryArrayAdapter(Context context, List<Category> categoryList) {
super(context, R.layout.single_row_delete_data,
R.id.textViewSingleRowDeleteData, categoryList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Category category = (Category) this.getItem(position);
final ImageView imageViewCheck;
final TextView textViewCN;
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_delete_data,
null);
imageViewCheck = (ImageView) convertView
.findViewById(R.id.imageViewSingleRowDeleteData);
textViewCN = (TextView) convertView
.findViewById(R.id.textViewSingleRowDeleteData);
convertView.setTag(new CategoryViewHolder(imageViewCheck,
textViewCN));
}
else {
CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
.getTag();
imageViewCheck = viewHolder.getImageViewCheck();
textViewCN = viewHolder.getTextViewCategoryName();
}
imageViewCheck.setFocusable(false);
imageViewCheck.setFocusableInTouchMode(false);
imageViewCheck.setClickable(true);
imageViewCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) v;
Category category = (Category) iv.getTag();
if (category.getChecked() == false) {
imageViewCheck.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageViewCheck
.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
imageViewCheck.setTag(category);
if (category.getChecked() == true)
imageViewCheck.setImageResource(R.drawable.set_check);
else
imageViewCheck.setImageResource(R.drawable.set_basecircle);
textViewCN.setText(category.getCatName());
return convertView;
}
}
private void loadDatabase() {
database = openOrCreateDatabase("WalletAppDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
This is my main layout code:
<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:background="#ffffff"
tools:context=".DeleteData" >
<RelativeLayout
android:id="#+id/relativeLayoutDeleteDataTopBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/textViewDeleteDataScreenTitle"
style="#style/screen_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Data" />
<ImageView
android:id="#+id/imageViewDeleteDataDelete"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/set_delete" />
</RelativeLayout>
<View
android:id="#+id/viewDeleteData"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#+id/relativeLayoutDeleteDataTopBar"
android:background="#drawable/shadow" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/linearLayoutDeleteDataAdMobBanner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<com.google.ads.AdView
android:id="#+id/adViewDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="a1512f50d8c3692"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />
</LinearLayout>
<ListView
android:id="#+id/listViewDeleteData"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#BDBDBD"
android:dividerHeight="1dp"
android:layout_below="#+id/viewDeleteData"
android:layout_above="#+id/linearLayoutDeleteDataAdMobBanner" >
</ListView>
</RelativeLayout>
And this is my custom layout code which i use to inflate in listview:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:padding="15dp" >
<TextView
android:id="#+id/textViewSingleRowDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
style="#style/listview_only_textview"
android:text="Category" />
<ImageView
android:id="#+id/imageViewSingleRowDeleteData"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/set_basecircle" />
</RelativeLayout>
Related
Good evening everyone !
I am currently working on an ExpandableListView.
The parent contains 1 ImageView.
The child contains 1 TextView and 3 Buttons.
In terms of display, no problem: everything works as I want.
However, I want to add actions to my buttons and I realize that when I put a SetOnclickListener in the getChildView I am not able to launch a new INTENT.
The examples I find on the internet seem to show only clicks on dynamic elements. However, the buttons are not dynamic in my case.
I planned to use a variable to do a SWITCH and thus launch the right INTENT.
But since it doesn't work, I wonder if my direction is the right one.
MaintActivity.java
package com.evo.tab2escape;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
public class jeux2 extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<Integer> headerData;
HashMap<Integer,ArrayList<ChildDataModel>> childData;
ChildDataModel childDataModel;
Context mContext;
ArrayList<ChildDataModel> logo0,logo1,logo2,logo3,logo4,logo5,logo6,logo7,logo8,logo9,logo10,logo11;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.jeux2);
mContext = this;
headerData = new ArrayList<>();
childData = new HashMap<Integer, ArrayList<ChildDataModel>>();
logo0 = new ArrayList<>();
logo1 = new ArrayList<>();
logo2 = new ArrayList<>();
logo3 = new ArrayList<>();
logo4 = new ArrayList<>();
logo5 = new ArrayList<>();
logo6 = new ArrayList<>();
logo7 = new ArrayList<>();
logo8 = new ArrayList<>();
logo9 = new ArrayList<>();
logo10 = new ArrayList<>();
logo11 = new ArrayList<>();
// get the listview
expListView = (ExpandableListView) findViewById(R.id.ExpandableListView);
// populate data
// Adding header data
headerData.add(R.drawable.logo0);
headerData.add(R.drawable.logo1);
headerData.add(R.drawable.logo2);
headerData.add(R.drawable.logo3);
headerData.add(R.drawable.logo4);
headerData.add(R.drawable.logo5);
headerData.add(R.drawable.logo6);
headerData.add(R.drawable.logo7);
headerData.add(R.drawable.logo8);
headerData.add(R.drawable.logo9);
headerData.add(R.drawable.logo10);
headerData.add(R.drawable.logo11);
// Adding child data
childDataModel = new ChildDataModel(1,"Test0","logo0");
logo0.add(childDataModel);
childData.put(headerData.get(0),logo0);
childDataModel = new ChildDataModel(1,"Test1","logo1");
logo1.add(childDataModel);
childData.put(headerData.get(1),logo1);
childDataModel = new ChildDataModel(1,"Test2","logo2");
logo2.add(childDataModel);
childData.put(headerData.get(2),logo2);
childDataModel = new ChildDataModel(1,"Test3","logo3");
logo3.add(childDataModel);
childData.put(headerData.get(3),logo3);
childDataModel = new ChildDataModel(1,"Test4","logo4");
logo4.add(childDataModel);
childData.put(headerData.get(4),logo4);
childDataModel = new ChildDataModel(1,"Test5","logo5");
logo5.add(childDataModel);
childData.put(headerData.get(5),logo5);
childDataModel = new ChildDataModel(1,"Test6","logo6");
logo6.add(childDataModel);
childData.put(headerData.get(6),logo6);
childDataModel = new ChildDataModel(1,"Test7","logo7");
logo7.add(childDataModel);
childData.put(headerData.get(7),logo7);
childDataModel = new ChildDataModel(1,"Test8","logo8");
logo8.add(childDataModel);
childData.put(headerData.get(8),logo8);
childDataModel = new ChildDataModel(1,"test09","logo9");
logo9.add(childDataModel);
childData.put(headerData.get(9),logo9);
childDataModel = new ChildDataModel(1,"test10","logo10");
logo10.add(childDataModel);
childData.put(headerData.get(10),logo10);
childDataModel = new ChildDataModel(1,"test11","logo11");
logo11.add(childDataModel);
childData.put(headerData.get(11),logo11);
listAdapter = new ExpandableListAdapter(this, headerData, childData);
// setting list adapter
expListView.setAdapter(listAdapter);
//--------------------------child click listener--------------------------
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
Log.d("TEST", "onChildClick: " + groupPosition + " " + childPosition + " " + id + " " + parent);
//Toast.makeText(getApplicationContext(), "heeeeeeeeerrrrreeeee!", Toast.LENGTH_SHORT).show();
return true;
}
});
//group expanded
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int headPosition) {
if (lastExpandedPosition != -1
&& headPosition != lastExpandedPosition) {
expListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = headPosition;
}
});
//group collapsed
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int headPosition) {
}
});
//--------------------------RETOUR--------------------------
Button retour = (Button) findViewById(R.id.retour);
retour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent Intent_next = new Intent(jeux2.this, MainActivity.class);
startActivity(Intent_next);
}
});
//--------------------------HISTO--------------------------
TextView histo = (TextView) findViewById(R.id.histo);
histo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent Intent_next = new Intent(jeux2.this, historique.class);
startActivity(Intent_next);
}
});
}
}
class ChildDataModel
{
long id;
String txt;
String aventure;
public ChildDataModel(int id, String explications, String aventure) {
this.setId(id);
this.setTxt(explications);
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTxt() {
return txt;
}
public void setTxt(String explications) {
this.txt = explications;
}
public String getTxt_aventure() {
return aventure;
}
#Override
public String toString()
{
return super.toString();
}
}
ExpandableListAdapter.java
package com.evo.tab2escape;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<Integer> headerData; // Images
// child data in format of header , child
private HashMap<Integer, ArrayList<ChildDataModel>> childData;
public ExpandableListAdapter(Context context, List<Integer> listDataHeader,
HashMap<Integer, ArrayList<ChildDataModel>> childData) {
this._context = context;
this.headerData = listDataHeader;
this.childData = childData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this.childData.get(this.headerData.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ChildDataModel child = (ChildDataModel) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView explications = (TextView) convertView.findViewById(R.id.explications);
explications.setText(child.getTxt());
Button play = (Button) convertView.findViewById(R.id.play);
Button doc = (Button) convertView.findViewById(R.id.doc);
Button param = (Button) convertView.findViewById(R.id.param);
final String aventure = child.getTxt_aventure();
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d("TAG", "poulet: ");
}
});
doc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d("TAG", "poulet: ");
}
});
param.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d("TAG", "poulet: ");
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.childData.get(this.headerData.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.headerData.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.headerData.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
ImageView logo = (ImageView) convertView.findViewById(R.id.logo);
int imageId = this.headerData.get(groupPosition);
logo.setImageResource(imageId);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Space
android:layout_width="match_parent"
android:layout_height="20dp">
</Space>
<ImageView
android:id="#+id/logo"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="100dp"/>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:id="#+id/divers">
<TextView
android:id="#+id/explications"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical"
android:textStyle="bold"
android:layout_weight="1.5">
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal">
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jouer"
android:layout_gravity="center"
android:background="#drawable/bouton_main"
android:layout_weight="1">
</Button>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
</Space>
<Button
android:id="#+id/doc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Documents"
android:layout_gravity="center"
android:background="#drawable/bouton_main"
android:layout_weight="1">
</Button>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
</Space>
<Button
android:id="#+id/param"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paramètres"
android:layout_gravity="center"
android:background="#drawable/bouton_main"
android:layout_weight="1">
</Button>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
</Space>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Can somoene help me ?
I want to start a new intent on click on Button.
Edit : i add child Click Listener on MainActivity but its works only if i set clickable,focusable = false on the 3 Buttons in layout list_item.xml.
And than the click is on the complete child. I can't say if the click is on Button 1, 2 or 3.
Can we fix it ?
Problem solved.
I do this in ExpandableListAdapter in getChildView.
param.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next = new Intent(parent.getContext(), parametres.class);
parent.getContext().startActivity(next);
}
});
In my app I have 3 views
ImagiveView
TextView
Button
ImagView displays image accordingly, TextView and Button display names and number accordingly. But the problem is when I click on the button it does not call to the number which is displaying on the button. Although it does open the android caller app.
Telephone numbers are in string.xml file.
Here I provide my all files. Please help me
strings.xml
<string-array name="names">
<item>Abdul Malik</item>
<item>Adeel ur Rehman</item>
<item>Asad Majeeb</item>
<item>Ata ul Salam</item>
<item>Atta ul Qadir</item>
<item>Bilal Scunder</item>
<item>Chaudry Adnan Ahmed</item>
<item>Chaudry Imran</item>
<item>Ejaz Ahmed Saroya</item>
<item>Hamid Joya</item>
</string-array>
<string-array name="telephones">
<item>0000000000</item>
<item>0486607636</item>
<item>0485256515</item>
<item>0485128196</item>
<item>0465922084</item>
<item>0487150005</item>
<item>0488627993</item>
<item>0484783792</item>
<item>0484688663</item>
<item>0497697050</item>
</string-array>
MainActivity.xml
package com.example.android.listview_with_custom_layout;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
ListView listView;
int [] movie_poster_resource={
R.drawable.movie_1,
R.drawable.movie_2,
R.drawable.movie_3,
R.drawable.movie_4,
R.drawable.movie_5,
R.drawable.movie_6,
R.drawable.movie_7,
R.drawable.movie_8,
R.drawable.movie_9,
R.drawable.movie_10,
};
String [] names ={};
String [] telephones ={};
MoviesAdapter moviesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.list_view);
telephones =getResources().getStringArray(R.array.telephones);
names =getResources().getStringArray(R.array.names);
int i=0;
moviesAdapter= new MoviesAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(moviesAdapter);
for(String titles: names){
MovieDataProvider movieDataProvider= new MovieDataProvider(movie_poster_resource[i], titles, telephones[i]);
moviesAdapter.add(movieDataProvider);
i++;
}
}
}
MoviesDataAdapter
package com.example.android.listview_with_custom_layout;
/**
* Created by temp on 2/11/2015.
*/
public class MovieDataProvider {
private int movie_poster_resource;
private String movie_title;
private String telePhone;
public MovieDataProvider(int movie_poster_resource, String movie_title, String telePhone) {
this.setMovie_poster_resource(movie_poster_resource);
this.setMovie_title(movie_title);
this.telePhone = telePhone;
}
public int getMovie_poster_resource() {
return movie_poster_resource;
}
public String getMovie_title() {
return movie_title;
}
public String getTelePhone() {
return telePhone;
}
public void setMovie_poster_resource(int movie_poster_resource) {
this.movie_poster_resource = movie_poster_resource;
}
public void setMovie_title(String movie_title) {
this.movie_title = movie_title;
}
public void setTelePhone(String telePhone) {
this.telePhone = telePhone;
}
}
MoviesAdapter
package com.example.android.listview_with_custom_layout;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by temp on 2/11/2015.
*/
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
MovieDataProvider dataProvider;
public MoviesAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler {
ImageView Poster;
TextView title;
Button telePhone;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.Poster = (ImageView) row.findViewById(R.id.movie_poster);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.telePhone = (Button) row.findViewById(R.id.btn_call);
row.setTag(handler);
} else {
handler = (DataHandler) row.getTag();
}
dataProvider = (MovieDataProvider) this.getItem(position);
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent to launch phone dialer
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
return row;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffd953"
tools:context=".MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#000000"
android:orientation="vertical"
android:paddingTop="10dp">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:src="#drawable/movie_1" />
<TextView
android:id="#+id/movie_title"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_toRightOf="#+id/movie_poster"
android:gravity="center"
android:text="This is movie name"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_call"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/movie_title"
android:gravity="center"
android:text="call"
android:textColor="#FFFF" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/movie_poster"
android:background="#FFFF"></View>
</RelativeLayout>
you forgot to initialize the telephones string in your MainActivity, do same as you did for movie_poster_resource after this it should work, and dont forgot to add permission
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
and last you can update the button click code with
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+dataProvider.getTelePhone()));
startActivity(callIntent);
and update your AdapterClass with this
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
public MoviesAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler {
ImageView Poster;
TextView title;
Button telePhone;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
final MovieDataProvider dataProvider = (MovieDataProvider) this.getItem(position);;
DataHandler handler;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.Poster = (ImageView) row.findViewById(R.id.movie_poster);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.telePhone = (Button) row.findViewById(R.id.btn_call);
} else {
handler = (DataHandler) row.getTag();
}
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
row.setTag(handler);
return row;
}
}
I am new to Android Development and I am having trouble with designing. I am trying to make an SMS app. I was successful in accessing the inbox and displaying the contact names. Now I want to set a custom height on each listview-item and remove the divider height which looks like a bottom border.
android:minHeight doesn't seem to work in my case. I also want to add click event on each dynamically created listview-item but it doesn't seem to work.
Here is my code:
MainActivity.java
public class MainActivity extends ListActivity {
ArrayList<String> messages = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayList<String> msglist = new ArrayList<String>();
String num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lvmsgs = (ListView) findViewById(R.id.msglist);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, null);
String sms = null;
ContentResolver resolver = null;
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(cur.getColumnIndexOrThrow("body")) + "\n";
num = cur.getString(2);
num = num.replace("+639", "09");
if (msglist.contains(num)) {
} else {
msglist.add(num);
messages.add(getContactName(num).toString());
}
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, messages);
setListAdapter(adapter);
lvmsgs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Toast",
Toast.LENGTH_LONG).show();
}
});
}
private String getContactName(String number) {
String name = null;
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
} else {
return number;
}
return name;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
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">
<ListView
android:id="#+id/msglist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
I think you can pass your own layout to arrayadapter .Create a layout with only text view without any layout. And set height and padding to text view.
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">
<ListView
android:id="#+id/lvCustomList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
layout_list_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="#+id/ivIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/start1" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Title" />
<TextView
android:id="#+id/tvDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Description" />
</LinearLayout>
</LinearLayout>
ModelClass:
package com.example.evuser.customlistviewdemo;
public class ListData {
String Description;
String title;
int imgResId;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
MainActivity:
package com.example.evuser.customlistviewdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView lvDetail;
Context context = MainActivity.this;
ArrayList<ListData> myList = new ArrayList<ListData>();
String[] title = new String[]{
"Title 1", "Title 2", "Title 3", "Title 4",
"Title 5", "Title 6", "Title 7", "Title 8"
};
String[] desc = new String[]{
"Desc 1", "Desc 2", "Desc 3", "Desc 4",
"Desc 5", "Desc 6", "Desc 7", "Desc 8"
};
int[] img = new int[]{
R.drawable.start1, R.drawable.star2, R.drawable.star3, R.drawable.star4,
R.drawable.star5, R.drawable.star4, R.drawable.star7, R.drawable.star8
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvDetail = (ListView) findViewById(R.id.lvCustomList);
// insert data into the list before setting the adapter
// otherwise it will generate NullPointerException - Obviously
getDataInList();
lvDetail.setAdapter(new MyBaseAdapter(context, myList));
}
private void getDataInList() {
for (int i = 0; i < title.length; i++) {
// Create a new object for each list item
ListData ld = new ListData();
ld.setTitle(title[i]);
ld.setDescription(desc[i]);
ld.setImgResId(img[i]);
// Add this object into the ArrayList myList
myList.add(ld);
}
}
}
AdapterClass:
package com.example.evuser.customlistviewdemo;
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 java.util.ArrayList;
public class MyBaseAdapter extends BaseAdapter {
ArrayList<ListData> myList = new ArrayList<ListData>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context, ArrayList<ListData> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListData getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
mViewHolder.tvDesc.setText(currentListData.getDescription());
mViewHolder.ivIcon.setImageResource(currentListData.getImgResId());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
tvDesc = (TextView) item.findViewById(R.id.tvDesc);
ivIcon = (ImageView) item.findViewById(R.id.ivIcon);
}
}
}
In the above example, I have given how to create custom layout for listview and use that in adapter class. You modify this class according to your requirement.
I am working on an android project that contains a view pager. The UI of MenuActivity is as following...
Below are the code of view pager activities...
MenuActivity.java
public class MenuActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs;
private String[] category_id;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
CommonFunctions.changeActionBar(getResources(),getActionBar());
// Initialization
initializeFoodCatagories();
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), tabs, category_id, MenuActivity.this);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
//Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
private void initializeFoodCatagories() {
GeneralHelper helper = new GeneralHelper();
JSONObject json = helper.callWebService(getString(R.string.API_END_POINT) + "get_food_category");
String total_items = helper.getValueFromJson(json, "TotalRecords");
tabs = new String[Integer.parseInt(total_items)];
category_id = new String[Integer.parseInt(total_items)];
if(!(total_items.equals("0"))) {
try {
final JSONArray jsonarray = json.getJSONArray("Response");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
tabs[i] = jsonobject.getString("category_name").toString();
category_id[i] = jsonobject.getString("category_id").toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
String [] category_name;
String [] category_id;
Activity context;
public TabsPagerAdapter(FragmentManager fm, String[] category_name, String[] category_id, Activity context) {
super(fm);
this.category_name = category_name;
this.category_id = category_id;
this.context = context;
}
#Override
public Fragment getItem(int index) {
for(int i = 0; i < category_name.length; i++) {
if(index==i) {
return new SwipeTabFragment(context, category_id[i]);
}
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return category_name.length;
}}
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
Activity context;
ListView list;
private String[] item_name;
private String[] price_per_unit;
private String[] item_image;
private String category_id;
public SwipeTabFragment(Activity context, String category_id) {
this.context = context;
this.category_id = category_id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_items, container, false);
list = (ListView) rootView.findViewById(R.id.lstItems);
initializeFoodItems(category_id);
list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
//ListView event handling
//This event not working
/*list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","ListView activated");
}
});*/
//This event is also not working
/*rootView.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","Plus Image Button activated");
}
});*/
return rootView;
}
private void initializeFoodItems(String position) {
String url = getString(R.string.API_END_POINT) + "get_menu_items?food_cat_id="+position;
GeneralHelper helper = new GeneralHelper();
JSONObject json = helper.callWebService(url);
String total_items = helper.getValueFromJson(json, "TotalRecords");
price_per_unit = new String[Integer.parseInt(total_items)];
item_name = new String[Integer.parseInt(total_items)];
item_image = new String[Integer.parseInt(total_items)];
if(!(total_items.equals("0"))) {
try {
final JSONArray jsonarray = json.getJSONArray("Response");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
price_per_unit[i] = jsonobject.getString("price_per_unit").toString();
item_name[i] = jsonobject.getString("item_name").toString();
item_image[i] = jsonobject.getString("item_image").toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}}
ItemListAdapter.java
public class ItemListAdapter extends ArrayAdapter<String> {
static int grand_total;
private final Activity context;
private final String title[];
private final String price[];
private final String discount[];
public ItemListAdapter(Activity context, String[] title, String[] price, String[] discount) {
super(context, R.layout.item_list, title);
this.context = context;
this.title = title;
this.price = price;
this.discount = discount;
}
#SuppressLint({ "ViewHolder", "InflateParams" })
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View row = inflater.inflate(R.layout.item_list, null,true);
((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
final int item_price = Integer.parseInt(price[position]);
((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange), PorterDuff.Mode.SRC_ATOP);
//Increasing Quantity
row.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
if (Integer.parseInt(qty.getText().toString()) > 0) {
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
//Decreasing Quantity
row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
if (Integer.parseInt(qty.getText().toString()) > 0) {
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
return row;
}
}
activity.menu.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
activity_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/activity_background">
<ListView
android:id="#+id/lstItems"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#drawable/listview_design"/>
</RelativeLayout>
item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/listview_design"
android:padding="5dp"
android:layout_margin="5dp" >
<TextView
android:id="#+id/txtTitl"
style="#style/ListViewHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="8dp"
android:layout_toRightOf="#+id/imgIcon"
android:gravity="left"
android:text="#string/itemname"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imgIcon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/img_desp"
android:src="#drawable/food_item_thumb" />
<RatingBar
android:id="#+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imgIcon"
android:layout_alignLeft="#+id/imgIcon"
android:background="#80FF0000"
android:numStars="5"
android:paddingBottom="5dp"
android:rating="3.5" />
<TextView
android:id="#+id/txtPrice"
style="#style/ListViewBottomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtTitl"
android:layout_below="#+id/txtTitl"
android:paddingTop="0dp"
android:text="#string/price_tag"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_alignBottom="#+id/imgIcon"
android:layout_alignLeft="#+id/txtPrice"
android:layout_alignTop="#+id/ratingBar" >
<ImageButton
android:id="#+id/imgPlus"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/sqr_plus"
android:contentDescription="#string/img_desp" />
<ImageButton
android:id="#+id/imgMinus"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_alignBottom="#+id/imgPlus"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/sqr_minus"
android:contentDescription="#string/img_desp" />
<TextView
android:id="#+id/txtQty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgPlus"
android:layout_toRightOf="#+id/imgMinus"
android:gravity="center_horizontal|center_vertical"
android:text="#string/qty"
android:textColor="#808080"
android:textSize="20sp" />
<TextView
android:id="#+id/TextView01"
style="#style/ListViewBottomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center_horizontal|center_vertical"
android:paddingBottom="0dp"
android:paddingTop="0dp"
android:text="#string/total"
android:textColor="#AC2A2E"
android:textSize="20sp" />
</RelativeLayout>
<ImageView
android:id="#+id/imgDiscount"
android:layout_width="30dp"
android:layout_height="40dp"
android:layout_alignRight="#+id/txtTitl"
android:layout_alignTop="#+id/txtTitl"
android:background="#drawable/label"
android:contentDescription="#string/img_desp" />
</RelativeLayout>
I think I've provided sufficient information to understand the problem. GeneralHelper is a web service class to get JSON data from server.
Here I want to get order details by the user. But I am facing some problems as following...
List Items are not clickable, and when I put event handling code, it is not working
How to handle onClick event of ImageButton(imgPlus and (imgMinus) which is placed in ListView item. I tried with the code written in comment in SwipeTabFragment.java, But it is also not working.
Last problem is, Tabs are switching very well when we swipe left or right, but if we click on tabs, then not able to switch.
Please help me to solve above problems or any one of them. Thank You!
How to use LinearLayout:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="400dp" >
<LinearLayout
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</RelativeLayout>
prompts.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type Your Name : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editTextDialogUserInput"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
row.xml
<?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="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/layoutbg"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="#+id/del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REMOVE" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.bean.FriendBean;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout mList;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
int loader = R.drawable.loader;
int i;
String val;
// public LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (LinearLayout) findViewById(R.id.layout1);
final ImageLoader img = new ImageLoader(getApplicationContext());
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsonarray.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("json");
Log.e("Length", "" + jsonarray.length());
for (i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
String friend_name = jsonObj.getString("friend_name");
String friend_phone = jsonObj.getString("friend_phone");
String url = jsonObj.getString("image_url");
FriendBean bean = new FriendBean(url, friend_name, friend_phone);
arr.add(bean);
Log.e("u", url);
Log.e("friend_name", friend_name);
Log.e("friend_phone", friend_phone);
LayoutInflater vi = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = vi.inflate(R.layout.row, null);
final ImageView im = (ImageView) v.findViewById(R.id.img);
final TextView t1 = (TextView) v.findViewById(R.id.name);
final TextView t2 = (TextView) v.findViewById(R.id.num);
final Button del = (Button) v.findViewById(R.id.del);
img.DisplayImage(url, loader, im);
t1.setText(friend_name);
t2.setText(String.valueOf(i));
mList.addView(v);
t1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
userInput.setText(t1.getText().toString());
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to
// result
// edit text
int f = Integer.parseInt(t2.getText()
.toString());
Toast.makeText(getApplicationContext(),
"Position " + f, Toast.LENGTH_SHORT)
.show();
val = userInput.getText().toString();
Toast.makeText(getApplicationContext(),
val, Toast.LENGTH_SHORT).show();
t1.setText(val);
// mList.addView(v1);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated
// method
// stub
Toast.makeText(
getApplicationContext(),
"Previously "
+ mList.getChildCount(),
Toast.LENGTH_SHORT).show();
int f = Integer.parseInt(t2.getText()
.toString());
mList.removeViewAt(f);
Toast.makeText(
getApplicationContext(),
"Position "
+ t1.getText().toString(),
Toast.LENGTH_SHORT).show();
myFunction(mList);
}
});
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Log.e("MSG", "HI");
}
});
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Previously " + mList.getChildCount(),
Toast.LENGTH_SHORT).show();
int f = Integer.parseInt(t2.getText().toString());
mList.removeViewAt(f);
Toast.makeText(getApplicationContext(), "Position " + f,
Toast.LENGTH_SHORT).show();
myFunction(mList);
}
});
im.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
t1.getText().toString(), Toast.LENGTH_SHORT).show();
return false;
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void myFunction(LinearLayout l) {
LayoutInflater vi = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.row, null);
int c = l.getChildCount();
for (int j = 0; j < c; j++) {
v = l.getChildAt(j);
TextView t2 = (TextView) v.findViewById(R.id.num);
t2.setText(String.valueOf(j));
}
Toast.makeText(getApplicationContext(), "Finally " + c,
Toast.LENGTH_SHORT).show();
}
}
jsonarray.json (put this on assets folder)
{ "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Madhumoy",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sattik",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Koushik",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Himanshu",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sandy",
"friend_phone" : "123"
}
] }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.customlist"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.customlist.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
FriendBean.java
public class FriendBean {
private String Image;
private String name;
private String ph;
public FriendBean(String Image,String name,String ph){
this.Image = Image;
this.name = name;
this.ph = ph;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPh() {
return ph;
}
public void setPh(String ph) {
this.ph = ph;
}
}
Just avoid the ImageLoader class. I expect that you can show a image from an URL. If you can do that then just use your method to show a image from an URL to the im ImageView...
Just create a new project with this files and you will understand this..
You have intentionally commented ListView's onItemclicklistener inside your onCreateView
Uncomment the code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_items, container, false);
list = (ListView) rootView.findViewById(R.id.lstItems);
initializeFoodItems(category_id);
list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
//ListView event handling
list.setOnItemClickListener(itemClickListener );
return rootView;
}
ImageVIew Click
Write this method anywhere
// Item Click Listener for the listview
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout linearLayoutParent = (RelativeLayout ) container;
// Getting the inner Linear Layout
RelativeLayout linearLayoutChild = (RelativeLayout ) linearLayoutParent.getChildAt(1);
// Getting the Country TextView
ImageView iv = (ImageView) linearLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), "Image CLicked", Toast.LENGTH_SHORT).show();
}
};
I got solution of two problems. That are...
How to handle onClick event of ImageButton(imgPlus and imgMinus) which is placed in ListView item. I tried with the code written in comment in SwipeTabFragment.java, But it is also not working.
Solution :
I am handling onclick event in ItemListAdapter.java that is working fine. Below is the code of this file. That may be helpful for others.
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
public class ItemListAdapter extends ArrayAdapter<String> {
static int grand_total;
private final Activity context;
private final String title[];
private final String price[];
private final String discount[];
public ItemListAdapter(Activity context, String[] title, String[] price, String[] discount) {
super(context, R.layout.item_list, title);
this.context = context;
this.title = title;
this.price = price;
this.discount = discount;
}
#SuppressLint({ "ViewHolder", "InflateParams" })
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View row = inflater.inflate(R.layout.item_list, null,true);
((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
final int item_price = Integer.parseInt(price[position]);
((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange), PorterDuff.Mode.SRC_ATOP);
//Increasing Quantity
row.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
if (Integer.parseInt(qty.getText().toString()) > 0) {
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
//Decreasing Quantity
row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
if (Integer.parseInt(qty.getText().toString()) > 0) {
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
return row;
}
}
Tabs are switching very well when we swipe left or right, but if we click on tabs, then not able to switch.
Solution : I simply put the following line in the onTabSelected() and make the tabs working. This was suggested by #AvishekDas. Again Thanks for this.
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
But I'm still finding problem 1. My listView is not clickable. If any of you have solution then please post. Thank you!
My activity extends ListActivity. This is how I set the list to the Adapter:
this.setListAdapter(new ArrayAdapter<String>(
this, R.layout.imgTxtView,
R.id.items,retrievedTasks));
RetrivedTasks is a String of tasks/items stored in shared pref.
I have this List in a Linear Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
And this is another Linear Layout (imgTxtView) that serves as a row in the List
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_marginBottom="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:src="#drawable/star" />
<TextView
android:id="#+id/Itemname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17sp"
android:paddingTop="5dp"/>
</LinearLayout>
The idea is when you click on just the image the image will change and the background for the TextView items.
All solutions talk about a Custom Adapter.
Now, is there a way to accomplish this WITHOUT using one?
EDIT. A piece of code Im trying atm.
ImageView theStar = (ImageView) findViewById(R.id.icon);
theStar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
Toast.makeText(getApplicationContext(), "item clicked: "+Integer.toString(position), Toast.LENGTH_LONG).show();
}
});
EDIT_2. Now full code to both linear layouts uploaded. I hate it when ppl post long lines of code, I was trying to avoid that.
I know its not hard to implement a Custom Adapter, but was curious if someone managed to do this without using one.
I don't think so. My understanding is that this a custom listview and you need to use a custom adapter to have access to all properties.
sorry for my English, but I hope and serve him this. This is 100% functional !, works for me
package com.exa.Usuario;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import com.app.basedatos.BD_Mundial;
import com.app.basedatos.ConnectionDetector;
import com.app.basedatos.responseJson;
import com.exa.citas.DetalleContacto;
import com.exa.citas.R;
public class Contactos extends Activity implements OnClickListener, OnQueryTextListener {
public class AtributosContactos {
String nombre,apellido,correo,telefono;
String idContacto,Separador;
}
ListView list_contactos;
SearchView search_contact;
private CodeLearnAdapter chapterListAdapter;
BD_Mundial adb = new BD_Mundial(this);
SQLiteDatabase db;
String idUsu;
SharedPreferences.Editor editor;
SharedPreferences prefs;
Boolean isInternetPresent = false;
ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_usuario_contactos);
getActionBar().hide();
header();
prefs = getSharedPreferences("Datos_usuario", Context.MODE_PRIVATE);
idUsu = prefs.getString("idUsu","");
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
#Override
protected void onResume(){
super.onResume();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
list_contactos = (ListView) findViewById(R.id.list_contactos);
search_contact = (SearchView) findViewById(R.id.search_contact);
list_contactos.setTextFilterEnabled(true);
new Async_ranking().execute();
setupSearchView();
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent){
SincronizaContactos();
EliminaContactos();
}
list_contactos.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
AtributosContactos ch=chapterListAdapter.getCodeLearnChapter(arg2);
if(ch.Separador.equals("0")){
Intent i=new Intent (getApplicationContext(),DetalleContacto.class);
i.putExtra("Nombre", ch.nombre);
i.putExtra("Apellido", ch.apellido);
i.putExtra("Telefono", ch.telefono);
i.putExtra("Correo", ch.correo);
startActivity(i);
//Log.i("ID:", ch.idContacto);
}
}
});
}
private void setupSearchView() {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search_contact.setIconifiedByDefault(false);
search_contact.setOnQueryTextListener(this);
search_contact.setSubmitButtonEnabled(false);
search_contact.setQueryHint("Buscar Contactos");
search_contact.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
if (TextUtils.isEmpty(newText)) {
new Async_ranking().execute();;
} else {
//String contacto=newText.replaceAll("\\s", "");
//Log.i("", "Entro"+newText);
chapterListAdapter.filter(newText);
//list_contactos.setFilterText(newText.toString());
}
return true;
}
public void header() {
Button back = (Button) findViewById(R.id.btn_back);
ImageView btn_1 = (ImageView) findViewById(R.id.btn_1);
ImageView btn_2 = (ImageView) findViewById(R.id.btn_2);
TextView txtTitulo = (TextView) findViewById(R.id.txtTitulo);
btn_2.setImageResource(R.drawable.btn_add);
back.setOnClickListener(this);
btn_1.setOnClickListener(this);
btn_2.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.btn_2:
Intent i = new Intent(getApplicationContext(), AddContacto.class);
startActivity(i);
break;
case R.id.btn_back:
onBackPressed();
break;
}
}
private class Async_ranking extends AsyncTask<String, Void, SoapObject> {
#Override
protected SoapObject doInBackground(String... params) {
chapterListAdapter = new CodeLearnAdapter();
return null;
}
#Override
protected void onPostExecute(SoapObject result) {
list_contactos.setAdapter(chapterListAdapter);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public class CodeLearnAdapter extends BaseAdapter {
List<AtributosContactos> codeLeanChapterList = getDataForListView();
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
ArrayList<String> mItems = new ArrayList<String>();
#Override
public int getCount() {
// TODO Auto-generated method stub
return codeLeanChapterList.size();
}
#Override
public AtributosContactos getItem(int arg0) {
// TODO Auto-generated method stub
return codeLeanChapterList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
LayoutInflater inflater = (LayoutInflater) Contactos.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arg1 = inflater.inflate(R.layout.item_contacto, arg2, false);
}
TextView txt_nombre = (TextView) arg1 .findViewById(R.id.txt_nombre);
TextView txt_num = (TextView) arg1 .findViewById(R.id.txt_num);
TextView txt_correo= (TextView) arg1 .findViewById(R.id.txt_correo);
final AtributosContactos ch = codeLeanChapterList.get(arg0);
if(ch.Separador.equals("1")){
txt_num.setVisibility(View.GONE);
txt_correo.setVisibility(View.GONE);
arg1.setBackgroundColor(Color.parseColor("#eaeaea"));
arg1.setSelected(false);
arg1.setEnabled(false);
//arg1.setFocusable(false);
}else {
txt_num.setVisibility(View.VISIBLE);
txt_correo.setVisibility(View.VISIBLE);
arg1.setBackgroundColor(Color.parseColor("#00000000"));
arg1.setSelected(true);
arg1.setEnabled(true);
//arg1.setFocusableInTouchMode(true);
}
txt_nombre.setText(ch.nombre+" "+ch.apellido);
txt_num.setText(ch.telefono);
txt_correo.setText(ch.correo);
// Log.i("Letra1: " +arg0,"Valor separador "+ch.Separador);
return arg1;
}
/**
*
* #param contacto
*
* Filtra la lista de contactos aqui se hace toda la búsqueda... Soy una Pipi! :3 ajaja
*/
public void filter(String contacto) {
contacto = contacto.toLowerCase(Locale.getDefault());
contacto= (contacto );
codeLeanChapterList.clear();
if (contacto.length() == 0) {
codeLeanChapterList = getDataForListView();
} else {
for (AtributosContactos wp : getDataForListView()) {
String nombreContacto=wp.nombre+" "+wp.apellido;
//Busca por nombre y apellido
if (nombreContacto.toLowerCase(Locale.getDefault()).contains( contacto) ) {
codeLeanChapterList.add(wp);
}else/**Busca por correo */
if (wp.correo.toLowerCase(Locale.getDefault()).contains( contacto) ) {
codeLeanChapterList.add(wp);
}else /**Busca por telefono */
if (wp.telefono.toLowerCase(Locale.getDefault()).contains( contacto) ) {
codeLeanChapterList.add(wp);
}
}
list_contactos.setAdapter(chapterListAdapter);
}
}
public AtributosContactos getCodeLearnChapter(int position) {
return codeLeanChapterList.get(position);
}
}
#SuppressLint("DefaultLocale")
public List<AtributosContactos> getDataForListView() {
final List<AtributosContactos> codeLeanChaptersList = new ArrayList<AtributosContactos>();
SQLiteDatabase db = adb.openDatabase();
Cursor mCursor = db.rawQuery( "SELECT idContacto, nombre,apellido,correo,telefono FROM tblContacto"
+ " where borrado=0 order by nombre COLLATE BINARY COLLATE NOCASE", null);
ArrayList<String> Header = new ArrayList<String>();
if (mCursor.moveToFirst()) {
do {
AtributosContactos chapter = new AtributosContactos();
AtributosContactos ch = new AtributosContactos();
String letra = mCursor.getString(1).substring(0, 1);
String c = letra.toUpperCase();
if (Header.size() > 0) {
int cont = 0;
for (int i = 0; i < Header.size(); i++) {
if (Header.get(i).equals(c)) {
cont++;
}
}
if (cont == 0) {
char res= c.charAt(0);
if ((res >= 'a' && res <= 'z') || (res >= 'A' && res <= 'Z')) {
Header.add(c);
ch.idContacto = " ";
ch.nombre = c;
ch.apellido = " ";
ch.correo = " ";
ch.telefono = " ";
ch.Separador = "1";
codeLeanChaptersList.add(ch);
chapter.idContacto = mCursor.getString(0);
chapter.nombre = mCursor.getString(1);
chapter.apellido = mCursor.getString(2);
chapter.correo = mCursor.getString(3);
chapter.telefono = mCursor.getString(4);
chapter.Separador = "0";
codeLeanChaptersList.add(chapter);
} else {
// Agregamos el contacto
chapter.idContacto = mCursor.getString(0);
chapter.nombre = mCursor.getString(1);
chapter.apellido = mCursor.getString(2);
chapter.correo = mCursor.getString(3);
chapter.telefono = mCursor.getString(4);
chapter.Separador = "0";
codeLeanChaptersList.add(chapter);
}
} else {
// Agregamos el contacto
chapter.idContacto = mCursor.getString(0);
chapter.nombre = mCursor.getString(1);
chapter.apellido = mCursor.getString(2);
chapter.correo = mCursor.getString(3);
chapter.telefono = mCursor.getString(4);
chapter.Separador = "0";
codeLeanChaptersList.add(chapter);
}
} else {
char res= c.charAt(0);
if ((res >= 'a' && res <= 'z') || (res >= 'A' && res <= 'Z')) {
Header.add(c);
ch.idContacto = " ";
ch.nombre = c;
ch.apellido = " ";
ch.correo = " ";
ch.telefono = " ";
ch.Separador = "1";
codeLeanChaptersList.add(ch);
chapter.idContacto = mCursor.getString(0);
chapter.nombre = mCursor.getString(1);
chapter.apellido = mCursor.getString(2);
chapter.correo = mCursor.getString(3);
chapter.telefono = mCursor.getString(4);
chapter.Separador = "0";
codeLeanChaptersList.add(chapter);
} else {
// Agregamos el contacto
chapter.idContacto = mCursor.getString(0);
chapter.nombre = mCursor.getString(1);
chapter.apellido = mCursor.getString(2);
chapter.correo = mCursor.getString(3);
chapter.telefono = mCursor.getString(4);
chapter.Separador = "0";
codeLeanChaptersList.add(chapter);
}
}
} while (mCursor.moveToNext());
}
db.close();
adb.close();
return codeLeanChaptersList;
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
}
item_contacto.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="vertical" >
<TextView
android:id="#+id/txt_nombre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="Juan Perez"
android:textColor="#000"
android:textSize="20sp" />
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" >
<TextView
android:id="#+id/txt_correo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="gortiz#exagononononono.net"
android:textColor="#color/negro" />
<TextView
android:id="#+id/txt_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="01234567890"
android:textColor="#color/negro" />
</TableRow>
</LinearLayout>
Activity main
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical|center_horizontal|center"
android:background="#fff"
android:orientation="vertical"
tools:context="com.exa.Usuario.Contactos" >
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/header" />
<SearchView
android:id="#+id/search_contact"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="26dp"
android:iconifiedByDefault="false" />
<View
android:id="#+id/view1"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#EAEAEA" />
<ListView
android:id="#+id/list_contactos"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" >
</ListView>
</LinearLayout>
hope and be your help
It's not required to use Adapters with ListView but I am concerned you may have UI overlapping issues between ListView, TextView and ImageView. Let's assume you don't.
There are listeners for ImageView. You need setOnClickListener in your case. A crude example:
ImageView theStar = (ImageView)v.findViewById(R.id.icon);
theStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(...
TextView itemText = (TextView) v.findViewById(R.id.items);
itemText.setBackground(R.Color...
}
});
I hope this gives you an idea. Keep us posted.