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;
}
}
Related
I am new with Android Studio, and I would like to try a listview with pictures on the left shown below. I managed to make such a list with a simple list item, but when I changed the simple item list with an ActivityList, it does not work anymore.
How can I change the ArrayList to combine imageviews with the names? I think it could be possible by using a new class which contains the imageview and name instead of strings.
Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<String> myFriends = new ArrayList<String>(asList("Mark","Jane","Sussy","Jan"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.activity_list_item
, myFriends);
friendsListView.setAdapter(arrayAdapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + myFriends.get(i), Toast.LENGTH_LONG).show();
}
});
}
}
You're right, you need to create a model class for your list item; this model class contains things that differ from item to item; for instance in your shared picture, a list item has a typical of a picture and a title; and so your model class.
Next, instead of having ArrayList<String>, use ArrayList<Item>; where Item is the model class
Third, you need to create a custom adapter that extends from ArrayAdapter<Item>; that is because you can't use the built-in list item layout "android.R.layout.activity_list_item", because it just offers you with a single string; and now you need to accompany a picture with it.
Below is a simple demo
Model class (Item.java)
class Item {
private int mPicture;
private String mTitle;
int getPicture() {
return mPicture;
}
Item(int picture, String title) {
mPicture = picture;
mTitle = title;
}
String getTitle() {
return mTitle;
}
}
List View Adapter (ListViewAdapter.java)
public class ListViewAdapter extends ArrayAdapter<Item> {
ListViewAdapter(#NonNull Context context, ArrayList<Item> items) {
super(context, 0, items);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null) {
listItem = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
// Get the {#link Word} object located at this position in the list
Item currentItem = getItem(position);
ImageView picture = listItem.findViewById(R.id.IvPicture);
picture.setBackgroundResource(currentItem.getPicture());
TextView title = listItem.findViewById(R.id.tvTitle);
title.setText(currentItem.getTitle());
return listItem;
}
}
Activity class
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.item1, "Item1"));
items.add(new Item(R.drawable.item2, "Item2"));
items.add(new Item(R.drawable.item3, "Item3"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
Activity Layout (activity_main.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">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
List item layout (list_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/IvPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item" />
</LinearLayout>
You have to have 3 images into res/drawable named item1, item2, and item3
Hope this satisfies your need.
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"
android:background="#color/grey_300"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</RelativeLayout>
cards_layout.xml code:
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/color_white"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/imageView"
android:tag="image_tag"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_weight="2"
android:orientation="vertical"
>
<TextView
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Name"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="#+id/textViewVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Version"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
menu_main.xml code:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="#+id/add_item"
android:title="Add"
android:orderInCategory="100"
app:showAsAction="always"/>
</menu>
MainActivity.java
package com.journaldev.recyclerviewcardview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<DataModel> data;
static View.OnClickListener myOnClickListener;
private static ArrayList<Integer> removedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<DataModel>();
for (int i = 0; i < MyData.nameArray.length; i++) {
data.add(new DataModel(
MyData.nameArray[i],
MyData.versionArray[i],
MyData.id_[i],
MyData.drawableArray[i]
));
}
removedItems = new ArrayList<Integer>();
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
private static class MyOnClickListener implements View.OnClickListener {
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
removeItem(v);
}
private void removeItem(View v) {
int selectedItemPosition = recyclerView.getChildPosition(v);
RecyclerView.ViewHolder viewHolder
= recyclerView.findViewHolderForPosition(selectedItemPosition);
TextView textViewName
= (TextView) viewHolder.itemView.findViewById(R.id.textViewName);
String selectedName = (String) textViewName.getText();
int selectedItemId = -1;
for (int i = 0; i < MyData.nameArray.length; i++) {
if (selectedName.equals(MyData.nameArray[i])) {
selectedItemId = MyData.id_[i];
}
}
removedItems.add(selectedItemId);
data.remove(selectedItemPosition);
adapter.notifyItemRemoved(selectedItemPosition);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_item) {
//check if any items to add
if (removedItems.size() != 0) {
addRemovedItemToList();
} else {
Toast.makeText(this, "Nothing to add", Toast.LENGTH_SHORT).show();
}
}
return true;
}
private void addRemovedItemToList() {
int addItemAtListPosition = 3;
data.add(addItemAtListPosition, new DataModel(
MyData.nameArray[removedItems.get(0)],
MyData.versionArray[removedItems.get(0)],
MyData.id_[removedItems.get(0)],
MyData.drawableArray[removedItems.get(0)]
));
adapter.notifyItemInserted(addItemAtListPosition);
removedItems.remove(0);
}
}
CustomAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private ArrayList<DataModel> dataSet;
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
TextView textViewVersion;
ImageView imageViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public CustomAdapter(ArrayList<DataModel> data) {
this.dataSet = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
view.setOnClickListener(MainActivity.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
ImageView imageView = holder.imageViewIcon;
textViewName.setText(dataSet.get(listPosition).getName());
textViewVersion.setText(dataSet.get(listPosition).getVersion());
imageView.setImageResource(dataSet.get(listPosition).getImage());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
DataModel.java
public class DataModel {
String name;
String version;
int id_;
int image;
public DataModel(String name, String version, int id_, int image) {
this.name = name;
this.version = version;
this.id_ = id_;
this.image=image;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public int getImage() {
return image;
}
public int getId() {
return id_;
}
}
MyData.java
public class MyData {
static String[] nameArray = {"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich","JellyBean", "Kitkat", "Lollipop", "Marshmallow"};
static String[] versionArray = {"1.5", "1.6", "2.0-2.1", "2.2-2.2.3", "2.3-2.3.7", "3.0-3.2.6", "4.0-4.0.4", "4.1-4.3.1", "4.4-4.4.4", "5.0-5.1.1","6.0-6.0.1"};
static Integer[] drawableArray = {R.drawable.cupcake, R.drawable.donut, R.drawable.eclair,
R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.ics,
R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop,R.drawable.marsh};
static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.abc, "Item1"));
items.add(new Item(R.drawable.def, "Item2"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView.setAdapter(adapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + items.get(i), Toast.LENGTH_LONG).show();
}
});
}
}
I m trying to add the value from textview dynamically to listview.For that I have created another layout to take the values from user. but I'm not able to do that. I have tried many things. Kindly help.. Here is my code.
package com.example.chetan.assignment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// String[] name= {"Apple","Banana","Mango","PineApple"};
//String[] price = {"Rs.40","Rs.60","Rs.70","Rs.80"};
List<String> names = new ArrayList<String>();
//String[] names = {"names"};
List<String> prices = new ArrayList<String>();
//String[] prices = {"prices"};
String name = getIntent().getStringExtra("name");
String price = getIntent().getStringExtra("price");
if(count==0) {
names.add(0, "name");
prices.add(0, "price");
}
if (count>0) {
names.add(count, name);
prices.add(count,price);
}
count++;
ListAdapter MyAdapter = new MyAdapter(names, prices, this);
ListView theList = (ListView) findViewById(R.id.listView);
theList.setAdapter(MyAdapter);
}
public void buttonClick(View view) {
Intent i = new Intent(this, Addlayout.class);
startActivity(i);
}
}
package com.example.chetan.assignment;
package com.example.chetan.assignment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
class MyAdapter extends BaseAdapter {
String[] name;
String[] price;
Context context;
private static LayoutInflater myInflater = null;
public MyAdapter(String[] name, String[] price, Context context) {
this.name = name;
this.price = price;
this.context = context;
myInflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return name.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView nametext;
TextView pricetext;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder myholder = new Holder();
View myViews = myInflater.inflate(R.layout.myview,parent,false);
myholder.nametext= (TextView) myViews.findViewById(R.id.textView);
myholder.pricetext= (TextView) myViews.findViewById(R.id.textView2);
myholder.nametext.setText(name[position]);
myholder.pricetext.setText(price[position]);
return myViews;
}
}
package com.example.chetan.assignment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Addlayout extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addlayout);
}
public void Onclickbutton(View view){
EditText nametext = (EditText)findViewById(R.id.editText);
EditText pricetext = (EditText)findViewById(R.id.editText2);
String namedata = nametext.getText().toString();
String pricedata = pricetext.getText().toString();
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("name",namedata);
intent.putExtra("price",pricedata);
startActivity(intent);
}
}
Here you can do something like this:
Instead of simple listview I have used RecyclerView as it has better performance.
//First create a Data class for name and price
public class Data implements Serializable {
private String name,price;
public Data(){}
public Data(String name,String price){
this.name = name;
this.price = price;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//your Addlayout class
public class Addlayout extends AppCompatActivity {
List<Data> dataList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addlayout);
}
public void Onclickbutton(View view){
EditText nameText = (EditText)findViewById(R.id.editText);
EditText priceText = (EditText)findViewById(R.id.editText2);
String nameData = nameText.getText().toString();
String priceData = priceText.getText().toString();
Data data = new Data(nameData, priceData);
dataList.add(data);
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("List", (Serializable) dataList);
startActivity(intent);
}
}
//add layout xml
//change layout according to you
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_addlayout"
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="com.example.mmc.testproject.Addlayout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="name"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="13dp"
android:id="#+id/editText" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="price"
android:layout_below="#+id/editText"
android:layout_alignEnd="#+id/editText"
android:layout_marginTop="18dp"
android:id="#+id/editText2" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginStart="43dp"
android:layout_marginTop="36dp"
android:onClick="Onclickbutton"
android:id="#+id/button" />
</RelativeLayout>
//Then your Listview Adapter
public class ListViewAdaptor extends RecyclerView.Adapter<ListViewAdaptor.MyViewHolder> {
private List<Data> mDataList;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView name,price;
public MyViewHolder(View view){
super(view);
name = (TextView) view.findViewById(R.id.name);
price= (TextView) view.findViewById(R.id.price);
}
}
public ListViewAdaptor(List<Data> dataList){
this.mDataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Data data = mDataList.get(position);
holder.name.setText(data.getName());
holder.price.setText(data.getPrice());
}
#Override
public int getItemCount() {
return mDataList.size();
}
}
//your Listview layout to show name and price
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/name"
android:text="name"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/price"
android:text="price"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
</LinearLayout>
//And finally the main Activity
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ListViewAdaptor mAdapter;
private List<Data> mDataList;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
Intent i = getIntent();
mDataList = (List<Data>) i.getSerializableExtra("List");
Log.e(TAG,"Datalist size : "+mDataList.size());
mAdapter = new ListViewAdaptor(mDataList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mAdapter);
}
}
//and main Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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="com.example.mmc.testproject.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Hope it helps!!!
This is may XML class random values in which we make a row that I want to delete
randomvalues.xml
<LinearLayout
android:id="#+id/linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addbtn">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/img1"
/>
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageButton
android:id="#+id/removebtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/remove"/>
</LinearLayout>
</LinearLayout>
this is my activity_main XML in which i used a list view to show a row that I make in random values XML file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.chaqeel.taskviews.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear">
<ImageButton
android:id="#+id/addbtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/add"
android:layout_marginLeft="280dp"/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear"
>
</ListView>
</RelativeLayout>
This is MainActivity.java in which we used a array to show the values
MainActivity.java
package com.example.chaqeel.taskviews;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.img1, R.drawable.img2, R.drawable.img3,
R.drawable.img4, R.drawable.img5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new dataListAdapter(Names, Address, Images));
}
class dataListAdapter extends BaseAdapter {
String[] Name, Addres;
int[] imge;
/*dataListAdapter() {
Name = null;
Addres = null;
imge=null;
}*/
public dataListAdapter(String[] text, String[] text1, int[] text3) {
Name = text;
Addres = text1;
imge = text3;
}
public int getCount() {
return Name.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomvalues, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(Names[position]);
Addres.setText(Address[position]);
imge.setImageResource(Images[position]);
final ArrayList<String> lvv= new ArrayList<>();
Collections.addAll(lvv,Names);
// Collection.addAll(lvv,Address);
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lvv.remove(Names);
lvv.remove(Address);
notifyDataSetChanged();
}
});
return (row);
}
}
}
In the onClickListener try the following code
youradapter.notifyDataSetChanged();
In the deletebutton onClickListener try this
Names = ArrayUtils.removeElement(Names,Names[position]);
Address = ArrayUtils.removeElement(Address,Address[position]);
notifyDataSetChanged();
Though it is advised to use OOP concept like a class to hold the Arrays of Names,Address and Images.
Try below code:
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Name = ArrayUtils.removeElement(Names, Names[position]);
Address = ArrayUtils.removeElement(Address, Address[position]);
imge = ArrayUtils.removeElement(imge, imge[position]);
notifyDataSetChanged();
}
});
change this:
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setTag(position);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) view.getTag();
lvv.remove(index.intValue());
notifyDataSetChanged();
}
});
Are you from Chakwal? I am Chakwalian. Again StackOverflow is telling me that my answer does not meet thier quality requirements.
You need to better idea to use Model class as below:-
create a model class MyModel.class
import java.util.ArrayList;
import java.util.List;
public class MyModel {
String Name, Address;
int image;
public MyModel(String name, String address, int image) {
Name = name;
Address = address;
this.image = image;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
}
and then add with adapter class see below:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.ic_menu_camera, R.drawable.ic_menu_gallery, R.drawable.ic_menu_manage,
R.drawable.ic_menu_send, R.drawable.ic_menu_share};
private List<MyModel> myModel=new ArrayList<>();
private DataListAdapter dataListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lv = (ListView) findViewById(R.id.listview);
for(int i=0;i<Names.length;i++){
myModel.add( new MyModel(Names[i],Address[i],Images[i]));
}
dataListAdapter=new DataListAdapter(myModel);
lv.setAdapter(dataListAdapter);
}
class DataListAdapter extends BaseAdapter {
private List<MyModel> myModel=new ArrayList<>();
public DataListAdapter(List<MyModel> myModel) {
this.myModel=myModel;
}
public int getCount() {
return myModel.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomevalue, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(myModel.get(position).getName());
Addres.setText(myModel.get(position).getAddress());
imge.setImageResource(myModel.get(position).getImage());
ImageButton dltbutton = (ImageButton) row.findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myModel.remove(position);
notifyDataSetChanged();
}
});
return (row);
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
add android:onClick="addMore" to your add button
it will fine Happy Coding :)
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo) item.getMenuInfo();
pos=info.position;
deleteditem=myList.get(pos);
if(item.getTitle()=="Delete")
{
String delete = myList.get(pos);
File f = new File(path + "/"+ delete);
if (f != null && f.exists())
{
f.delete();
}
myList.remove(pos);
adapter. notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "item has deleted",Toast.LENGTH_LONG).show();
}
I'm struggling with assigning my listview row more than one textview.
I want my row to have one textview for a person's name, one for address and one for age - but I'm not succeeding in doing so.
If someone could provide me with a simple example, that would be great.
Thanks!
Here's my custom ArrayAdapter
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater = null;
private ArrayList<Invoice> peopleList;
private final class ViewHolder {
TextView kidLabel;
TextView restLabel;
TextView fristLabel;
TextView amountLabel;
}
private ViewHolder mHolder = null;
public MyAdapter(Context context) {
Context mContext = context;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return peopleList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
mHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
convertView.setTag(mHolder);
} else {
mHolder = (ViewHolder) convertView.getTag();
}
mHolder.kidLabel = (TextView) convertView.findViewById(R.id.kidLabel);
mHolder.kidLabel.setText(peopleList.get(position).getKID());
mHolder.fristLabel = (TextView) convertView
.findViewById(R.id.fristLabel);
mHolder.fristLabel.setText(peopleList.get(position).getDueDate());
mHolder.restLabel = (TextView) convertView.findViewById(R.id.restLabel);
mHolder.restLabel.setText(peopleList.get(position).getDueAmount());
mHolder.amountLabel = (TextView) convertView
.findViewById(R.id.amountLabel);
mHolder.amountLabel.setText(peopleList.get(position).getDueAmount());
return convertView;
}
}
And Here's my custom row xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="45dip"
android:src="#drawable/cellback" android:scaleType="fitXY"/>
<TextView
android:id="#+id/kidLabel"
android:layout_width="160dip"
android:layout_height="25dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="13dip" android:textColor="#333"/>
<TextView
android:id="#+id/fristLabel"
android:layout_width="160dip"
android:layout_height="20dip"
android:layout_marginTop="25dip"
android:textSize="11dip" android:textColor="#999"/>
<TextView
android:id="#+id/amountLabel"
android:layout_width="160dip"
android:layout_height="25dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="13dip" android:layout_marginLeft="160dip" android:gravity="right" android:textColor="#333"/>
<TextView
android:id="#+id/restLabel"
android:layout_width="160dip"
android:layout_height="20dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="11dip" android:layout_marginLeft="160dip" android:layout_marginTop="25dip" android:gravity="right" android:textColor="#999"/>
</RelativeLayout>
First,you should create a xml to describe what your list cell likes,called cell.xml,for example:
<?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" android:background="#color/spink">
<TextView
android:id="#+id/name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/address_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Second,create a adapter.It helps your listview to show data:
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater = null;
private ArrayList<People> peopleList;
private final class ViewHolder {
TextView nameTextView;
TextView addressTextView;
}
private ViewHolder mHolder = null;
public MyAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return peopleList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
mHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.cell, null);
convertView.setTag(mHolder);
} else {
mHolder = (ViewHolder)convertView.getTag();
}
mHolder.nameTextView (TextView)convertView.findViewById(R.id.name_textView);
mHolder.nameTextView.setText(peopleList.get(position).getName());
mHolder.addressTextView = (TextView)convertView.findViewById(R.id.address_textView);
mHolder.addressTextView.setText(peopleList.get(position).getAddress());
return convertView;
}
}
Finally,when you want to show the data,do this in your activity:
listView.setAdapter(new MyAdapter());
hope it helps you.
You need to create a custom listview layout and a custom array adapter (I have also created a custom class to work with the layout).
An example of this is:
Custom class that works with the custom listview layout:
package id10778734.sceresini.week4.exercise3.views;
import id10778734.sceresini.week4.exercise3.R;
import id10778734.sceresini.week4.exercise3.Constants;
import id10778734.sceresini.week4.exercise3.tasks.Task;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TaskListItem extends LinearLayout {
private Task mTask;
private ImageView mEmailImageView;
private ImageView mPriorityImageView;
private TextView mTaskNameTextView;
private TextView mTaskResponsibleTextView;
private ImageView mDeleteImageView;
public TaskListItem (Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void onFinishInflate() {
super.onFinishInflate();
mEmailImageView = (ImageView) findViewById(R.id.list_row_layout_email_button);
mPriorityImageView = (ImageView) findViewById(R.id.list_row_layout_priority_icon);
mTaskNameTextView = (TextView) findViewById(R.id.list_row_layout_task_name);
mTaskResponsibleTextView = (TextView) findViewById(R.id.list_row_layout_responsible);
mDeleteImageView = (ImageView) findViewById(R.id.list_row_layout_delete_button);
}
public void setTask (Task task) {
mTask = task;
mEmailImageView.setTag(task);
switch (task.getPriority()) {
case Constants.LOW:
mPriorityImageView.setImageResource(R.drawable.low);
break;
case Constants.MEDIUM:
mPriorityImageView.setImageResource(R.drawable.medium);
break;
case Constants.HIGH:
mPriorityImageView.setImageResource(R.drawable.high);
break;
}
mTaskNameTextView.setText(task.getName());
mTaskResponsibleTextView.setText(task.getResponsible());
mDeleteImageView.setTag(task);
}
public Task getTask () {
return mTask;
}
public ImageView getDeleteImageView () {
return mDeleteImageView;
}
public ImageView getEmailImageView () {
return mEmailImageView;
}
}
the custom layout xml file:
<?xml version="1.0" encoding="UTF-8"?>
<id10778734.sceresini.week4.exercise3.views.TaskListItem
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/list_row_layout_email_button"
android:layout_width="36dip"
android:layout_height="36dip"
android:layout_gravity="center_vertical"
android:layout_marginLeft="4dip"
android:layout_marginRight="5dip"
android:contentDescription="#string/list_row_email_icon_description"
android:src="#android:drawable/ic_dialog_email" />
<ImageView
android:id="#+id/list_row_layout_priority_icon"
android:layout_width="24dip"
android:layout_height="24dip"
android:layout_gravity="center_vertical"
android:layout_marginLeft="4dip"
android:layout_marginRight="10dip"
android:contentDescription="#string/view_task_priority_icon_description" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
<TextView
android:id="#+id/list_row_layout_task_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/list_row_layout_responsible"
android:paddingRight="5dip"
android:textAppearance="#style/list_row_task_name" />
<TextView
android:id="#id/list_row_layout_responsible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/list_row_layout_delete_button"
android:maxWidth="100dip"
android:textAppearance="#style/list_row_task_responsible" />
<ImageView
android:id="#id/list_row_layout_delete_button"
android:layout_width="36dip"
android:layout_height="36dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:contentDescription="#string/delete_task_icon_description"
android:src="#drawable/task_delete" />
</RelativeLayout>
</id10778734.sceresini.week4.exercise3.views.TaskListItem>
And the custom array adapter:
package id10778734.sceresini.week4.exercise3;
import id10778734.sceresini.week4.exercise3.R;
import id10778734.sceresini.week4.exercise3.tasks.Task;
import id10778734.sceresini.week4.exercise3.views.TaskListItem;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class TaskListAdapter extends BaseAdapter
{
private ArrayList<Task> mTasks;
private Context mContext;
private AlertDialog unsavedChangesDialog;
private TaskManagerApplication mApp;
public TaskListAdapter(Context context, ArrayList<Task> tasks) {
super();
mApp = (TaskManagerApplication) context.getApplicationContext();
mContext = context;
mTasks = tasks;
}
#Override
public int getCount()
{
return mTasks.size();
}
#Override
public Task getItem(int position)
{
return (null == mTasks) ? null : mTasks.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
TaskListItem tli;
if (null == convertView)
{
tli = (TaskListItem) View.inflate(mContext, R.layout.list_row_layout, null);
} else
{
tli = (TaskListItem) convertView;
}
tli.setTask(mTasks.get(position));
tli.getEmailImageView().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
emailTask(v);
}
});
tli.getDeleteImageView().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
deleteTask(v);
}
});
return tli;
}
/**
* deleteTask() prompts the user with an alert dialog and presents them with
* the option to continue with the delete request or to cancel the request.
* Upon confirmation, the selected Task object which is retrieved from the
* deleteTaskIcon tag, will be removed from the list of currentTasks.
*
* #param v
*/
protected void deleteTask(View v)
{
final Task t = (Task) v.getTag();
String alertMessage = String.format(mContext.getString(R.string.delete_task_message), t.getName());
unsavedChangesDialog = new AlertDialog.Builder(mContext).setTitle(R.string.delete_task_title).setMessage(alertMessage)
// Delete the task and refresh the adapter.
.setPositiveButton(R.string.delete_task_delete, new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1)
{
// Remove task from array list
mTasks.remove(t);
// Remove task from Database
mApp.deleteTask(t);
// Display toast message stating the task was deleted
mApp.displayToast(Constants.TASK_DELETED);
// Update listView with modified adapter
forceReload();
}
})
// Cancel the delete request and do nothing.
.setNegativeButton(R.string.delete_task_cancel, new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1)
{
unsavedChangesDialog.cancel();
}
}).create();
unsavedChangesDialog.show();
}
/**
* emailTask() populates the selected task into an intent which allows the
* user to select a client to send the task. This is formatted for email
* clients.
*
* #param v
*/
protected void emailTask(View v)
{
// Retrieve the task that is allocated to this RowView
final Task t = (Task) v.getTag();
// Instantiate the intent that will be used to call the email client
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
// Variables/Arrays to hold email attributes
String[] emailRecipients = { mContext.getString(R.string.email_task_to_email) };
String emailType = mContext.getString(R.string.email_task_type);
String emailTitle = mContext.getString(R.string.email_task_title);
String emailSubject = String.format(mContext.getString(R.string.email_task_subject), t.getName());
String emailMessage = String.format(mContext.getString(R.string.email_task_message), t.getResponsible(), t.getName(), mContext.getString(t.getPriorityStringId()));
// Add the email attributes to the intent
emailIntent.setType(emailType);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailRecipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, emailSubject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailMessage);
// Start intent
mContext.startActivity(Intent.createChooser(emailIntent, emailTitle));
}
/**
* Refreshes the ListView with the modified dataset.
*/
public void forceReload()
{
notifyDataSetChanged();
}
}
ive been attempting to add subrows to a listview. I have a taxi app which at present shows a list of taxi company names, i want to be able to add some sub rows in which show address, postcode etc.
I have had some attempts at this but none have been successful. I am calling my strings from an array in the strings.xml file. My code at the moment is :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You Have Selected: "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), Booking.class);
intent.putExtra("booking", taxi[selectedPosition]);
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
If anyone can help me get round this problem it would be very much appreciated.
The original question i asked is here: Android - Adding Subitem to a listview
Thanks
Whoops, just noticed this one. I'll paste my edited answer into here:
Okay, just for kicks, I threw this together. It compiles and functions correctly, see if you can adapt it for your particular needs:
layout/taxi_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="100dp"
android:padding="10dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_address"
/>
</LinearLayout>
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
TaxiMain.java
package com.test.taxi;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TaxiMain extends ListActivity {
/** Called when the activity is first created.
* #return */
class Taxi {
private String taxiName;
private String taxiAddress;
public String getName() {
return taxiName;
}
public void setName(String name) {
taxiName = name;
}
public String getAddress() {
return taxiAddress;
}
public void setAddress(String address) {
taxiAddress = address;
}
public Taxi(String name, String address) {
taxiName = name;
taxiAddress = address;
}
}
public class TaxiAdapter extends ArrayAdapter<Taxi> {
private ArrayList<Taxi> items;
private TaxiViewHolder taxiHolder;
private class TaxiViewHolder {
TextView name;
TextView address;
}
public TaxiAdapter(Context context, int tvResId, ArrayList<Taxi> items) {
super(context, tvResId, items);
this.items = items;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.taxi_list_item, null);
taxiHolder = new TaxiViewHolder();
taxiHolder.name = (TextView)v.findViewById(R.id.taxi_name);
taxiHolder.address = (TextView)v.findViewById(R.id.taxi_address);
v.setTag(taxiHolder);
} else taxiHolder = (TaxiViewHolder)v.getTag();
Taxi taxi = items.get(pos);
if (taxi != null) {
taxiHolder.name.setText(taxi.getName());
taxiHolder.address.setText(taxi.getAddress());
}
return v;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] taxiNames = getResources().getStringArray(R.array.taxi_name_array);
String[] taxiAddresses = getResources().getStringArray(R.array.taxi_address_array);
ArrayList<Taxi> taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i]));
}
setListAdapter(new TaxiAdapter(this, R.layout.taxi_list_item, taxiList));
}
}