I want to create a ListView where each row would have two buttons. Button1 and Button2.
I have read few tutorials on how to create CustomAdapter or extend BaseAdapter, but none of them worked in my case, that is why I'm opening a new question here.
I have a static (not changing) String Array in my strings.xml:
<string-array name="locations_array">
<item>Item1</item>
<item>Item2</item>
</string-array>
I want to use this Array in my ListView ( I manage to create a normal ListView with onClick event, but now I want to add buttons to each row ) and add two buttons to each row where each will have their own onClick event.
I have followed steps from this answers here and few other tutorials on web, but I always get NullPointerException when trying to setText.
CustomAdapter.java:
public class CustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<>();
private Context ctx;
public CustomAdapter(ArrayList<String> list, Context ctx){
this.list = list;
this.ctx = ctx;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
Log.d("TAG", list.get(position));
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_listview,null);
}
Log.d("TAG", list.get(position));
TextView listItemText = (TextView) view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
Button localData = (Button) view.findViewById(R.id.button1);
Button onlineData = (Button) view.findViewById(R.id.button2);
localData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
onlineData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
}
And here I use the adapter in my Fragment:
locationsArray = getResources().getStringArray(R.array.locations_array);
ArrayList<String> data = new ArrayList<>(Arrays.asList(locationsArray));
CustomAdapter adapter = new CustomAdapter(data,getActivity());
listView.setAdapter(adapter);
But this doesn't work. All tutorials are focusing on something else then what I need. I just need simply to put two buttons on each row, with existing String Array. I dont want to add anything dynamically etc. Just use that String Array that I have already created.
EDIT (adding XML files I forgot!)
R.layout.layout_listview (the EditText is to filter the List):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/et_filter"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Search Location">
</EditText>
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
R.layout.layout_listview_buttons:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/button1"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Online Data"
android:textColor="#0099CC" />
<Button
android:id="#+id/button2"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="3dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Local Data"
android:textColor="#0099CC" />
</RelativeLayout>
LogCat Exception:
12-15 11:24:10.852 14626-14626/com.inodroid.myweatherapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.inodroid.myweatherapp, PID: 14626
java.lang.NullPointerException
at com.inodroid.myweatherapp.Data.CustomAdapter.getView(CustomAdapter.java:59)
Line in code:
listItemText.setText(list.get(position));
Hope someone can help me out here.
Cheers
Please try the following :
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/lvItems"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
MainActivity.java :
public class MainActivity extends Activity {
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItems = (ListView) findViewById(R.id.lvItems);
String[] locationsArray = getResources().getStringArray(
R.array.locations_array);
CustomAdapter adapter = new CustomAdapter(this, locationsArray);
lvItems.setAdapter(adapter);
lvItems.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ViewHolder holder = (ViewHolder) view.getTag();
String item = holder.getItem();
// Do what ever with your Item.
// If You need the position, you can take it from above
// position.
}
});
}
}
list_item.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="vertical"
android:padding="5dp" >
<Button
android:id="#+id/btnLocalData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="local Data" />
<TextView
android:id="#+id/tvItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/btnLocalData"
android:layout_alignTop="#+id/btnOnlineData"
android:layout_toLeftOf="#+id/btnOnlineData"
android:layout_toRightOf="#+id/btnLocalData"
android:gravity="center"
android:text="Item"
android:textSize="16dp"
android:textStyle="bold" />
<Button
android:id="#+id/btnOnlineData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Online Data" />
</RelativeLayout>
CustomAdapter.java :
public class CustomAdapter extends ArrayAdapter<String> {
private LayoutInflater lf;
public CustomAdapter(Context context, String[] objects) {
super(context, 0, objects);
lf = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = lf.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.btnLocalData = (Button) convertView
.findViewById(R.id.btnLocalData);
holder.btnOnlineData = (Button) convertView
.findViewById(R.id.btnOnlineData);
holder.tvItem = (TextView) convertView.findViewById(R.id.tvItem);
holder.initListeners();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData(getItem(position));
return convertView;
}
public static class ViewHolder {
TextView tvItem;
Button btnOnlineData;
Button btnLocalData;
String mItem;
public String getItem(){
return mItem;
}
public void setData(String item) {
mItem = item;
tvItem.setText(item);
}
public void initListeners() {
btnLocalData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),
"Local Data Clicked : " + mItem, Toast.LENGTH_LONG)
.show();
}
});
btnOnlineData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),
"Online Data Clicked : " + mItem, Toast.LENGTH_LONG)
.show();
}
});
}
}
}
Please use the ViewHolder pattern. You will need these:
item_listrow.xml:
<LinearLayout
android:layout_height = "match_parent";
andorid:layout_width = "match_parent";
andorid:orientation = "horizontal";
>
<Button
android:id = "#+id/button1"
android:layout_height = "match_parent";
andorid:layout_width = "0dp";
andorid:layout_weight = 1;
/>
<Button
android:id = "#+id/button2"
android:layout_height = "match_parent";
andorid:layout_width = "0dp";
andorid:layout_weight = 1;
/>
</LinaerLayout>
And your Adapter getView() method should look like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_listrow,null);
Holder h = new Holder();
h.button1 = (Button) view.findViewById(R.id.button1);
h.button2 = (Button) view.findViewById(R.id.button2);
view.setTag(h);
}
Holder holder = (Holder) view.getTag();
holder.button1.setText(list.get(0));
holder.button2.setText(list.get(1));
listItemText.setText(list.get(position));
holder.button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
The Holder class used above: (just nest it inside the Adapter class)
public static class Holder {
Button button1;
Button button2;
}
Here is the code for hiding the buttons based on a given method isDeveloperMode():
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_listrow,null);
Holder h = new Holder();
h.button1 = (Button) view.findViewById(R.id.button1);
h.button2 = (Button) view.findViewById(R.id.button2);
view.setTag(h);
}
Holder holder = (Holder) view.getTag();
if(isDeveloperMode()){
holder.button1.setVisibility(View.VISIBLE);
holder.button2.setVisibility(View.VISIBLE);
holder.button1.setText(list.get(0));
holder.button2.setText(list.get(1));
listItemText.setText(list.get(position));
holder.button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
} else {
holder.button1.setVisibility(View.GONE);
holder.button2.setVisibility(View.GONE);
}
return view;
}
Change your code to the following in adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView= inflater.inflate(R.layout.layout_listview,null);
}
Log.d("TAG", list.get(position));
TextView listItemText = (TextView) convertView.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
Button localData = (Button) convertView.findViewById(R.id.button1);
Button onlineData = (Button) convertView.findViewById(R.id.button2);
localData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
onlineData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
Try instead of
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_listview,null);
}
Log.d("TAG", list.get(position));
TextView listItemText = (TextView) view.findViewById(R.id.list_item_string);
use
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Log.d("TAG", list.get(position));
TextView listItemText = (TextView) view.findViewById(R.id.list_item_string);
Related
I'm trying to get ArrayList with different variables that i'm getting from a database to display in a customized listview
this is the main 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View the balance sheet"
android:textSize="29sp"
android:id="#+id/view"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="36dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView">
</ListView>
</RelativeLayout>
this is the customized layout
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/description_names"
android:text="description"
android:layout_marginTop="25sp"
android:layout_marginLeft="15sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/values_names"
android:text="value"
android:layout_marginTop="25sp"
android:layout_marginLeft="105sp"/>
</RelativeLayout>
this is the adapter, i wanted both the ArrayLists from the main activity but it's not working
class CustomAdapter extends ArrayAdapter<String> {
CustomAdapter(#NonNull Context context, ArrayList<String> mDetails,ArrayList<String> mValues) {
super(context,R.layout.custom_layout ,mDetails);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater=LayoutInflater.from(getContext());
View customView=inflater.inflate(R.layout.custom_layout,parent,false);
String details=getItem(position);
String values=getItem(position);
TextView description_names=(TextView)customView.findViewById(R.id.description_names);
TextView values_names=(TextView)customView.findViewById(R.id.values_names);
description_names.setText(details);
return customView;
}
}
main activity
ListView listvIew=(ListView)findViewById(R.id.listView);
final ArrayAdapter<String>array=new CustomAdapter(this,mDetails,mValues);
listvIew.setAdapter(array);
private ArrayList<String>mDetails=new ArrayList<>();
private ArrayList<String>mValues=new ArrayList<>();
V3Ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value=dataSnapshot.child("records").child("values").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is"+value);
mDetails.add(value);
mValues.add(value);
array.notifyDataSetChanged();
}
i'm getting values from the database then putting them in ArrayLists then i'm trying to display them in a customized listview but it's not working when i try to use the second Arraylist
adapter calls from your main activity should be like,
CusatomeAdapter adapter;
adapter = new CusatomeAdapter(mActivity,mList1 ,mList2);
mListview.setAdapter(adapter);
here is your adapter calss
public class CusatomeAdapter extends BaseAdapter {
public ArrayList<String> mList1;
public ArrayList<String> mList2;
Activity activity;
public CusatomeAdapter(Activity activity,ArrayList<String> mList1 , ArrayList<String> mList2){
super();
this.activity = activity;
this.mList1 = mList1;
this.mList2 = mList2;
}
#Override
public int getCount() {
return mList1.size(); //give the size of list here
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_detail, null);
holder = new ViewHolder();
holder.tv_detail = (TextView) convertView.findViewById(R.id.tv_detail);
//same way define another text view and set their value ..
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv_detail.setText(mList1.get(position).toString());
return convertView;
}
private class ViewHolder {
TextView tv_detail;
}
}
I'm removing images from a gridview when a button is pressed.
The images does remove fine and the gridview also updates with the call "adapter.notifyDataSetChanged();".
When an imageview is removed another image next to this position should take its position. This happens, but the image here won't reload so there's just a blank space? How can I get this imageview to reload its image?
The problem:
Here is my gridadapter:
public class FavoriteMovieGridAdapter extends BaseAdapter {
Context context;
ArrayList<DataFavorites> List;
FavoritesMovie fragment;
private static LayoutInflater inflater = null;
FavoriteMovieGridAdapter adapter = this;
public FavoriteMovieGridAdapter(Context context, ArrayList<DataFavorites> List, FavoritesMovie fragment) {
this.context = context;
this.List = List;
this.fragment = fragment;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return List.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row
final ViewHolder holder;
/*
* If convertView is not null, reuse it directly, no inflation
* Only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = inflater.inflate(R.layout.favorite_grid_item, null);
holder = new ViewHolder();
holder.poster = (ImageView) convertView.findViewById(R.id.upcoming_image);
holder.editbutton = (ImageView) convertView.findViewById(R.id.delete_item);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
}
else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
final View finalConvertView = convertView;
final DataFavorites e;
new DataFavorites();
e = List.get(position);
String url = String.valueOf(e.getUrl());
// load image url into poster
// Seems as if this doesn't run for the imageview next to this when this view is removed?
Picasso.with(context).load(url).fit().placeholder(R.drawable.movie_back).into(holder.poster);
// Create onclick and show edit button
convertView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// show edit button
holder.editbutton.setVisibility(View.VISIBLE);
YoYo.with(Techniques.FadeIn).duration(700).playOn(finalConvertView.findViewById(R.id.delete_item));
// onclick edit button remove item and update gridview
holder.editbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YoYo.with(Techniques.ZoomOut).duration(700).playOn(finalConvertView.findViewById(R.id.favorite_relative));
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
adapter.List.remove(e);
adapter.notifyDataSetChanged();
// Delete specific movie from data base
DatabaseHandlerMovie db = new DatabaseHandlerMovie(context);
// Reading all movies
db.deleteMovie(e);
}
}, 1000);
}
});
return false;
}
});
return convertView;
}
static class ViewHolder {
ImageView poster;
ImageView editbutton;
}
}
My grid item layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/favorite_relative"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal">
<ImageView android:layout_width="123.3dp"
android:layout_height="185.3dp"
android:id="#+id/upcoming_image"
android:scaleType="fitXY" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/delete_item"
android:src="#drawable/ic_remove_circle_outline_white_24dp"
android:tint="#color/colorPrimaryDark"
android:clickable="true"
android:visibility="gone"
android:layout_alignRight="#+id/upcoming_image"
android:layout_alignEnd="#+id/upcoming_image"/>
</RelativeLayout>
My grid layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".Favorites"
android:background="#FFFFFF"
android:focusableInTouchMode="true">
<GridView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/movies_gridlayout"
android:paddingRight="-1dp"
android:paddingEnd="-1dp"
android:numColumns="3"
android:background="#ffffff"
android:visibility="invisible"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/favorite_none"
android:text="No favorite movies found"
android:textSize="15sp"
android:visibility="gone"
android:textColor="#color/SecondaryText"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
>
</ProgressBar>
</FrameLayout>
Turns out a 3rd-party lib was causing this:
YoYo.with(Techniques.ZoomOut).duration(700).playOn(finalConvertView.findViewById(R.id.favorite_relative));
you will have adapter and mainactivity for gridview
So u will have to implement public interface in both of them to communicate
following code may help you :)
In Adapter class add following code
private OnItemClickListner onItemClickListner;
public MyAdapter(Context c, List<PDFDoc> pdfDocs,OnItemClickListner onItemClickListner) {
this.context = c;
this.pdfDocs = pdfDocs;
this.onItemClickListner=onItemClickListner;
}
public interface OnItemClickListner {
void removefromadapter(int position);
}
ImageButton imageButton = view.findViewById(R.id.cancelid);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// write your stuff here
onItemClickListner.removefromadapter(position);
}
});
In MainActivity of gridview add following code
implements OnItemClickListner required**
public class addclient_fragment extends Fragment implements MyAdapter.OnItemClickListner {
you will required to add this method in mainactivity
#Override
public void removefromadapter(int position) {
// write your stuff here
}
I am developing an android application with a custom list view ( with a single image and two text views)
The class mainactivity has ....
public class MainActivity extends ActionBarActivity {
String[] memetitles;
String[] memedesc;
ListView list;
int[] images = {R.drawable.angry_icon,R.drawable.happy_icon,R.drawable.kid_icon,R.drawable.scare_icon,R.drawable.warn_icon};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
memetitles = res.getStringArray(R.array.titles);
memedesc = res.getStringArray(R.array.notneed);
list = (ListView) findViewById(R.id.listView1);
Itarray adapter = new Itarray(this,memetitles,memedesc,images);
list.setAdapter(adapter);
setTitle("Tamil Memer");
}
The class for combining two layouts into a single list view has
class Itarray extends ArrayAdapter<String>{
Context context;
int[] image;
String[] tit1;
String[] tit2;
Itarray(Context c , String[] titles ,String[] notneed, int imgs[])
{
super(c , R.layout.single_row,titles);
this.context = c;
this.image = imgs;
this.tit1 = titles;
this.tit2 = notneed;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if(row == null)
{
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inf.inflate(R.layout.single_row , parent , false);
}
ImageView myImage = (ImageView) row.findViewById(R.id.imageView1);
TextView tit = (TextView) row.findViewById(R.id.textView1);
TextView des = (TextView) row.findViewById(R.id.textView2);
myImage.setImageResource(image[position]);
tit.setText(tit1[position]);
des.setText(tit2[position]);
return row;
}
}
The two layout files :
(the one with the image and the textviews)
<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:gravity="top"
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.itassistors.tmg.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/imageView1"
android:layout_toRightOf="#+id/imageView1"
android:text="#string/simple"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/textView1"
android:layout_alignStart="#+id/textView1"
android:text="#string/simple"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/textView1"
android:src="#drawable/happy_icon" />
(the one with the listview)
<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:gravity="center_vertical"
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.itassistors.tmg.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
I want to know how and where to place the onClickListener() for this custom list view
Thanks in advance
You have two options:
1) Set the click listener in your activity:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// Do your stuff here
}
});
2) Set the click listener in your adapter:
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if(row == null)
{
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inf.inflate(R.layout.single_row , parent , false);
}
ImageView myImage = (ImageView) row.findViewById(R.id.imageView1);
TextView tit = (TextView) row.findViewById(R.id.textView1);
TextView des = (TextView) row.findViewById(R.id.textView2);
myImage.setImageResource(image[position]);
tit.setText(tit1[position]);
des.setText(tit2[position]);
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do your stuff here
}
});
return row;
}
If you are doing it in adapter you will to follow this code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolderItem holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.your_list_item, null);
View row = convertView;
holder = new ViewHolderItem();
convertView.setTag(holder);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v(LOG_TAG, "ROW PRESSED");
context.startActivity(new Intent(context, YourAction.class));
}
});
} else {
holder = (ViewHolderItem) convertView.getTag();
}
return convertView;
}
I want to display ArrayList of object in AlertDialog but my list view dont show. Here is my code.
public class PrzystanekDialog extends DialogFragment {
private ListView trasaPrzejazdu;
private ArrayList<Linia> trasaPrzejazduList;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
LayoutInflater inflater = getActivity().getLayoutInflater();
final View rootView = inflater.inflate(R.layout.dialog_layout, null);
//ustawienie lisview z wygenerowaną linia
trasaPrzejazduList = getArguments().getParcelableArrayList("linia");
trasaPrzejazdu = (ListView) rootView.findViewById(R.id.trasaListView);
final ArrayAdapter<Linia> adapter = new ArrayAdapter<Linia>(getActivity(),R.layout.listbox_dialog_element, trasaPrzejazduList);
trasaPrzejazdu.setAdapter(adapter);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final ViewPager mViewPager;
mViewPager = (ViewPager) getActivity().findViewById(R.id.pager);
builder.setView(inflater.inflate(R.layout.dialog_layout, null));
//getActivity().setContentView(inflater.inflate(R.layout.dialog_layout, null));
builder.setMessage(R.string.choose)
.setPositiveButton(R.string.start_trip, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mViewPager.setCurrentItem(1);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity().getApplicationContext(), "Anulowano podróż.", Toast.LENGTH_LONG).show();
}
});
return builder.create();
}
}
Here is my ArrayAdapter
public class DialogListAdapter extends BaseAdapter {
private List<Linia> listData;
private LayoutInflater layoutInflater;
public DialogListAdapter(Context context, List<Linia> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Linia getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listbox_dialog_element, null);
holder = new ViewHolder();
holder.start = (TextView) convertView.findViewById(R.id.przystanekStartowy);
holder.end = (TextView) convertView.findViewById(R.id.przystanekDocelowy);
holder.vehicleImage = (ImageView) convertView.findViewById(R.id.line_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//listData.get(position).getHeadline()
if(listData.get(position).getTypLini().toString() == "bus")
holder.vehicleImage.setImageResource(R.drawable.autobus_ico);
else
holder.vehicleImage.setImageResource(R.drawable.tram_ico);
holder.start.setText(listData.get(position).getStopPrzystanki().get(0).getNazwa_przystanku());
holder.end.setText(listData.get(position).getStopPrzystanki().get(listData.get(position).getStopPrzystanki().size()-1).getNazwa_przystanku());
return convertView;
}
static class ViewHolder {
ImageView vehicleImage;
TextView start;
TextView end;
}
}
And here is my xml file
<?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/trasaListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
I have no compile errors. Thank you very much for help.
EDIT:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/line_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/autobus_ico"
android:layout_marginLeft="5dip"/>
<TextView
android:id="#+id/przystanekStartowy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textStyle="bold"
android:typeface="sans"
android:layout_marginLeft="60dip"/>
<TextView
android:id="#+id/przystanekDocelowy"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:text=""
android:textColor="#343434"
android:textSize="12sp"
android:layout_marginLeft="60dip"/>
</LinearLayout>
how to select row item using Tick mark like iphone in android?iam using imageview in list_row.xml.when i click the list row item then i show image in row imageview.
if(getItem(position)!=null){
img.setvisibilty(View.Visible);}
else{System.out.println("imagenull");}
iam using this but image display in last row only.please help me how to select item using tickmark image.
public class DistanceArrayAdapter extends ArrayAdapter<Constant>{
public static String category,state,miles;
public ImageView img;
private Context context;
private int current = -1;
ArrayList<Constant> dataObject;
public DistanceArrayAdapter(Context context, int textViewResourceId,
ArrayList<Constant> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.category_row, parent, false);
}
//TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
//textView.setText(""+getItem(position).id);
textView1.setText(""+getItem(position).caption);
img=(ImageView)rowView.findViewById(R.id.img);
img.setVisibility(View.GONE);
if(position%2==1)
{
rowView.setBackgroundResource(R.color.even_list);
}
else
{
rowView.setBackgroundResource(R.color.odd_list);
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(img.getVisibility()==View.GONE)
{
img.setVisibility(View.VISIBLE);
System.out.println("1");
}
if(img.getVisibility()==View.VISIBLE){
img.setVisibility(View.GONE);
System.out.println("12");
}
miles=getItem(position).caption;
System.out.println("miles"+miles);
}
});
return rowView;
}
}
Drawing from https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String[] GENRES = new String[] {"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"};
private CheckBoxAdapter mCheckBoxAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for (int i = 0; i < GENRES.length; i++) {
if (mCheckBoxAdapter.mCheckStates.get(i) == true) {
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener {
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
String[] gen;
private SparseBooleanArray mCheckStates;
private SparseBooleanArray mCheckStates;
CheckBoxAdapter(MainActivity context, String[] genres) {
super(context, 0, genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen = genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
And the XML file for the checkboxes:
<?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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
When you click the button a toast message with list of item choosen is displayed. You can modify the above according to your requirements.
Set selection mode on your ListView
//if using ListActivity or ListFragment
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//or
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//myListView is reference to your ListView
1.Make visibility gone to you tick mark image
2.Implement view.setOnClickListener in arrayadapter.
3.In that check image.getVisibility()==View.GONE then make image.setVisibity(View.Visible)
4.if image.getVisiblity()==View.VISIBLE then make your image.setVisibity(View.GONE)
Try this.