So what I want to do is have a different image for each list item in my App. I've been attempting to do this for a little while now and have no idea what I'm doing.
Here's what I'm trying to do:
How do I go about this? Here's my current code:
package net.androidbootcamp.gamesandcoffee;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[ ] attraction = {"Games", "Coffee Shops"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main, R.id.games, attraction));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
switch (position) {
case 0:
startActivity(new Intent(MainActivity.this, games.class));
break;
case 1:
startActivity(new Intent(MainActivity.this, coffee.class));
break;
}
}
}
and my XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/games"
android:textSize="20sp"
android:text="#+id/games"
android:drawableLeft="#drawable/games"/>
</RelativeLayout>
For that you have to create a custom adapter, where you can customize all the ListView items.
public class ListAdapter extends ArrayAdapter<Item> {
public ListAdapter(Context context, int imageViewResourceId) {
super(context, imageViewResourceId);
}
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
}
Item p = getItem(position);
if (p != null) {
ImageView iv = (ImageView ) v.findViewById(R.id.id);
if (iv != null) {
iv .setImageResource(R.id.xyz);
}
}
return v;
}
}
load the image resource id's to the array and pass to the list adapter in this way
int[] images = {R.drawables.firstimg,R.drawables.secondimg};
setListAdapter(new CustomAdapter(this,images, attraction));
Crate CustomAdapter Class
public class CustomAdapter extends BaseAdapter{
private Context context;
int[] images;
String[] textdata;
public CustomAdapter(Context context, int[] images,String[] textdata) {
this.context = context;
this.images=images;
this.textdata=textdata;
}
#Override
public Object getItem(int position) {
return textdata.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.drawer_listitem,parent,false);
}else {
row = convertView;
}
TextView name = (TextView) row.findViewById(R.id.draweritemtext);
ImageView image = (ImageView) row.findViewById(R.id.draweritemimage);
name.setText(textdata[position]);
image.setImageResource(images[position]);
return row;
}
#Override
public int getCount() {
return textdata.size();
}
}
Following these two video tutorials, geared towards beginners, I was able to arrive to my desired result. Thank you those who contributed, but none of the answers or resources provided were geared towards beginners that lack experience.
These are the videos I watched
Android Studio Tutorial - 18 - ListView with Custom Adapter part-1
Android Studio Tutorial - 19 - ListView with Custom Adapter part-2
Related
My code has an ExpandableListView and each child (schedule) can be deleted via a delete button in the child. I want to use a functionality of "Edit" TextView so that if the user clicks on "Edit" the Delete Buttons will be visible. I tried it on my custom adapter MainAdapter but gives me crashes. Could anyone help me?
MainAdapter.java
package com.example.easyplan;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class MainAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> listPlan; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> listScheduleMap;
ImageButton scheduleDeleteBtn;
public MainAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this.listPlan = listDataHeader;
this.listScheduleMap = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this.listScheduleMap.get(this.listPlan.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.schedule_group, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.scheduleGroup);
scheduleDeleteBtn = convertView.findViewById(R.id.scheduleDeleteBtn);
scheduleDeleteBtn.setVisibility(View.INVISIBLE);
scheduleDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> plan = listScheduleMap.get(listPlan.get(groupPosition));
plan.remove(childPosition);
notifyDataSetChanged();
}
});
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.listScheduleMap.get(this.listPlan.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.listPlan.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.listPlan.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.plan_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.planGroup);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setDeleteVisibility(boolean visible){
for(int j = 0; j < getGroupCount(); j ++){
for(int i = 0; i<getChildrenCount(i); i++ ){
if(visible){
scheduleDeleteBtn.setVisibility(View.VISIBLE);
}else{
scheduleDeleteBtn.setVisibility(View.INVISIBLE);
}
}
}
}
}
PlansFragment.java
package com.example.easyplan;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class PlansFragment extends Fragment {
TextView editText;
MainAdapter mainAdapter;
ExpandableListView planExplandable;
List<String> listPlanName;
HashMap<String, List<String>> listSchedules;
TextView textView;
static int count = 0;
View view;
public PlansFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_plans_fragment, container, false);
listPlanName = new ArrayList<String>();
listSchedules = new HashMap<String, List<String>>();
// get the listview
planExplandable = (ExpandableListView) view.findViewById(R.id.plansExpandable);
textView = view.findViewById(R.id.scheduleGroup);
editText = view.findViewById(R.id.planEditText);
// preparing list data
// prepareListData();
createAPlan(3);
createAPlan(1);
createAPlan(3);
createAPlan(4);
mainAdapter = new MainAdapter(getActivity(), listPlanName, listSchedules);
// setting list adapter
planExplandable.setAdapter(mainAdapter);
//mainAdapter.setDeleteVisibility(false);
/* editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mainAdapter.setDeleteVisibility(true);
}
});*/
return view;
}
public HashMap<String, String> getData(){
return null;
}
private void createAPlan(int sch){
listPlanName.add("Plan#"+(count+1));
List<String> schedules = new ArrayList<String>();
if(sch > 0 ){
for (int i = 1; i <= sch; i++){
schedules.add("Schedule#" + i);
}
}
listSchedules.put(listPlanName.get(count),schedules);
count++;
}
}
The child's xml has
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.8">
<TextView
android:id="#+id/scheduleGroup"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textColor="#android:color/black" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2">
<ImageButton
android:id="#+id/scheduleDeleteBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:srcCompat="#drawable/delete_icon"
android:visibility="visible"
android:clickable="true"
></ImageButton>
</LinearLayout>
Inside your fragment use setOnItemClickListener() method on your listView and in overriden method make use of getFirstVisiblePosition() to subtract from the position where you will find the position of that view. then set the visibility.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listPosition = position - planExplandable.getFirstVisiblePosition();
if (planExplandable.getChildAt(listPosition).findViewById(R.id.yourview).getVisibility() == View.INVISIBLE) {
//Write your logic here
planExplandable.getChildAt(listPosition).findViewById(R.id.yourview).setVisibility(View.VISIBLE);
}
}
If this won't help then please paste your crash log.
I'm trying to get my replaced fragment to appear in the detail fragment but after debugging my app on a tablet emulator and selecting the necessary list view item, the log cat gives me this error:
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0050 (com.apptacularapps.exitsexpertlondonlite:id/detail_container) for fragment FragmentWCBank{3b4ea8fb #0 id=0x7f0c0050}
I really don't understand why I'm getting this error when my fragment is there within my project. Does anyone know what I'm doing wrong and how to fix this?
FragmentWCLine.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FragmentWCLine extends android.support.v4.app.Fragment {
public final static String EXTRA_MESSAGE = "Station_key";
private class WC {
private CharSequence station;
private CharSequence zone;
private Class<? extends Activity> activityClass;
private Class<? extends android.support.v4.app.Fragment> fragmentClass;
public WC(int stationResId, int zoneResId, Class<? extends Activity> activityClass, Class<? extends android.support.v4.app.Fragment> fragmentClass) {
this.fragmentClass = fragmentClass;
this.activityClass = activityClass;
this.station = getResources().getString(stationResId);
this.zone = getResources().getString(zoneResId);
}
#Override
public String toString() { return station.toString(); }
public String getzone(){ return zone.toString(); }
}
private static WC[] mWC;
private boolean mTwoPane;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_wc_line, container, false);
// Instantiate the list of stations.
mWC = new WC[]{
new WC(R.string.bank, R.string.zone_1, WCBankActivity.class, FragmentWCBank.class),
new WC(R.string.wat, R.string.zone_1, WCWATActivity.class, FragmentWCWAT.class)
};
final ListView listView = (ListView)v.findViewById(R.id.list_wc);
listView.setAdapter(new MyAdapter(getActivity(), mWC));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mTwoPane){
setItemNormal();
View rowView = view;
setItemSelected(rowView);
}
else{
Intent intent = new Intent(getActivity(), mWC[position].activityClass);
String station = mWC[position].station.toString();
intent.putExtra(EXTRA_MESSAGE, station);
startActivity(intent);
}
}
public void setItemSelected(View view){
View rowView = view;
view.setBackgroundColor(Color.parseColor("#66CCCC"));
TextView tv0 = (TextView)rowView.findViewById(R.id.list_item_station);
tv0.setTextColor(Color.parseColor("#000099"));
TextView tv1 = (TextView)rowView.findViewById(R.id.list_item_zone);
tv1.setTextColor(Color.parseColor("#000099"));
}
public void setItemNormal()
{
for (int i=0; i< listView.getChildCount(); i++) {
View v = listView.getChildAt(i);
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.list_item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.list_item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
}
});
return v;
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView station;
TextView zone;
}
LayoutInflater inflater;
WC[] mWC;
public MyAdapter(Context contexts, WC[] samples) {
this.mWC = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mWC.length;
}
#Override
public Object getItem(int position) {
return mWC[position];
}
#Override
public long getItemId(int position) {
return 0;
}
/**set selected position**/
private int selectPosition = -1;
public void setSelectPosition(int position){
if(position!=selectPosition){
selectPosition = position;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_dualline, null);
viewHolder = new ViewHolder();
viewHolder.station = (TextView) convertView.findViewById(R.id.list_item_station);
viewHolder.zone = (TextView) convertView.findViewById(R.id.list_item_zone);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.station.setText(mWC[position].station);
viewHolder.zone.setText(mWC[position].getzone());
//change item color
if(position==selectPosition){
convertView.setBackgroundColor(Color.parseColor("#000099"));
viewHolder.station.setTextColor(Color.parseColor("#000099"));
}else {
}
return convertView;
}
}
}
WCBankActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
public class WCBankActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "Station_key";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_wc_bank);
if (savedInstanceState == null) {
// Get the message from the intent
Intent intent = getIntent();
// Notice to specify the sender Activity for the message
String station = intent.getStringExtra(WCBankActivity.EXTRA_MESSAGE);
FragmentWCBank newFragment = new FragmentWCBank();
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
}
}
}
FragmentWCBank.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentWCBank extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wc_bank, container, false);
return v;
}
}
fragment inflation
fragment_wc_bank.xml layout
<?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"
android:id="#+id/detail_container">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Bank"
android:id="#+id/textView0"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
fragment_wc_line.xml layout
<?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"
android:id="#+id/fragmentwcline">
<ListView
android:id="#+id/list_wc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="false"
android:layout_centerHorizontal="true"/>
</LinearLayout>
activity_main.xml layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/master_container"
android:name="com.apptacularapps.exitsexpertlondonlite.FragmentMainList"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
activity_main.xml layout (sw600dp)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".MainActivity" >
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/master_container"/>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:id="#+id/detail_container"/>
</LinearLayout>
Undesired result
Your code transaction.replace(R.id.detail_container...Now this may be the correct UI element. I am assuming this is the correct UI. If so, fragment_wc_bank layout xml does not have that ID detail_container, hence you get error, simple as that. However activity_main.xml has that ID, again I am assuming detail_container is the correct UI that you want.
Suggested code FROM:
setContentView(R.layout.fragment_wc_bank);
TO:
setContentView(R.layout.activity_main.xml);
Notes:
activity_main.xml is the only difference between the 2 codes above.
This is a common error but we all have to learn from this. Learn more about layouts. It is a critical knowledge in making Android apps.
There are 2 different activity_main.xml files you posted. They should at least be similar. Otherwise you could be very confused.
Your activity is trying to inflate a layout, then place a fragment into it in place of the view detail_container. detail_container does not exist in that layout- either you forgot to add it or you're inflating the wrong thing. I notice you're inflating R.layout.fragment_wc_bank for both the fragment and the main activity, my guess is you're inflating the wrong layout in the activity.
I have a ListView with the name of the timer, and the time of the timer, I don't know how to implement the countdown part. In each row in the ListView I have two TextViews: the time and the name of the timer, and then a Button which should start and stop the timer. This is my custom ListViewAdapter class, where I believe the timer should start stop in the OnClick method, to have the timer reacting to each line:
public class CustomTimerRowAdapter extends ArrayAdapter<TimerRow> {
Context context;
int height;
public CustomTimerRowAdapter(Context context, int resourceId,
List<TimerRow> items) {
super(context, resourceId, items);
this.context = context;
// Height of screen from not Activity subclass
height = context.getResources().getDisplayMetrics().heightPixels;
}
/* private view holder class */
private class ViewHolder {
TextView txtTimer;
TextView txtName;
Button bStartStop;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TimerRow rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.timer_row, null);
holder = new ViewHolder();
// make layout params
holder.txtTimer = (TextView) convertView.findViewById(R.id.tvTimes);
holder.txtTimer.getLayoutParams().height = height / 10;
holder.txtName = (TextView) convertView.findViewById(R.id.tvName);
holder.txtName.getLayoutParams().height = height / 10;
holder.bStartStop = (Button) convertView
.findViewById(R.id.bStartStopTimer);
holder.bStartStop.getLayoutParams().height = height / 10;
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtName.setText(rowItem.getName());
holder.txtTimer.setText(rowItem.getTimer());
final String name = holder.txtName.getText().toString();
holder.bStartStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// THIS IS WHERE THE TIMER SHOULD START AND STOP.
Toast.makeText(context, "Selected " + name + " timer.",
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
The length of the timers can be up to 99 hours, 59 minutes and 59 seconds. The timers are formatted as strings like this "hh:mm:ss".
Please use RecyclerView instead of Listview. Here you can check and download the source code of Countdown timers in a ListView
activity_main.xml
<RelativeLayout android:layout_width=”match_parent”
android:layout_height=”match_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”>
<android.support.v7.widget.RecyclerView
android:id=”#+id/recycler_view”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:scrollbars=”vertical” />
</RelativeLayout>
adapter_layout.xml
<?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="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:padding="10dp"
android:id="#+id/tv_timer"/>
</LinearLayout>
MainActivity.java
package com.androidsolutionworld.multipletimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList al_data = new ArrayList<>();
private Adapter obj_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
al_data.add("1234");
al_data.add("1257");
al_data.add("100");
al_data.add("1547");
al_data.add("200");
al_data.add("500");
al_data.add("2000");
al_data.add("1000");
obj_adapter = new Adapter(al_data);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(obj_adapter);
}
}
Custom Adapter:
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter{
private ArrayList al_data;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView tv_timer;
CountDownTimer timer;
public MyViewHolder (View view){
super(view);
tv_timer = (TextView)view.findViewById(R.id.tv_timer);
}
}
public Adapter(ArrayList al_data) {
this.al_data = al_data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.tv_timer.setText(al_data.get(position));
if (holder.timer != null) {
holder.timer.cancel();
}
long timer = Long.parseLong(al_data.get(position));
timer = timer*1000;
holder.timer = new CountDownTimer(timer, 1000) {
public void onTick(long millisUntilFinished) {
holder.tv_timer.setText("" + millisUntilFinished/1000 + " Sec");
}
public void onFinish() {
holder.tv_timer.setText("00:00:00");
}
}.start();
}
#Override
public int getItemCount() {
return al_data.size();
}
}
How can I modify the code below so that each item has two lines instead of one? I want the code in the mSample section the same layout as I've posted so please do not inappropriately modify it unless it is necessary. Below is an image depicting what the list looks like with one line.
I know that the click event and list adapter codes needs to change, but I don't know what to.
I also have an xml called list_item_entry.xml that contains two text views (1 bigger than the other) in a linear layout but I'm not sure if I need to use that.
package com.example.android.animationsdemo;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* The launchpad activity for this sample project. This activity launches other activities that
* demonstrate implementations of common animations.
*/
public class MainActivity extends ListActivity {
/**
* This class describes an individual sample (the sample title, and the activity class that
* demonstrates this sample).
*/
private class Sample {
private CharSequence title;
private Class<? extends Activity> activityClass;
public Sample(int titleResId, Class<? extends Activity> activityClass) {
this.activityClass = activityClass;
this.title = getResources().getString(titleResId);
}
#Override
public String toString() {
return title.toString();
}
}
/**
* The collection of all samples in the app. This gets instantiated in {#link
* #onCreate(android.os.Bundle)} because the {#link Sample} constructor needs access to {#link
* android.content.res.Resources}.
*/
private static Sample[] mSamples;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.title_crossfade, CrossfadeActivity.class),
new Sample(R.string.title_card_flip, CardFlipActivity.class),
new Sample(R.string.title_screen_slide, ScreenSlideActivity.class),
new Sample(R.string.title_zoom, ZoomActivity.class),
new Sample(R.string.title_layout_changes, LayoutChangesActivity.class),
};
setListAdapter(new ArrayAdapter<Sample>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
mSamples));
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// Launch the sample associated with this list position.
startActivity(new Intent(MainActivity.this, mSamples[position].activityClass));
}
}
list_item_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingRight="?android:attr/scrollbarSize"
android:baselineAligned="false">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="6dip"
android:layout_weight="1">
<TextView android:id="#+id/list_item_entry_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
/>
<TextView android:id="#+id/list_item_entry_summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/list_item_entry_title"
android:layout_alignLeft="#id/list_item_entry_title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:singleLine="true"
android:textColor="?android:attr/textColorSecondary"
/>
</RelativeLayout>
</LinearLayout>
class errors
package com.example.android.animationsdemo;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
* The launchpad activity for this sample project. This activity launches other activities that
* demonstrate implementations of common animations.
*/
public class MainActivity extends ListActivity {
/**
* This class describes an individual sample (the sample title, and the activity class that
* demonstrates this sample).
*/
private class Sample {
private CharSequence title;
private CharSequence summary;
private Class<? extends Activity> activityClass;
public Sample(int titleResId, int summaryResId, Class<? extends Activity> activityClass) {
this.activityClass = activityClass;
this.title = getResources().getString(titleResId);
this.summary = getResources().getString(summaryResId);
}
#Override
public String toString() { return title.toString(); return summary.toString(); }
}
/**
* The collection of all samples in the app. This gets instantiated in {#link
* #onCreate(android.os.Bundle)} because the {#link Sample} constructor needs access to {#link
* android.content.res.Resources}.
*/
private static Sample[] mSamples;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.title_crossfade, R.string.summary_crossfade, CrossfadeActivity.class),
new Sample(R.string.title_card_flip, R.string.summary_card_flip, CardFlipActivity.class),
new Sample(R.string.title_screen_slide, R.string.summary_screen_slide, ScreenSlideActivity.class),
new Sample(R.string.title_zoom, R.string.summary_zoom, ZoomActivity.class),
new Sample(R.string.title_layout_changes, R.string.summary_layout_changes, LayoutChangesActivity.class),
};
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// Launch the sample associated with this list position.
startActivity(new Intent(MainActivity.this, mSamples[position].activityClass));
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView title;
TextView summary;
}
LayoutInflater inflater;
Sample[] mSamples;
public MyAdapter(Context contexts, Sample[] samples) {
this.mSamples = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mSamples.length;
}
#Override
public Object getItem(int position) {
return mSamples[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.entry, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_entry_title);
viewHolder.summary = (TextView) convertView.findViewById(R.id.list_item_entry_summary);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(mSamples[position].title);
viewHolder.summary.setText(mSamples[position].summary);
return convertView;
}
}
}
maybe it will help you
public class MainActivity extends ListActivity {
/*
current code
*/
public void onCreate(Bundle savedInstanceState) {
//
//
setListAdapter(new SampleAdapter(this,
android.R.layout.simple_list_item_1,
mSamples));
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// Launch the sample associated with this list position.
startActivity(new Intent(MainActivity.this, mSamples[position].activityClass));
}
public static class SampleAdapter extends ArrayAdapter<Sample>{
SampleAdapter(Context context, int resource, Sample[] objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rootView = super.getView(position, convertView, parent);
TextView firstLine = rootView.findViewById(R.id.list_item_entry_title);
TextView secondLine = rootView.findViewById(R.id.list_item_entry_summary);
firstLine.setText(getItem(position)./*Sample class field*/);
secondLine.setText(getItem(position)./*Sample class field*/);
return rootView;
}
}
}
If you want to customise the rows with more than one TextView then you should implement your own Adapter. The xml you have posted is useless because you are using android.R.layout.simple_list_item_1 and android.R.id.text1. To achieve what you want to do try this:
public class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView title;
TextView summary;
}
LayoutInflater inflater;
Sample[] mSamples;
public MyAdapter(Context contexts, Sample[] samples) {
this.mSamples = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mSamples.length;
}
#Override
public Object getItem(int position) {
return mSamples[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.entry, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_entry_title);
viewHolder.summary = (TextView) convertView.findViewById(R.id.list_item_entry_summary);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(mSamples[position].title);
viewHolder.summary.setText(mSamples[position].summary);
return convertView;
}
}
And you can use it like this:
list.setAdapter(new MyAdapter(this, samples));
When I am trying to use the drop down list of a spinner, the option doesn't select, I was investigating in Google and I think I am configuring the spinner correctly for cities but maybe I have forgotten something in the adapter. I am using a CustomAdapter.
My fragment is:
In the Fragment call I have this code:
ArrayList<ItemPair> data1 = IAndroid.getAllCities();
Spinner spCity = (Spinner) rootView.findViewById(R.id.spPoblacion);
spCity.setAdapter(new ItemPairListAdapter(inflater.getContext(), data1));
At the moment I don't have the select click item associated, I only set all items in dropdownlist.
My fragment.xml is:
<Spinner
android:id="#+id/spProvincia"
android:layout_width="wrap_content"
android:clickable="true"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1" />
My Custom Adapter is:
package info.android.adapter;
import info.android.MainActivity;
import info.android.R;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
public class ItemPairListAdapter extends BaseAdapter implements SpinnerAdapter {
private Context context;
private ArrayList<info.android.model.ItemPair> navProOffers;
public ItemPairListAdapter(Context context, ArrayList<info.android.model.ItemPair> navProOffers) {
this.context = context;
this.navProOffers = navProOffers;
}
#Override
public int getCount() {
return navProOffers.size();
}
#Override
public info.android.model.ItemPair getItem(int position) {
return navProOffers.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.fragment_row_itempair, null);
}
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
TextView txtKey = (TextView) convertView.findViewById(R.id.txtKey);
TextView txtValue = (TextView) convertView.findViewById(R.id.txtValue);
info.android.model.ItemPair ip = getItem(position);
if (ip != null)
{
if (ip.Key != null) txtKey.setText(ip.Key);
if (ip.Value != null) txtValue.setText(ip.Value);
}
convertView.setTag(ip.Key);
return convertView;
}
}
My ItemPair class is:
package info.android.model;
public class ItemPair {
public String Key;
public String Value;
}
What is wrong? What do I need to simulate the click behaviour and afterwards receive my item?
I removed click listener in the getView, answered it for G.T.
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.fragment_row_itempair, null);
}
TextView txtKey = (TextView) convertView.findViewById(R.id.txtKey);
TextView txtValue = (TextView) convertView.findViewById(R.id.txtValue);
info.android.model.ItemPair ip = getItem(position);
if (ip != null)
{
if (ip.Key != null) txtKey.setText(ip.Key);
if (ip.Value != null) txtValue.setText(ip.Value);
}
convertView.setTag(ip.Key);
return convertView;
}