onclick Listener for custom listview - java

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;
}

Related

duplicating all activity instead of [check boxes and text only] (To do list android app)

I'm trying to make to-do list app. the design here "https://i.ibb.co/cXnQ9dP/Capture.png"
I got box and text code from "https://www.vogella.com/tutorials/AndroidListView/article.html" proj (15.1. Interaction between the model and Listview) but I put the XML code into my existing XML activity [not in a new activity] and changed activity name in super(context, R.layout.rowbuttonlayout, list); and view = inflator.inflate(R.layout.rowbuttonlayout, null); to my main activity name
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mando.todolist.new_list">
.............background and buttons code here............
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignStart="#id/plus"
android:orientation="horizontal"
android:paddingTop="205dp"
android:id="#+id/repeat_layout"
>
<CheckBox
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4px"
android:layout_marginRight="10px" >
</CheckBox>
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="50px"
android:layout_alignRight="#id/check"
>
</TextView>
</LinearLayout>
public InteractiveArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.activity_new_list, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.activity_new_list.,null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
public class new_list extends ListActivity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// create an array of Strings, that will be put to our ListActivity
ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
getModel());
setListAdapter(adapter);
}
private List<Model> getModel() {
List<Model> list = new ArrayList<Model>();
list.add(get("Linux"));
list.add(get("Windows7"));
list.add(get("Suse"));
list.add(get("Eclipse"));
list.add(get("Ubuntu"));
list.add(get("Solaris"));
list.add(get("Android"));
list.add(get("iPhone"));
// Initially select one of the items
list.get(1).setSelected(true);
return list;
}
private Model get(String s) {
return new Model(s);
}
}
The output is All activity has been duplicated [including background and buttons] instead duplicating checkbox with text only in the same activity
Move your background and buttons to the xml file where you put your ListView
it should look like this, because the item xml you are using where your CheckBox exists is the one used for the ListView, if you but the button it will duplicated too
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- background and buttons code here -->
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:headerDividersEnabled="true"/>
</LinearLayout>

onListItemClick is not work for added two clickable items in the list row

I created a ListFragment by using a custom adapter. OnListItemClick is not work after I add a button in the list row. If I click on the list row it should be intent to other class, but now when I click on the list row, it did not have any action. No error and no action. So I think it might because there has two clickable items in the list row, so the onListItemClick is not work. But I do not know how can I solve this problem.
Fragment1.java
public class Fragment1 extends ListFragment implements AdapterInterface{
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_show_queue, container, false);
// initialize the items list
mItems = new ArrayList<ListViewItem>();
// initialize and set the list adapter
adapter = new ListViewAdapter2(getActivity(), mItems, this);
setListAdapter(adapter);
return rootView;
}
#Override
public void buttonPressed(int position) {
System.out.println("Fragment1: " + position);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(getActivity(), QueueDetail.class);
i.putExtra("qid", qid.get(position).toString());
startActivity (i);
}
}
ListViewAdapter2.java
public class ListViewAdapter2 extends ArrayAdapter<ListViewItem> {
AdapterInterface buttonListener;
private int position;
public ListViewAdapter2(Context context, List<ListViewItem> items, AdapterInterface buttonListener) {
super(context, R.layout.listview_layout2, items);
this.buttonListener = buttonListener;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
this.position = position;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_layout2, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.img = (ImageView) convertView.findViewById(R.id.img);
viewHolder.txt = (TextView) convertView.findViewById(R.id.txt);
viewHolder.smallTxt = (TextView) convertView.findViewById(R.id.smallTxt);
viewHolder.datetime = (TextView) convertView.findViewById(R.id.datetime);
viewHolder.viewBtn = (Button) convertView.findViewById(R.id.viewBtn);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.viewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("ListViewAdapter: " + position);
buttonListener.buttonPressed(position);
}
});
...
return convertView;
}
private int getViewBtnPosition(){
return position;
}
}
fragment_show_queue.xml
<FrameLayout 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" >
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</FrameLayout>
listview_layout2.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" >
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp"
android:layout_alignParentLeft="true"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:layout_toRightOf="#+id/img"
android:layout_toLeftOf="#+id/datetime"
android:layout_toStartOf="#+id/datetime">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp" />
<TextView
android:id="#+id/smallTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp" />
</LinearLayout>
<TextView
android:id="#+id/datetime"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text=""
android:textSize="10dp" />
<Button
android:layout_width="35dp"
android:layout_height="20dp"
android:id="#+id/viewBtn"
android:text="JOIN"
android:textSize="10dp"
android:background="#b5e61d"
android:layout_marginRight="10dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
add android:focusable="false" and android:focusableInTouchMode="false" to your Button in the row's layout file.

ListView with Buttons and static String Array

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);

Cant display listview in AlertDialog android

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>

ImageView in a List Null Pointer Exception

I am trying to set up an list view with only some images, ie no text. Here are my files:
//the Main File:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listview1 = (ListView)findViewById(R.id.listView1);
final Integer[] mThumbIds = {
R.drawable.blue, R.drawable.blue2,
R.drawable.blue3, R.drawable.blue4,
R.drawable.blue5, R.drawable.blue6
};
listview1.setAdapter(new ImageAdapter(this,mThumbIds));
listview1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Upon Clicking
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class ImageAdapter extends ArrayAdapter<Integer> {
private Context mContext;
Integer [] resources;
public ImageAdapter (Context c, Integer[] resources) {
super(c, R.layout.activity_main, resources);
//System.out.println("Set up of Image Adapter");
mContext = c;
this.resources=resources;
for(Integer resource:resources){
System.out.println(resource);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.layout.image_view);
imageView.setImageResource(resources[position]);
return rowView;
}
}
}
The XML is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/export_folder_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Formation Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#+id/listView1"
android:layout_below="#+id/color_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:background="#ff000000" >
</ListView>
</RelativeLayout>
And finally, the one defining the ImageView:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:minHeight="64dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="9dp"
android:layout_alignParentTop="true"/>
</RelativeLayout>
Unfortunately, I get NullPointerExceptions at the point where I set the image Resource on the image view. The image resources exist- I've made sure.
I am not sure what I am doing wrong, and I am new to Android. Thank you.
Looks like you are inflating a wrong xml in your getView(),
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
Here R.layout.activity_main should be replaced by the xml file which contains the ImageView.
And from your code, I think the name of the xml file containing the ImageView is, R.layout.image_view
So, your final code should be something like this,
View rowView = inflater.inflate(R.layout.image_view, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
imageView.setImageResource(resources[position]);
Try the following code link :-
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
// get input stream
InputStream ims = null;
try {
ims = context.getAssets().open(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imageView.setImageDrawable(d);
return rowView;
}
}
Use R.id.image_view instead of using R.layout.image_view
Change Line
ImageView imageView = (ImageView) rowView.findViewById(R.layout.image_view);
To Below Line
ImageView imageView = (ImageView) rowView.findViewById(R.id.image_view);

Categories