How to inflate views programmatically in vertical order - java

I just picked up Android developing. I decided to make a ToDo-list(simple and has a somewhat visual body) but I'm facing problems with inflating Layout in order.
Basically I have an Activity that collects information that is supposed to be shown in Main Activity. I get one of them showing up, but can't figure out how to add more than one of them. They'd be showing up in vertical order as the title says.
Main:
package com.example.victor.todo;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
String NEW_TASK, NEW_TASK_DETAILS;
int pos = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add_task){
Intent i = new Intent(this,AddTaskActivity.class);
startActivityForResult(i, 1);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
String task = data.getStringExtra("task");
String taskDetails = data.getStringExtra("details");
String taskInfo = data.getStringExtra(AddTaskActivity.EXTRA_NAME);
Log.i("TAG", "task: " + task);
Log.i("TAG", "task info: " + taskDetails);
AddTask(task, taskDetails);
} else {
//DO SOMETHING IF NO INFO IS RETURNED
}
}
}
public void AddTask(String task, String details){
TextView tw = (TextView)findViewById(R.id.addMainHint);
((ViewManager) tw.getParent()).removeView(tw);
LinearLayout linearLayoutMain = (LinearLayout) findViewById(R.id.mainLinearLayout);
View v = getLayoutInflater().inflate(R.layout.task_listing, null);
linearLayoutMain.addView(v);
TextView taskName = (TextView) v.findViewById(R.id.single_task_info);
taskName.setText(task);
CheckBox taskCheckBox = (CheckBox) v.findViewById(R.id.single_task_checkbox);
taskCheckBox.setChecked(false);
/*
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.single_task_layout);
relativeLayout.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
*/
/*
RelativeLayout layout = (RelativeLayout) findViewById(R.id.single_task_layout);
TextView ll = new TextView();
*/
}
public void TaskClicked(){
}
}
task_listing.xml(a relative layout that acts as the container of the info):
<?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="70dp"
android:id="#+id/single_task_layout"
>
<TextView
android:layout_width="300dp"
android:layout_height="30dp"
android:id="#+id/single_task_info"
android:layout_marginTop="20dp"
android:textColor="#color/primary_material_dark"
android:textSize="20sp"
android:layout_alignParentRight="true"
android:layout_marginLeft="40dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:clickable="true" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/single_task_checkbox"
android:layout_gravity="left"
android:layout_toLeftOf="#id/single_task_info"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:enabled="true"
android:clickable="true"
android:onClick="TaskClicked"
android:visibility="visible" />
</RelativeLayout>
I guess I'm using the wrong tools but I don't even know what to search for! I don't have problems with Java itself but the design is giving me serious headache. I've been trying to figure this out for hours(it's 7.48 in the morning)!
Again, it works if I add just one of the layouts so the other javas and xmls aren't probably that important.
Thanks!

Use a listview is correct. Try doing this (A little bit more elaborate than what you have but worth it.
Create a Task object that implements Pacelable. This object can be sent back in the result of AddTaskActivity
public class Task implements Parcelable {
private String myTask;
private String myDetails;
public static final Parcelable.Creator<Task> CREATOR
= new Parcelable.Creator<Task>() {
public Task createFromParcel(Parcel in) {
return new Task(in);
}
public Task[] newArray(int size) {
return new Task[size];
}
};
public Task() {}
public Task(Parcel in){
myTask = in.readString();
myDetails = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(myTask);
dest.writeString(myDetails);
}
}
And this is your class slightly modified
public class MainActivity extends ActionBarActivity {
private Adapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myAdapter = new Adapter();
ListView listView = (ListView)findViewById(android.R.id.list);
listView.setAdapter(myAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add_task){
Intent i = new Intent(this,AddTaskActivity.class);
startActivityForResult(i, 1);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
myAdapter.addTask(data.getParcelableExtra(AddTaskActivity.[key constant]));
} else {
//DO SOMETHING IF NO INFO IS RETURNED
}
}
}
public void TaskClicked(){
}
private class Adapter extends BaseAdapter {
private List<Task> myTasks;
public Adapter() {
myTasks = new ArrayList<Task>();
}
public void addTask(Task task) {
myTasks.add(task);
notifyDataSetChanged();
}
#Override
public int getCount() {
return myTasks.size();
}
#Override
public Object getItem(int position) {
return myTasks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tw = (TextView)findViewById(R.id.addMainHint);
((ViewManager) tw.getParent()).removeView(tw);
convertView = getViewNotNull(convertView, parent);
Task task = (Task)getItem(position);
TextView taskName = (TextView) convertView.findViewById(R.id.single_task_info);
taskName.setText(task.getTask());
}
private View getViewNotNull(View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.task_listing)
//here you should create a viewholder and set it on the view using setTag()
}
return convertView;
}
}
}
I quickly threw this together so hopefully it has what you need to get started
you'll still need to implement the item click listener on the listview as well as the check status for the checkboxes

Use ListView to get it done easily.

Related

Android custom listView click - how to call an intent to another activity

Some one help please. I'm trying to create an app with a custom list view which has text view and image view. the list items are filtered and on clicking on the list item it should open up an associated activity. However the app crashes when i click on an item giving message,"thread exiting with uncaught exception". Here are my codes.
main.java
package com.example.lenovo.filterapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
ListView lv;
SearchView sv;
String[] names = {"Lionel Messi","Christiano Ronaldo","Neymar JNR","Luis Suarez"};
int[] images ={R.drawable.badge,R.drawable.bucky,R.drawable.dentala,R.drawable.house};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView);
sv = (SearchView) findViewById(R.id.searchView);
//Adapter
final Adapter adapter = new Adapter(this,getPlayers());
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
return false;
}
});
final HashMap<String, Class> hashMap=new HashMap<String, Class>();
hashMap.put("Lionel Messi",Lionel.class);
hashMap.put("Christiano Ronaldo",Christiano.class);
hashMap.put("Neymar JNR",Neymar.class);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String openClass = (String) adapter.getItem(position);
Intent myIntent1 = new Intent(MainActivity.this,
hashMap.get(openClass));
startActivity(myIntent1);
}
});
}
private ArrayList<Player> getPlayers(){
ArrayList<Player> players = new ArrayList<Player>();
Player p;
for (int i = 0;i<names.length;i++){
p = new Player(names[i],images[i]);
players.add(p);
}
return players;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter.java
package com.example.lenovo.filterapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by LENOVO on 2/6/2016.
*/
public class Adapter extends BaseAdapter implements Filterable{
Context c;
ArrayList<Player> players;
CustomFilter filter;
ArrayList<Player> filterList;
public Adapter(Context c, ArrayList<Player> players) {
this.c = c;
this.players = players;
this.filterList = players;
}
#Override
public int getCount() {
return players.size();
}
#Override
public Object getItem(int position) {
return players.get(position);
}
#Override
public long getItemId(int position) {
return players.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView= inflater.inflate(R.layout.activity_customrow,null);
}
TextView nameTxt = (TextView) convertView.findViewById(R.id.buckysTextView);
ImageView img = (ImageView) convertView.findViewById(R.id.alisImageView);
//Set data to them
nameTxt.setText(players.get(position).getName());
img.setImageResource(players.get(position).getImg());
return convertView;
}
#Override
public Filter getFilter() {
if(filter == null){
filter = new CustomFilter();
}
return filter;
}
//Inner Class
class CustomFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length()>0){
//Constraint to Upper
constraint = constraint.toString().toUpperCase();
ArrayList<Player> filters = new ArrayList<Player>();
//get specific Items
for (int i =0;i<filterList.size();i++){
if(filterList.get(i).getName().toUpperCase().contains(constraint)){
Player p = new Player(filterList.get(i).getName(),filterList.get(i).getImg());
filters.add(p);
}
}
results.count = filters.size();
results.values = filters;
}
else {
results.count = filterList.size();
results.values = filterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
players = (ArrayList<Player>) results.values;
notifyDataSetChanged();
}
}
}
Player.java
package com.example.lenovo.filterapp;
/**
* Created by LENOVO on 2/6/2016.
*/
public class Player {
private String name;
private int img;
public Player(String name, int img) {
this.name = name;
this.img = img;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:queryHint="search...." />
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/searchView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="0dp" />
</LinearLayout>
manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name="com.example.lenovo.filterapp.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.lenovo.filterapp.Lionel"
android:label="#string/title_activity_lionel"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="com.example.lenovo.filterapp.Christiano"
android:label="#string/title_activity_christiano"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="com.example.lenovo.filterapp.Neymar"
android:label="#string/title_activity_neymar"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
finding the reason behind my crash is really hard. What might be the problem? Thanks in advance
You need to disable the focus of the components in your custom list view.
android:focusable="false"
android:focusableInTouchMode="false"
A workaround is as I have done in my application - you can try to replace the onItemClickListener with the onItemTouchListener like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView);
//we need this to identify the gesture of the goalsRecyclerView touch
final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
lv.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
LinearLayout child = (LinearLayout) rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mGestureDetector.onTouchEvent(e))//only if clicked on an existing child and not swiping
{
Intent intent = new Intent(ThisActivity.this, OtherActivity.class);
startActivityForResult(intent, 1);
return true;//transfer the touch event to the recyclerView
}
return false;//ignore the event
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
This works just fine for my scenarios with customListViews
Do this on list click
String openClass = (String) lv.getItemAtPosition(position);
instead of
String openClass = (String) adapter.getItem(position);

Android: Can't get Checkbox OnClickListener to work in ListFragment

I've looked through a few posts, but can't get the checkbox to acknowledge clicks. I think I'm 90% there but falling over the last hurdle.
I have a ListFragment where each item has a CheckBox and a TextView. When users click on the TextView they're taken to a new fragment. But when they click the CheckBox I want the value to be ticked/unticked directly in the list.
Here's my code, kept it so that only classes relevant to the ListView are shown, let me know if you need to see others.
I did follow this guide but can't really understand why it's not working on my code: http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html
TaskListFragment.java
package com.laytonlabs.android.todotoday;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
public class TaskListFragment extends ListFragment {
ArrayList<Task> mTasks;
private boolean mSubtitleVisible;
private Callbacks mCallbacks;
private static final String TAG = "TaskListFragment";
private int touchPositionX;
public interface Callbacks {
void onTaskSelected(Task task);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks)activity;
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.crimes_title);
mTasks = TaskLab.get(getActivity()).getTasks();
TaskAdapter adapter = new TaskAdapter(mTasks);
setListAdapter(adapter);
setRetainInstance(true);
mSubtitleVisible = false;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible && showSubtitle != null) {
showSubtitle.setTitle(R.string.hide_subtitle);
}
}
#TargetApi(11)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
Task task = new Task();
TaskLab.get(getActivity()).addTaskToFirst(task);
((TaskAdapter)getListAdapter()).notifyDataSetChanged();
mCallbacks.onTaskSelected(task);
return true;
case R.id.menu_item_show_subtitle:
if (getActivity().getActionBar().getSubtitle() == null) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
mSubtitleVisible = true;
item.setTitle(R.string.hide_subtitle);
} else {
getActivity().getActionBar().setSubtitle(null);
mSubtitleVisible = false;
item.setTitle(R.string.show_subtitle);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.crime_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
TaskAdapter adapter = (TaskAdapter)getListAdapter();
Task task = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
TaskLab.get(getActivity()).deleteTask(task);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mSubtitleVisible) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
}
}
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
//Use floating context menus on Froyo and Gingerbread
registerForContextMenu(listView);
} else {
//Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.crime_list_item_context, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
TaskAdapter adapter = (TaskAdapter)getListAdapter();
TaskLab taskLab = TaskLab.get(getActivity());
for (int i = adapter.getCount() - 1; i >= 0; i--) {
if (getListView().isItemChecked(i)) {
taskLab.deleteTask(adapter.getItem(i));
}
}
mode.finish();
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
}
});
}
return v;
}
#Override
public void onResume() {
super.onResume();
((TaskAdapter)getListAdapter()).notifyDataSetChanged();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Task t = ((TaskAdapter)getListAdapter()).getItem(position);
mCallbacks.onTaskSelected(t);
}
private class TaskAdapter extends ArrayAdapter<Task> {
public TaskAdapter(ArrayList<Task> tasks) {
super(getActivity(), 0, tasks);
}
private class ViewHolder {
TextView titleTextView;
CheckBox completedCheckBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
//If we wern't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_task, null);
holder = new ViewHolder();
holder.titleTextView = (TextView)convertView.findViewById(R.id.task_list_item_titleTextView);
holder.completedCheckBox = (CheckBox)convertView.findViewById(R.id.task_list_item_completedCheckBox);
convertView.setTag(holder);
holder.completedCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task task = (Task) cb.getTag();
task.setCompleted(cb.isChecked());
Log.d(TAG, "Clicked on checkbox for: " + task.getmTitle());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
//Configure the view for this Task
Task t = getItem(position);
holder.titleTextView.setText(t.getmTitle());
holder.completedCheckBox.setChecked(t.isCompleted());
holder.completedCheckBox.setTag(t);
return convertView;
}
}
public void updateUI() {
((TaskAdapter)getListAdapter()).notifyDataSetChanged();
}
}
list_item_task.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/task_list_item_completedCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:enabled="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="4dp" />
<TextView
android:id="#+id/task_list_item_titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="Task title" />
</LinearLayout>
Thanks in Advance!
Your clicks are not getting thru, because ur CheckBox has
android:enabled="false"
Which prevents the onClickListener from firing.
Remove this line, and try again.
Also, I advise you to change width of TextView to wrap_content, and rather position the CheckBox to the right.
In your list_item_task.xml layout file, where the CheckBox and TextView are defined, you set to the TextView
android:layout_width="match_parent"
when it should be as in the tutorial
android:layout_width="wrap_content"
It is possible that the too wide text is intercepting the click event from the checkbox.

Cannot cast CheckableLayout and highlight selected items

I want a multiple selection on this GridView, but I've a casting problem. This is my code:
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivityTest extends ActionBarActivity {
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setMultiChoiceModeListener(new MultiChoiceModeListener());
gridView.setAdapter(new NumberAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int numero = position+1;
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.custom_toast_layout,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView selectedNumber = (TextView) layout.findViewById(R.id.selected_number);
selectedNumber.setText(""+numero);
Context context = getBaseContext();
String text = ""+numero;
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 600);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class CheckableLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
#SuppressWarnings("deprecation")
public void setChecked(boolean checked) {
mChecked = checked;
setBackgroundDrawable(checked ? getResources().getDrawable(
R.drawable.rounded_edittext_denim) : null);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
public class MultiChoiceModeListener implements GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return true;
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount + " items selected");
break;
}
}
}
public class NumberAdapter extends BaseAdapter {
private Context context;
public NumberAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return 60;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckableLayout checkableLayout;
TextView numberView;
if (convertView == null) {
numberView = new TextView(context);
numberView.setLayoutParams(new GridView.LayoutParams(110, 110));
numberView.setPadding(0, 0, 0, 0);
numberView.setTextColor(Color.WHITE);
numberView.setBackgroundResource(R.drawable.rounded_edittext_zaffiro);
numberView.setGravity(Gravity.CENTER);
numberView.setTextSize(25);
checkableLayout = new CheckableLayout(MainActivityTest.this);
checkableLayout.addView(numberView);
} else {
//ERROR AT THIS POINT
checkableLayout = (CheckableLayout) convertView;
numberView = (TextView) checkableLayout.getChildAt(0);
}
numberView.setText("" + (position + 1));
return numberView;
}
}
}
java.lang.ClassCastException: android.widget.TextView cannot be cast to kangel.customtest.MainActivityTest$CheckableLayout
Anyone can help me to highlight selected item. Where is the error in my code?
you are returning the wrong object, that's the reason why you are getting the ClassCastException. In your custom getView's change
return numberView;
with
return checkableLayout;

ListView Items aren't displaying on Main Activity

I'm a beginner in android development. I'm trying to send data from an ArrayList of Type Workout Item to the MainActivity using an Adapter, but I don't understand base adapters very well. Here is my code:
WorkoutActivity.java:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class WorkoutActivity extends Activity {
WorkoutItemAdapter workoutItemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
}
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1;
List<WorkoutItem> workoutsList = getDataForListView();
public WorkoutItem getWorkout(int position)
{
return workoutsList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.workout_item, parent, false);
}
TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);
WorkoutItem workout = workoutsList.get(position);
workoutNum.setText(workout.workoutNum);
workoutTime.setText(workout.time);
return convertView;
}
#Override
public int getCount() {
return workoutsList.size();
// TODO Auto-generated method stub
}
#Override
public WorkoutItem getItem(int position) {
// TODO Auto-generated method stub
return workoutsList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void addRow() {
rowCount++;
notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.workout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public List<WorkoutItem> getDataForListView()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for(int i = 0; i < (workoutsList.size() + 1); i++)
{
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i+1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
public void startAndStopTimer(View view)
{
long totalTime = 0;
Button startAndStop = (Button) findViewById(R.id.button1);
Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
if(startAndStop.getText().equals("Start"))
{
c.setBase(SystemClock.elapsedRealtime() + totalTime);
c.start();
startAndStop.setText("Pause");
}
else
{
totalTime = c.getBase() - SystemClock.elapsedRealtime();
c.stop();
startAndStop.setText("Start");
}
}
public void save(View view)
{
// create broadcast receiver saying ...saved.
// Add ArrayList value to arrayList
Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);
SharedPreferences timerSettings = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = timerSettings.edit();
editor.putString("Workout Time", timer.getText().toString());
editor.commit();
// go back to main activity.
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
startActivity(intent);
finish();
}
public void cancel(View view)
{
// go back to main activity
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
startActivity(intent);
finish();
}
}
OverviewActivity.java:
import edu.uark.csce.razorrunner.WorkoutActivity.WorkoutItemAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
public class OverviewActivity extends Activity{
WorkoutItemAdapter workoutAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
LoadPreferences();
LoadListView();
}
private void LoadListView() {
// TODO Auto-generated method stub
ListView workoutList = (ListView) findViewById(R.id.workout_list);
workoutList.setAdapter(workoutAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.overview, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String Name = sharedPreferences.getString("Name", "");
TextView textView = (TextView) findViewById(R.id.textView2);
textView.setText(Name);
}
public void openWorkoutActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
startActivity(intent);
finish();
}
public void openProfileActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
public void openHistoryActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
startActivity(intent);
finish();
}
}
activity_overview.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.uark.csce.razorrunner.OverviewActivity" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/profileButton"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="openProfileActivity"
android:text="Profile" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<ListView
android:id="#+id/workout_list"
android:layout_width="wrap_content"
android:layout_height="195dp"
android:layout_weight="0.19" >
</ListView>
<Button
android:id="#+id/startNewWorkout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:onClick="openWorkoutActivity"
android:text="Start New Workout!"
android:typeface="sans" />
</LinearLayout>
activity_workout.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:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.uark.csce.razorrunner.WorkoutActivity" >
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignRight="#+id/button1"
android:text="Cancel"
android:onClick="cancel" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/Button01"
android:text="Save"
android:onClick="save" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Button01"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginRight="22dp"
android:text="Start"
android:onClick="startAndStopTimer" />
<TextView
android:id="#+id/time_col"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:text="New Workout"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/time_col"
android:layout_marginTop="18dp"
android:text="Calories Burned"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="14dp"
android:text="Duration"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignRight="#+id/button1"
android:layout_toRightOf="#+id/button2"
android:ems="10"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge">
<requestFocus />
</TextView>
<Chronometer
android:id="#+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/TextView01"
android:layout_alignLeft="#+id/TextView1"
android:layout_alignRight="#+id/TextView1"
android:text="Chronometer" />
</RelativeLayout>
I'd like to show the workout number and duration for each list item every time I click Save, but currently all I get is a blank ListView every time I click Save. Any help and/or additional sources on this topic would be useful.
I hope two mistakes you made.
public List<WorkoutItem> getDataForListView()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for(int i = 0; i < (workoutsList.size() + 1); i++)
{
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i+1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
I guess you are trying to add data to list view. Since you are creating new List using
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
workoutsList.size() will return zero. your loop iterates till list size+1. (only one time )
then you need to pass the List from WorkoutActivity to OverviewActivity.
change WorkoutActivity insert following code
public class WorkoutActivity extends Activity {
WorkoutItemAdapter workoutItemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.workout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public List<WorkoutItem> getDataForListView() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for (int i = 0; i < (10+ 1); i++) {
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i + 1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
public void startAndStopTimer(View view) {
long totalTime = 0;
Button startAndStop = (Button) findViewById(R.id.button1);
Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
if (startAndStop.getText().equals("Start")) {
c.setBase(SystemClock.elapsedRealtime() + totalTime);
c.start();
startAndStop.setText("Pause");
} else {
totalTime = c.getBase() - SystemClock.elapsedRealtime();
c.stop();
startAndStop.setText("Start");
}
}
public void save(View view) {
// create broadcast receiver saying ...saved.
// Add ArrayList value to arrayList
Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);
SharedPreferences timerSettings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = timerSettings.edit();
editor.putString("Workout Time", timer.getText().toString());
editor.commit();
// go back to main activity.
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
intent.putStringArrayListExtra("stock_list", getDataForListView());
startActivity(intent);
finish();
}
public void cancel(View view) {
// go back to main activity
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
intent.putStringArrayListExtra("stock_list", getDataForListView());
startActivity(intent);
finish();
}
}
and OverviewActivity to this
public class OverviewActivity extends Activity{
List<WorkoutItem> workList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
Intent i = getIntent();
workList = i.getStringArrayListExtra("stock_list");
LoadPreferences();
LoadListView();
}
private void LoadListView() {
// TODO Auto-generated method stub
ListView workoutList = (ListView) findViewById(R.id.workout_list);
WorkoutItemAdapter workoutAdapter= new WorkoutItemAdapter(workList);
workoutList.setAdapter(workoutAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.overview, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String Name = sharedPreferences.getString("Name", "");
TextView textView = (TextView) findViewById(R.id.textView2);
textView.setText(Name);
}
public void openWorkoutActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
startActivity(intent);
finish();
}
public void openProfileActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
public void openHistoryActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
startActivity(intent);
finish();
}
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1;
List<WorkoutItem> workoutsList ;
public WorkoutItemAdapter( List<WorkoutItem> list) {
workoutsList=list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.workout_item, parent, false);
}
TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);
WorkoutItem workout = workoutsList.get(position);
workoutNum.setText(workout.workoutNum);
workoutTime.setText(workout.time);
return convertView;
}
#Override
public int getCount() {
return workoutsList.size();
// TODO Auto-generated method stub
}
#Override
public WorkoutItem getItem(int position) {
// TODO Auto-generated method stub
return workoutsList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void addRow() {
rowCount++;
notifyDataSetChanged();
}
}
}
try these code. I have not yet tried, hope will works fine.
So I assume OverviewActivity.java is your main Activity which in return opens WorkoutActivity ?
you haven't initialise workoutAdapter...only declared....
hence workoutAdapter is null....which means the size of adapter is 0 ...which means no rows for list view...
before setting the adapter to listview ..you must have to initialize workoutAdapter
i.e.
workoutAdapter=new WorkoutItemAdapter(getDataForListView());
create the adaper contructor and pass the list array
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1; //don't know about that
List<WorkoutItem> workoutsList;
public WorkoutItemAdapter(List<WorkoutItem> tmp)
{
this.workoutsList=tmp; //setting the list array to datamember of this adapter
}
In WorkOutItemAdapter List<WorkoutItem> workoutsList = getDataForListView();
// check the size of the list is zero or null
In WorkOutItemActivity you do like this
WorkoutItemAdapter workoutItemAdapter = new WorkoutItemAdapter();
ListView workoutList = (ListView) findViewById(R.id.workout_list);
workoutList.setAdapter(workoutAdapter);*

How to add a Button to my EmptyView?

Hi I'm trying to insert a Button into anEmptyView. The only thing I can seem to get to work is the EmptyText where a text value is displayed when the list is empty. This code works for just displaying a textview. How can I successfully add a button to the view?
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.text.format.DateFormat;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.robertrichardson.crimeproofassistant.R.string;
public class crimeListFragment extends ListFragment {
private ArrayList<crime> mcrime;
private boolean mSubtitleVisible;
public static final String TAG = "crimeListFragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.app_name);
mcrime = crimeLab.get(getActivity()).getcrime();
crimeAdapter adapter = new crimeAdapter(mcrime);
setListAdapter(adapter);
setRetainInstance(true);
mSubtitleVisible = false;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setEmptyText(getResources().getString(string.new_crime_attack_empty_desc));
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mSubtitleVisible) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
}
}
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Use floating point context menus on Froyer and Gingerbread
registerForContextMenu(listView);
} else {
// Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
// ActionMode.Callback methods
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.crime_list_item_context, menu);
return true;
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// required but not used in this implementation
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
crimeAdapter adapter = (crimeAdapter)getListAdapter();
crimeLab crimeLab = crimeLab.get(getActivity());
for (int i = adapter.getCount() - 1; i >= 0; i--) {
if (getListView().isItemChecked(i)) {
crimeLab.deletecrime(adapter.getItem(i));
}
}
mode.finish();
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
// Required, but not used in this implementation
}
public void onDestroyActionMode(ActionMode mode) {
}
});
}
return v;
}
public void onListItemClick(ListView l, View v, int position, long id) {
crime c = ((crimeAdapter)getListAdapter()).getItem(position);
// Start crime Activity
Intent i = new Intent(getActivity(), crimePagerActivity.class);
i.putExtra(crimeFragment.EXTRA_crime_ID, c.getId());
startActivity(i);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
((crimeAdapter)getListAdapter()).notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible && showSubtitle != null) {
showSubtitle.setTitle(R.string.hide_subtitle);
}
}
#TargetApi(11)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
crime crime = new crime();
crimeLab.get(getActivity()).addcrime(crime);
Intent i = new Intent(getActivity(), crimePagerActivity.class);
i.putExtra(crimeFragment.EXTRA_crime_ID, crime.getId());
startActivityForResult(i,0);
return true;
case R.id.menu_item_show_subtitle:
if (getActivity().getActionBar().getSubtitle() != null) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
mSubtitleVisible = true;
item.setTitle(R.string.hide_subtitle);
} else {
getActivity().getActionBar().setSubtitle(null);
mSubtitleVisible = false;
item.setTitle(R.string.show_subtitle);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.crime_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
crimeAdapter adapter = (crimeAdapter)getListAdapter();
crime crime = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
crimeLab.get(getActivity()).deletecrime(crime);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
private class crimeAdapter extends ArrayAdapter<crime> {
public crimeAdapter(ArrayList<crime> crime) {
super(getActivity(), 0, crime);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_crime, null);
}
// Enter the view of this crime Attack
crime c = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.crime_list_item_titleTextView);
titleTextView.setText(c.getTitle());
TextView dateTextView =
(TextView)convertView.findViewById(R.id.crime_list_item_dateTextView);
dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy hh : mm a", c.getDate()).toString());
CheckBox resolvedCheckBox =
(CheckBox)convertView.findViewById(R.id.crime_list_item_resolvedCheckBox);
resolvedCheckBox.setChecked(c.isResolved());
return convertView;
}
}
#Override
public void onResume() {
super.onResume();
((crimeAdapter)getListAdapter()).notifyDataSetChanged();
}
}
Here's my XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#f2f3f4"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#android:id/list"
android:background="#f2f3f4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
<linearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f3f4"
android:orientation="vertical"
>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="#string/new__empty_desc"
/>
<Button
android:id="#+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="#string/new_attack_empty"
/>
</linearLayout>
</FrameLayout>
public class MainActivity extends Activity {
private CustomBaseAdapter customBaseAdapter;
private ListView lv;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout fl = new FrameLayout(this);
btn = new Button(this);
btn.setText("Hit me");
lv = new ListView(this);
customBaseAdapter = new CustomBaseAdapter(this);
lv.setAdapter(customBaseAdapter);
fl.addView(lv);
fl.addView(btn);
setContentView(fl);
handleVisbility();
}
public void handleVisbility() {
if (customBaseAdapter.getCount() == 0) {
lv.setVisibility(View.GONE);
btn.setVisibility(View.VISIBLE);
} else {
lv.setVisibility(View.VISIBLE);
btn.setVisibility(View.GONE);
}
}
public class CustomBaseAdapter extends BaseAdapter {
private Context context;
View superView;
public CustomBaseAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int arg0) {
return new Object();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
FrameLayout fl = new FrameLayout(context);
Button btn = new Button(context);
btn.setText("Hello, im a Button");
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Yay hit me again", Toast.LENGTH_LONG).show();
}
});
fl.addView(btn);
return fl;
}
}
}
Ok, this is kinda what you want to do here. It shows a ListView, if there is an Item in the List, and will show the Button if the List is Empty. Only thing you have to do, is to call handleVisbility() everytime you make a change to the ListViews content. Especially after you add something to the List.
The default implementation of the ListFragment involves setting up a textView as the empty view for the list.
http://developer.android.com/reference/android/app/ListFragment.html#setEmptyText(java.lang.CharSequence)
You can change this by extending a Fragment and create your own ListView inside it. you can use the code from the ListFragment if you like some of the things it offers.
As an alternative you can try to do getListView().setEmptyView() and set up the view that you need. Again see how they do it in the code in the ListFragment and reproduce it with a different View (instead of TextView use a Button or ImageButton whatever you need)
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/app/ListFragment.java

Categories

Resources