How to add a Button to my EmptyView? - java

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

Related

Call another activity from childrow, expandable listview, filter

I would like to make an expandable list On clicking on an option take me to another activity. At the moment I only managed to make a message appear. I have only a few childrow, but I want to add more and they all take me to different activities
MainActivity.java
package com.example.gerardoalberto.lmx;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SearchView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private SearchManager searchManager;
private android.widget.SearchView searchView;
private MyExpandableListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<ParentRow> parentList = new ArrayList<ParentRow>();
private ArrayList<ParentRow> showTheseParentList = new ArrayList<ParentRow>();
private MenuItem searchItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
parentList = new ArrayList<ParentRow>();
showTheseParentList = new ArrayList<ParentRow>();
//The app will crash if display list is not called here.
displayList();
//This expands the list of continents.
expandAll();
}
private void loadData() {
ArrayList<ChildRow> childRows = new ArrayList<ChildRow>();
ParentRow parentRow = null;
childRows.add(new ChildRow(R.mipmap.generic_icon,"Charlie."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"James."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Carlos."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Alphonse."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Amelia."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Olivia."));
parentRow = new ParentRow("Names", childRows);
parentList.add(parentRow);
childRows = new ArrayList<ChildRow>();
childRows.add(new ChildRow(R.mipmap.generic_icon,"Arcane"));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Fire."));
parentRow = new ParentRow("Magic", childRows);
parentList.add(parentRow);
childRows = new ArrayList<ChildRow>();
childRows.add(new ChildRow(R.mipmap.generic_icon,"red"));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Yellow."));
parentRow = new ParentRow("Color", childRows);
parentList.add(parentRow);
}
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i=0; i<count; i++) {
myList.expandGroup(i);
}
}
private void displayList() {
loadData();
myList = (ExpandableListView) findViewById(R.id.expandableListView_search);
listAdapter = new MyExpandableListAdapter(MainActivity.this, parentList);
myList.setAdapter(listAdapter);
}
#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);
searchItem = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setOnCloseListener(this);
searchView.requestFocus();
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);
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
listAdapter.filterData(newText);
return false;
}
}
MyExpandableListAdapter.java
package com.example.gerardoalberto.lmx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by GerardoAlberto on 10/04/2016.
*/
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<ParentRow> parentRowList;
private ArrayList<ParentRow> originalList;
public MyExpandableListAdapter(Context context, ArrayList<ParentRow>originalList) {
this.context = context;
this.parentRowList = new ArrayList<>();
this.parentRowList.addAll(originalList);
this.originalList = new ArrayList<>();
this.originalList.addAll(originalList);
}
#Override
public int getGroupCount() {
return parentRowList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return parentRowList.get(groupPosition).getChildList().size();
}
#Override
public Object getGroup(int groupPosition) {
return parentRowList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return parentRowList.get(groupPosition).getChildList().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
ParentRow parentRow = (ParentRow) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.parent_row, null);
}
TextView heading = (TextView) convertView.findViewById(R.id.parent_text);
heading.setText(parentRow.getName().trim());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildRow childRow = (ChildRow) getChild(groupPosition, childPosition);
if(convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_row, null);
}
ImageView childIcon = (ImageView) convertView.findViewById(R.id.child_icon);
childIcon.setImageResource(R.mipmap.generic_icon);
final TextView childText = (TextView) convertView.findViewById(R.id.child_text);
childText.setText(childRow.getText().trim());
final View finalConvertView = convertView;
childText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(finalConvertView.getContext(), childText.getText(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
parentRowList.clear();
if (query.isEmpty()) {
parentRowList.addAll(originalList);
}
else {
for (ParentRow parentRow : originalList) {
ArrayList<ChildRow> childList = parentRow.getChildList();
ArrayList<ChildRow> newList = new ArrayList <ChildRow>();
for (ChildRow childRow: childList) {
if (childRow.getText().toLowerCase().contains(query)){
newList.add(childRow);
}
} //end for (childRow childRow: childList)
if (newList.size() > 0) {
ParentRow nParentRow = new ParentRow(parentRow.getName(),newList);
parentRowList.add(nParentRow);
}
} //end for (ParentRow parentRow : originalList)
} //end else
notifyDataSetChanged();
}
}

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;

How to inflate views programmatically in vertical order

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.

How to stop music background when specific image is reached?

I have music background in my app.. and want to stop the music when user reaches the last image in my app. If possible, I would like to make the last image to be name as "last" so that it will be better for code and when it recognize that image name "last" is reached it should be able to stop the music ...or it will be great if the music stops smoothly when last image in my app is reached by viewer..Any idea on how to do that ?
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
}
}
Imageadapter.java
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private final int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Add an OnPageChangeListener to your viewPager and check if the current image is the last one:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos==adapter.getCount()-1) {
oursong.stop();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});

Categories

Resources