How can I add another TextView in my Listview? - android

I've made a ListView by following a tutorial on the web. It works great and exactly like I want it to. Now I'm trying to create another ListView in another activity but this time I need two TextViews, not one.
Here's my Adapter:
public class CustomListTwo extends ArrayAdapter<String> {
private final Activity context;
private final String[] web;
// private final String[] hex; <-- was trying to add this one but it gave me an error :(
private final Integer[] imageId;
public CustomListTwo(Activity context,
String[] web, Integer[] imageId) {
super(context, R.layout.color_item_layout, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.color_item_layout, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item_value);
ImageView imageView = (ImageView) rowView.findViewById(R.id.item_color);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
I'm trying to add "String[] hex;" but it gives me an error saying that the "variable may not be initialized". My idea was to duplicate everything that was written about the web variable and replace it with the hex variable and change the values.
Here's my activity:
public class ColorRed extends Activity {
ListView list;
String[] web;
Integer[] imageId = {
R.color.red_50,
R.color.red_100,
R.color.red_200,
R.color.red_300,
R.color.red_400,
R.color.red_500,
R.color.red_600,
R.color.red_700,
R.color.red_800,
R.color.red_900,
R.color.red_A100,
R.color.red_A200,
R.color.red_A400,
R.color.red_A700,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_red);
web = getResources().getStringArray(R.array.values);
CustomListTwo adapter = new
CustomListTwo(ColorRed.this, web, imageId);
list=(ListView)findViewById(R.id.list_red);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position){
case 0: r50(view);
break;
case 1: r50(view);
break;
default:
r50(view);
break;
}
}
});
}
Here's my ListView item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="72dp"
android:background="?android:attr/selectableItemBackground">
<ImageView
android:background="?android:attr/selectableItemBackground"
android:layout_width="match_parent"
android:layout_height="72dp"
android:id="#+id/item_color"
android:src="#drawable/myrect" />
<TextView
android:id="#+id/item_hex"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:textColor="#de000000"
android:textAllCaps="true"
android:textSize="18sp"
android:text="List Item"
android:paddingRight="16dp"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="72dp"
android:text="New Text"
android:textColor="#de000000"
android:textSize="18sp"
android:id="#+id/item_value"
android:layout_centerVertical="true"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:paddingLeft="16dp"
android:gravity="center_vertical"/>
</RelativeLayout>
So basicly, my question is how do I add a new TextView and load it with an array from strings.xml just like I do with the current TextView? I want the TextView "hex" to be populated with text from an array which I declare in strings.xml.
EDIT: My updated adapter:
public class CustomListTwo extends ArrayAdapter<String> {
private final Activity context;
private final String[] web;
private final String[] hex;
private final Integer[] imageId;
public CustomListTwo(Activity context, String[] web, String[] hex, Integer[] imageId) {
super(context, R.layout.color_item_layout, web, hex);
this.context = context;
this.web = web;
this.hex = hex;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.color_item_layout, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item_value);
ImageView imageView = (ImageView) rowView.findViewById(R.id.item_color);
TextView txtHex = (TextView) rowView.findViewById(R.id.item_hex);
txtHex.setText(hex[position]);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
Updated activity:
public class ColorRed extends Activity {
ListView list;
String[] web;
String[] hex;
Integer[] imageId = {
R.color.red_50,
R.color.red_100,
R.color.red_200,
R.color.red_300,
R.color.red_400,
R.color.red_500,
R.color.red_600,
R.color.red_700,
R.color.red_800,
R.color.red_900,
R.color.red_A100,
R.color.red_A200,
R.color.red_A400,
R.color.red_A700,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_red);
web = getResources().getStringArray(R.array.values);
hex = getResources().getStringArray(R.array.hex_red);
CustomListTwo adapter = new
CustomListTwo(ColorRed.this, web, hex, imageId);
list=(ListView)findViewById(R.id.list_red);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position){
case 0: r50(view);
break;
case 1: r50(view);
break;
default:
r50(view);
break;
}
}
});
}
Now I get an error in this code:
super(context, R.layout.color_item_layout, web, hex);
"Cannot resolve method"

You can't declare a final variable and not initialize it anywhere.
Pass the hex array in your adapter constructor, assign it to the hex[] in the adapter and use it in getView(..).

Related

Android Customer Array Adapter does not display data

Hi StackOverflow community! I need your help understanding the following behavior:
I tried to implement a ListView for which each view follows the below layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLWLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100">
<TextView
android:id="#+id/noteText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="66.6" />
<LinearLayout
android:id="#+id/linearVLWLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="33.3"
android:orientation="vertical">
<TextView
android:id="#+id/textcolor"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/reminder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textcolor" />
<TextView
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/reminder" />
<TextView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/location" />
</LinearLayout>
Now, when I'm assigning elements to the list, I'm using the below adapter:
public class MyAdapter extends ArrayAdapter<Note> {
private Context mContext;
private int mResource;
public MyAdapter(#NonNull Context context, int resource, ArrayList<Note> objects) {
super(context, resource);
mContext =context;
mResource=resource;
}
public View getView(int position, View convertView, ViewGroup parent){
String text = getItem(position).getText();
String color = getItem(position).getColor();
String location = getItem(position).getLocation();
String reminder = getItem(position).getReminder();
String image = getItem(position).getImage();
Note note = new Note(text,color,location,reminder,image);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView=inflater.inflate(mResource,parent,false);
TextView nttxt = (TextView) convertView.findViewById(R.id.noteText);
TextView ntcolor = (TextView) convertView.findViewById(R.id.textcolor);
TextView ntrem = (TextView) convertView.findViewById(R.id.reminder);
TextView ntlocat = (TextView) convertView.findViewById(R.id.location);
TextView ntimg = (TextView) convertView.findViewById(R.id.image);
nttxt.setText(text);
ntcolor.setText(color);
ntrem.setText(reminder);
ntlocat.setText(location);
ntimg.setText(image);
Log.i("Convert",convertView.toString());
Log.i("Text",nttxt.toString());
return convertView;
}
}
The final result should be a list of notes together with user preferences and location/reminder.
Please see below the list assignation made on OnCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_explorer);
FloatingActionButton myFab = this.findViewById(R.id.fabAddNote);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intentNoteEditor = new Intent(getApplicationContext(), NoteEditor.class);
startActivity(intentNoteEditor);
}
});
ListView notesList = (ListView) findViewById(R.id.listviewNotes);
Note note1 = new Note("Note1","Col1","Reminder1","Location1","Image1");
Note note2 = new Note("Note2","Col2","Reminder2","Location2","Image2");
Note note3 = new Note("Note3","Col3","Reminder3","Location3","Image3");
Note note4 = new Note("Note4","Col4","Reminder4","Location4","Image4");
ArrayList<Note> notesArray = new ArrayList<>();
notesArray.add(note1);
notesArray.add(note2);
notesArray.add(note3);
notesArray.add(note4);
Log.i("Notes",note1.getText().toString());
MyAdapter adapter = new MyAdapter(this,R.layout.list_item,notesArray);
notesList.setAdapter(adapter);
Log.i("Adapter",adapter.getContext().toString());
}
What am I doing wrong?
Any suggestions will be highly appreciated.
Thank you in advance!
You didn't store the list you feed your adapter to a local field.
Here you are passing ArrayList<Note> objects through the adapter constructor, but didn't save it locally to some store.
So, First modify your Adapter to have a filed of ArrayList<Note>
and initialize it in the constructor.
Second, override the adapter getCount() to return the size of your
list.
Third: modify your getView(), to get the Note object of the current
position in the list
public class MyAdapter extends ArrayAdapter<Note> {
private Context mContext;
private int mResource;
private ArrayList<Note> mNotes;
public MyAdapter(#NonNull Context context, int resource, ArrayList<Note> objects) {
super(context, resource);
mContext = context;
mResource = resource;
mNotes = objects;
}
#Override
public int getCount() {
return mNotes.size();
}
public View getView(int position, View convertView, ViewGroup parent){
String text = mNotes.get(position).getText();
String color = mNotes.get(position).getColor();
String location = mNotes.get(position).getLocation();
String reminder = mNotes.get(position).getReminder();
String image = mNotes.get(position).getImage();
// .... continue the rest of code.
Hope this address your issue.

How to add tabs to listview?

I need to add two tabs in my listing and I do not know how to do it, I wanted to add one in the first row and another after the fourth item that separates: trend and genre, I saw something about adding a new xml layout but I need help because I can not, this would be just a text between the items..
My main activity:
public class inicio extends AppCompatActivity {
private ListView listaitens;
private String[] itens = {
"Home", "playlist", "trend", "Conta", "Live", "rock", "Hip Hop", "Pop",
"House", "Gospel Music", "Metal", "Alt Rock", "Sport", "Game"
};
Integer[] imgid={
R.drawable.home,
R.drawable.playlist,
R.drawable.trend,
R.drawable.conta,
R.drawable.live,
R.drawable.rock,
R.drawable.hiphop,
R.drawable.pop,
R.drawable.house,
R.drawable.gospel,
R.drawable.metal,
R.drawable.alternative_rock,
R.drawable.sport,
R.drawable.game,
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio);
listaitens = (ListView) findViewById(R.id.listview);
CustomListAdapter adapter=new CustomListAdapter(this, itens, imgid);
listaitens=(ListView)findViewById(R.id.listview);
listaitens.setAdapter(adapter);
listaitens.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (position == 0) {
Intent intent = new Intent(inicio.this, INSMainActivity.class);
intent.putExtra("link", "https://m.youtube.com/");
startActivity(intent);
My adapter:
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] itens;
private final Integer[] imgid;
public CustomListAdapter(inicio context, String[] itens, Integer[] imgid) {
super(context, R.layout.mylist, itens);
this.context=context;
this.itens=itens;
this.imgid=imgid;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.mylist, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itens[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Access "+itens[position]);
return rowView;
}
xml listview
<?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="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#000000" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
If anyone can help me, thank you very much.
You have to create separate xml files:
One to create your row layout
Another for your tab
And then make changes to your adapter as below
public class CustomListAdapter extends ArrayAdapter<String> {
private static final int TYPE_ITEM = 0;
private static final int TYPE_TAB = 1;
private final Activity context;
private final String[] itens;
private final Integer[] imgid;
public CustomListAdapter(inicio context, String[] itens, Integer[] imgid) {
super(context, R.layout.mylist, itens);
this.context=context;
this.itens=itens;
this.imgid=imgid;
}
public View getView(int position,View view,ViewGroup parent) {
int type = getItemViewType(position);
LayoutInflater inflater=context.getLayoutInflater();
if (view == null) {
// Inflate the layout according to the view type
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (type == TYPE_ITEM) {
view = inflater.inflate(R.layout.your_item_layout, parent, false);
} else {
view = inflater.inflate(R.layout.your_tab_layout, parent, false);
}
TextView txtTitle = (TextView) view.findViewById(R.id.item);
ImageView imageView = (ImageView) view.findViewById(R.id.icon);
TextView extratxt = (TextView) view.findViewById(R.id.textView1);
/**
* Your tab layout textView
*/
if (type == TYPE_TAB) {
TextView tab = (TextView) view.findViewById(R.id.tab);
tab.setText("Your text");
}
txtTitle.setText(itens[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Access "+itens[position]);
return view;
}
/**
* Override this function, returns the number of types of views in your list.
* In your case it is 2
*/
#Override
public int getViewTypeCount() {
return 2;
}
/**
* Override this function, returns the item to be return at position
*/
#Override
public int getItemViewType(int position) {
//return type = tab according to your position
if (position == 0 || position == 4) {
return TYPE_TAB;
} else {
return TYPE_ITEM;
}
}

Implement click only on image not on text in custom listview

I have a custom Listview where it contains image & text and implemented the OnItemClickListener for list which should work only for image not for text. OnItemClick is working fine for image but there is a Fatal Exception when i click on text. Additionally image will be visible in list if it exists else it will be hide.
Tried with android:focusable="false", android:clickable="false" but still i am getting the below exception
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable.getBitmap()' on a null object reference
OnItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ImageView imageView1 = (ImageView) view.findViewById(R.id.imageList);
final GlideBitmapDrawable bitmapDrawable = (GlideBitmapDrawable) imageView1.getDrawable();
final Bitmap yourBitmap = bitmapDrawable.getBitmap();
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourBitmap);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
How can i implement click only on image?
In your custom layout xml, set
android:descendantFocusability="blocksDescendants"
to your root layout.
Edit
Check my Custom ListView.
listitem.xml
<?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:gravity="center"
android:descendantFocusability="blocksDescendants"
android:layout_height="60dp">
<ImageView
android:id="#+id/m_imageview"
android:layout_width="0dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"
android:layout_height="50dp" />
<TextView
android:id="#+id/m_textview"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="50dp"
android:gravity="center|center"
android:textColor="#ffffff"
android:text="hello"/>
<Button
android:id="#+id/m_buttonview"
android:layout_width="0dp"
android:layout_weight="2"
android:text="OK"
android:layout_height="50dp" />
</LinearLayout>
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" >
<ListView
android:id="#+id/lv_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:dividerHeight="2dp"
android:divider="#ffffff"
tools:context=".MainActivity" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView m_pic;
TextView m_title;
Button m_btn;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.m_title = (TextView) convertView.findViewById(R.id.m_textview);
holder.m_btn = (Button)convertView.findViewById(R.id.m_buttonview);
holder.m_pic = (ImageView) convertView.findViewById(R.id.m_imageview);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.m_title.setText(rowItem.getTxt());
holder.m_pic.setImageResource(rowItem.getImage());
holder.m_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position + " clicked" , Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
RowItem.java
public class RowItem {
private int image;
private String txt;
public RowItem(int imageview , String textview)
{
this.image = imageview;
this.txt = textview;
}
public int getImage() {
return image;
}
public String getTxt() {
return txt;
}
public void setImage(int image) {
this.image = image;
}
public void setTxt(String txt) {
this.txt = txt;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
String m_txt[] = {"one" , "two" , "three" , "four", "five"};
int m_img [] = {R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher};
ListView m_list;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_list = (ListView)findViewById(R.id.lv_items);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < m_txt.length; i++) {
RowItem item = new RowItem(m_img[i],m_txt[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.listitem, rowItems);
m_list.setAdapter(adapter);
m_list.setOnItemClickListener(MainActivity.this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position) + ": " + rowItems.get(position).getTxt(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
This should helps you.
Happy coding.!!!
use a recyclerview.
a recylerview handles every list item as a view, it can hold clicklisteners for every view it holds and that view can hold clicklisteners for every view its holding.

add image to list view

i want to add image to my list view and this is my list view activity code:
package com.example.dssdfsd;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView lv;
ArrayAdapter<String> adapter;
EditText inputSearch;
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String products[] = {"Dell Inspiron"};
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
}
i want to add image to my list view. how can i do it?
can any one help me to add image on my list view?
You're probably going to need to create a custom ListView Adapter and a new XML Layout for the custom ListView row.
See Tutorial.
Ex:
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp"/>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
CustomList.java
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] web;
private final Integer[] imageId;
public CustomList(Activity context, String[] web, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}

Utilising my created list view. Android

I am trying to use list views and I have managed to create one and it works perfectly. However it creates itself in a new screen. I'd like to know how I can use an already created list view in the main menu (defined by main.xml).
My Java Code:
public class Option2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent startNewActivityOpen = new Intent(Option2Activity.this, ListViewActivity.class);
startActivityForResult(startNewActivityOpen, 0);
}
}
public class ListViewActivity extends ListActivity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ListView lv = (ListView)findViewById(R.id.listview_main);
// Currently unused...
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.list_titles);
TypedArray icons = res.obtainTypedArray(R.array.list_icons);
setListAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
//I tried using lv.setAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
//but it didn't work. 'setListAdapter' is creating a new listview in another screen
}
}
public class Adapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public Adapter(Context ctx, int viewResourceId, String[] strings, TypedArray icons)
{
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
#Override
public int getCount()
{
return mStrings.length;
}
#Override
public String getItem(int position)
{
return mStrings[position];
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(mViewResourceId, null);
Button ib = (Button)convertView.findViewById(R.id.list_button);
ib.setText(mStrings[position]);
ib.setCompoundDrawables((mIcons.getDrawable(position)), null, null, null);
//this doesn't work either, it is supposed to set an image in the button
//if anyone knows how to help me I'd appreciate but it isn't the main issue
TextView tv = (TextView)convertView.findViewById(R.id.list_text);
tv.setText(mStrings[position]);
return convertView;
}
}
THE XML
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:maxHeight="50dp"
android:maxWidth="50dp"
android:src="#drawable/newsimage" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:maxHeight="50dp"
android:maxWidth="50dp"
android:src="#drawable/newsimage" />
<TextView
android:id="#+id/textView1"
android:layout_marginTop="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:text="Option 2 Menu"
android:textSize="25dp" />
</RelativeLayout>
<ListView
android:id="#+id/listview_main"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/newspaper"
android:scaleType="fitXY"
/>
</LinearLayout>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/list_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24dp"
android:padding="6dp"
/>
<Button
android:id="#+id/list_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I think this is all the relevant code. Thank you in advance. I also would like to include that a piece of this code was referenced from other developers which I searched in forums.
FIXED
public class Option2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView)findViewById(R.id.listview_main);
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.list_titles);
TypedArray icons = res.obtainTypedArray(R.array.list_icons);
lv.setAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
}
}
Not exactly like the latest user's reply. But it worked. There is no need for the ListViewActivity.
Thank you forum.
Remove ListViewActivity activity just use the activity I given below,
public class Option2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView)findViewById(R.id.listview_main);
// Currently unused...
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.list_titles);
TypedArray icons = res.obtainTypedArray(R.array.list_icons);
lv.setListAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
}
public class Adapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public Adapter(Context ctx, int viewResourceId, String[] strings, TypedArray icons)
{
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
#Override
public int getCount()
{
return mStrings.length;
}
#Override
public String getItem(int position)
{
return mStrings[position];
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(mViewResourceId, null);
Button ib = (Button)convertView.findViewById(R.id.list_button);
ib.setText(mStrings[position]);
ib.setCompoundDrawables((mIcons.getDrawable(position)), null, null, null);
//this doesn't work either, it is supposed to set an image in the button
//if anyone knows how to help me I'd appreciate but it isn't the main issue
TextView tv = (TextView)convertView.findViewById(R.id.list_text);
tv.setText(mStrings[position]);
return convertView;
}
}
Try this,

Categories

Resources