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,
Related
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.
All! I'am new in android app. Now I have some problem. I can't see the result of changing list right away (after updating listView in my ListFragment).
For example, i called method addNewItem and I didn't see any changes on the screen. But if I touch ListFragment I will see all my changes.
ListFragment:
public class PointsListFragment extends ListFragment {
PlaceItemsAdapter adapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new PlaceItemsAdapter(
getActivity(), R.layout.place_list_item,
new ArrayList<PlaceItem>());
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void addNewItem(int id, String address) {
adapter.items.add(new PlaceItem(id, address));
adapter.notifyDataSetChanged();
}
private class PlaceItemsAdapter extends ArrayAdapter<PlaceItem> {
private final int viewResourceId;
final public ArrayList<PlaceItem> items;
#Override
public int getCount() {
return items.size();
}
#Nullable
#Override
public PlaceItem getItem(int position) {
return items.get(position);
}
public PlaceItemsAdapter(Context context, int viewResourceId, ArrayList<PlaceItem> items) {
super(context, viewResourceId, items);
this.items = items;
this.viewResourceId = viewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
PlaceItem placeItem = getItem(position);
TextView placeIdTextView = (TextView) v.findViewById(R.id.placeId);
placeIdTextView.setText(String.valueOf(placeItem.getId()));
TextView placeAddressView = (TextView) v.findViewById(R.id.placeAddress);
placeAddressView.setText(placeItem.getAddress());
if (selectedValue == position) {
v.setBackgroundResource(R.drawable.active_item);
}
return v;
}
}
}
My activity xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"[enter image description here][1]
android:padding="2dp">
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/forBorder"
android:orientation="horizontal">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_weight="1" />
<TextView
android:text="проложить маршрут"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:drawable/ic_media_ff" />
</LinearLayout>
<fragment
class="com.restfulrobot.cdcapplication.PointsListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_frag" />
</LinearLayout>
Image Example
Thank you, ALL! I found the answer! I called method from another class (no Activity or Fragment). And now I also call method from another class, but i do it through Handler. And it really works fine now!
Something like that:
Message msg = mainActivityHandler.obtainMessage(MainActivity.NEW_MESSAGE, someObjectToAdd);
mainActivityHandler.sendMessage(msg);
i want to combine two LinearLayout, both have different TextView arrangement in them, in a single ListView. so the final look should be like below:
and i run it with my code, but the app wouldn't start. below are my code.
Activity class:
public class MainActivity extends Activity {
// Create list of items
String[] publicModeItems = {
"AAAAA",
"BBBBB"
};
String[] publicModeParameters = {
"YES",
"NO"
};
String[] publicModeResetExe = {
"CCCCC",
"DDDDD"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
private void populateListView() {
CustomList adapter1 = new CustomList(this, publicModeItems, publicModeParameters);
// Build adapter
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
this, // context for the activity
R.layout.text_view_test, // layout to use (create)
publicModeResetExe); // items to display
// Configure the list view
ListView list = (ListView) findViewById(R.id.PublicModeListView);
list.setAdapter(adapter1);
list.setAdapter(adapter2);
}
private class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] publicModeItems;
private final String[] publicModeParameters;
public CustomList(Activity context,
String[] publicModeItems,
String[] publicModeParameters) {
super(context, R.layout.text_views_1, publicModeItems);
this.context = context;
this.publicModeItems = publicModeItems;
this.publicModeParameters = publicModeParameters;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutinflater = context.getLayoutInflater();
View rowView = layoutinflater.inflate(R.layout.text_views_1, null, true);
TextView txtPublicModeItems = (TextView) rowView.findViewById(R.id.PublicModeItems);
TextView txtPublicModeParameters = (TextView) rowView.findViewById(R.id.PublicModeParameters);
txtPublicModeItems.setText(publicModeItems[position]);
txtPublicModeParameters.setText(publicModeParameters[position]);
return rowView;
}
}
}
text_views_1 xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/PublicModeLayoutForTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/PublicModeItems"
android:layout_width="200sp"
android:layout_height="wrap_content"
android:textColor="#drawable/text_color_change" />
<TextView
android:id="#+id/PublicModeOpenBracket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="["
android:textColor="#drawable/text_color_change" />
<TextView
android:id="#+id/PublicModeParameters"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:gravity="end"
android:textColor="#drawable/text_color_change" />
<TextView
android:id="#+id/PublicModeCloseBracket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="]"
android:textColor="#drawable/text_color_change" />
</LinearLayout>
text_view_test xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#drawable/text_color_change" >
</TextView>
activity_main xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/PublicModeListViewLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/black"
android:baselineAligned="true"
android:orientation="vertical"
tools:context="com.example.mycalendar.MainActivity" >
<LinearLayout
android:id="#+id/PublicModeListViewLayout02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/custom_border"
android:padding="5dp" >
<ListView
android:id="#+id/PublicModeListView"
android:layout_width="308dp"
android:layout_height="wrap_content"
android:choiceMode="singleChoice"
android:listSelector="#color/yellow"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
</LinearLayout>
Problem : I just run my code just now, and only 'CCCCC' and 'DDDDD' is showing. so do you have any idea on this?
You should inherit your list adapter from BaseAdapter rather than ArrayAdapter.
Rewrite adapter's getView() method to inflate layout according position, like below.
public View getView(int position, View convertView, ViewGroup parent) {
...
View rootView = null;
if (position == 0 || position == 1) {
rootView = layoutinflater.inflate(R.layout.text_views_1, null, true);
} else {
rootView = layoutinflater.inflate(R.layout.text_views, null, true);
}
...
return rootView;
}
You set the list adapter twice
list.setAdapter(adapter1);
list.setAdapter(adapter2);
in this case the current adapter is the second, not them both.
Use ListView with SimpleAdapter or a custom adapter and that will solve all your problems, check out this for SimpleAdapter tutorial to learn a the basics and this tutorial to learn how you can make multiple views instead of just 1. This tutorial is about creating custom adapter
BTW, I have few comments on your code and xml layout
First, there is no need for 2 TextViews for your bracket, you can easily add them programmatically to the String[] or even to YES/NO TextView.
Second, You're not using a ViewHolder in your CustomList adapter and this is not a good practice as every time you scroll your list, it creates new view although it can use already existing one.
I already solve this problem. but it seems not so convenient to use this method.
public class PublicModeActivity extends Activity {
// Create list of items
String[] publicModeItems = {
"AAAAA",
"BBBBB"
};
String[] publicModeParameters = {
"YES",
"NO"
String[] publicModeResEx = {
"",
"",
"CCCCC",
"DDDDD"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
private void populateListView() {
CustomList adapter = new CustomList(this, publicModeItems, publicModeParameters, publicModeResEx);
// Configure the list view
ListView list = (ListView) findViewById(R.id.PublicModeListView);
list.setAdapter(adapter);
}
private class CustomList extends BaseAdapter {
private final Activity context;
private final String[] publicModeItems;
private final String[] publicModeParameters;
private final String[] publicModeResEx;
public CustomList(Activity context,
String[] publicModeItems,
String[] publicModeParameters,
String[] publicModeResEx) {
super();
this.context = context;
this.publicModeItems = publicModeItems;
this.publicModeParameters = publicModeParameters;
this.publicModeResEx = publicModeResEx;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutinflater = context.getLayoutInflater();
View rowView = null;
Log.i("PublicModeActivity", "" + position);
if (position < 2) {
rowView = layoutinflater.inflate(R.layout.text_views_1, null, true);
TextView txtPublicModeItems = (TextView) rowView.findViewById(R.id.PublicModeItems);
TextView txtPublicModeParameters = (TextView) rowView.findViewById(R.id.PublicModeParameters);
txtPublicModeItems.setText(publicModeItems[position]);
txtPublicModeParameters.setText(publicModeParameters[position]);
} else {
rowView = layoutinflater.inflate(R.layout.text_view_test, null, true);
TextView txtPublicModeResEx = (TextView) rowView.findViewById(R.id.PublicModeResEx);
txtPublicModeResEx.setText(publicModeResEx[position]);
}
return rowView;
}
#Override
public int getCount() {
return 4;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
}
}
I need to put that blank string "", to match the number of row with the upper layout (text_views_1) even-though those blank string are use in different layout. so it is not so convenient especially when you want to display so many data. If someone here have much simpler method than this. feel free to share with me/us. i'm eager to learn. thank you!
I am using a viewpager in my program and on that I am displaying custom listview. On every viewpager swipe I am displaying the same listview but with differnt list items. I want to get all the items checked from all those listviews, when I click on the submit button.
But this submit button is not on my viewpager. Its quite complicated for me. Here is my main class code(I am just showing part of my code there are no errors in the code right now):
public class HotelMenu extends FragmentActivity implements CompletionListener {
static final int ITEMS = 10;
MyAdapter mAdapter;
ViewPager mPager;
private NetworkTask networkTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_menu);
get_restaurant_menu();
mAdapter = new MyAdapter(getSupportFragmentManager(),HotelMenu.this);
mPager = (ViewPager) findViewById(R.id.pager);//adapter for viewpager
Button submit= (Button) findViewById(R.id.next);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//here I want all the items checked from the listview
}
});
}
Here is my layout for this class:
<?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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip"
android:background="#drawable/home_screen_background">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tvRestNameForMenu"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#ffffff"
android:layout_gravity="center_vertical"
android:background="#drawable/offers_text"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:alpha="0.7"
android:background="#android:color/white">
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:background="#drawable/button_shape"
android:textColor="#android:color/white">
</Button>
</LinearLayout>
</LinearLayout>
This is my adpater for viewpager:
public static class MyAdapter extends FragmentStatePagerAdapter {
Context context;
public MyAdapter(FragmentManager fragmentManager, Context context) {
super(fragmentManager);
this.context=context;
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show list of maincourse items
// return ArrayListFragment.newInstance(position, mainCourse);//pass viewpager page position and list to be displayed
case 1: // Fragment # 1 - This will show list of soups
return ArrayListFragment.newInstance(position,startersName,startersCost );
default:// Fragment # 2-9 - Will show list
return ArrayListFragment.newInstance(position, maincourseName,maincourseCost);
}
}
}
and finally this is my fragment for displaying listview on viewpager:
public class ArrayListFragment extends android.support.v4.app.Fragment{
int fragNum;
String[] arr;
ArrayList<String>item_name;
ArrayList<String>item_cost;
ListView lvsoups;
MyAdapter myAdapter;
Context context;
LayoutInflater inflater1;
View layoutView;
public static final ArrayListFragment newInstance(int val, ArrayList<String> itemName, ArrayList<String> itemCost){
ArrayListFragment list=new ArrayListFragment();
//Bundle is used to use values and array passed through hotel menu class
Bundle bundle = new Bundle(2);
bundle.putInt("val", val);
bundle.putStringArrayList("itemName",itemName);
bundle.putStringArrayList("itemCost",itemCost);
list.setArguments(bundle);
return list ;
}
/**
* Retrieving this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init passed values
fragNum = getArguments() != null ? getArguments().getInt("val") : 1;
item_name=getArguments().getStringArrayList("itemName");
item_cost=getArguments().getStringArrayList("itemCost");
}
/**
* to set view to the fragment activity
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_pager_list,
container, false);
lvsoups = (ListView) layoutView.findViewById(R.id.listMenu);
myAdapter = new MyAdapter(getActivity(), item_name,item_cost);
lvsoups.setAdapter(myAdapter);//set adapter to the list view
return layoutView;
}
//adapter for the listview
public class MyAdapter extends BaseAdapter {
ArrayList<String> itemName;
ArrayList<String> itemCost;
Context context;
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<String> item_name, ArrayList<String> item_cost) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(item_name!=null)
{
// arr = new String[objects.length];
this.itemName = item_name;
this.itemCost=item_cost;
}
}
#Override
public int getCount() {
return itemName.size();
}
#Override
public Object getItem(int position) {
return itemName.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int value;
View menuRow = inflater.inflate(R.layout.hotel_menu_list_item, null);
TextView tvSoups = (TextView) menuRow.findViewById(R.id.tvMenuItem); //To set name of menu item, for example Corn Soup
TextView tvPrice = (TextView) menuRow.findViewById(R.id.tvMenuPrice); //To set price of that item
CheckBox cbQty = (CheckBox) menuRow.findViewById(R.id.cbMenuItem);
Spinner spQty = (Spinner) menuRow.findViewById(R.id.spinnerQty);
String[] quantity = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
ArrayAdapter spinnerAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, quantity);
spQty.setAdapter(spinnerAdapter);
tvSoups.setText(itemName.get(position));
tvPrice.setText(itemCost.get(position));
Log.e("arr", itemName.get(position));
if (cbQty.isChecked()) {
value = 1;
} else {
value = 0;
}
menuRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent=new Intent(SearchResult.this,RestMainActivity.class);
// intent.putExtra("Hotel_Master_Id",hotelMasterIdList.get(position));
// startActivity(intent);
}
});
return menuRow;
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
This is my hotel_menu_list_item.xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:weightSum="5">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cbMenuItem" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_weight="3"
android:id="#+id/tvMenuItem" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_weight="1"
android:id="#+id/tvMenuPrice" />
<Spinner
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/spinnerQty"
android:layout_weight="1"
>
</Spinner>
</LinearLayout>
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(..).