Google Glass - Creating an options menu, nothing happens when item is clicked - android

I am creating an app for Glass that displays a list of saved items (RememberItem). Each item has its card, and when you tap it, a menu appears with the following options: Get directions (launch google nav to the location of saved item), delete (remove the item from the list).
However, nothing happens when we tap on the menu options.
Here's the code:
package com.adrianavecc.findit;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.speech.RecognizerIntent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.adrianavecc.findit.adapter.ScrollAdapter;
import com.adrianavecc.findit.db.SqlHelper;
import com.adrianavecc.findit.domain.RememberItem;
import com.adrianavecc.findit.util.RememberUtils;
import com.google.android.glass.app.Card;
import com.google.android.glass.app.Card.ImageLayout;
import com.google.android.glass.widget.CardScrollView;
public class Find extends Activity implements Callback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> voiceResults = getIntent().getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
String tag= voiceResults.get(0);
RememberItem item=SqlHelper.getInstance(this).findRememberItem(tag);
if(item!=null){
List<RememberItem> items=new ArrayList<RememberItem>();
items.add(item);
displayRememberItems(items);
} else{
if(RememberUtils.EVERY_THING.equalsIgnoreCase(tag)){
List<RememberItem> items=SqlHelper.getInstance(this).findAllRememberItem();
displayRememberItems(items);
}
else{
displayFailureView();
}
}
}
private void displayFailureView() {
Card fail = new Card(this);
fail.setText(R.string.storefailhead);
fail.setFootnote(R.string.storefailfoot);
fail.setImageLayout(Card.ImageLayout.FULL);
fail.addImage(R.drawable.storefailbackground);
View failView = fail.getView();
setContentView(failView);
}
private Card createCardOfRememberItem(RememberItem item) {
Card card = new Card(this);
card.setText(item.getTag());
card.setFootnote(String.format("%tc", item.getAddedDate()));
card.setImageLayout(ImageLayout.FULL);
card.addImage(BitmapFactory.decodeFile(item.getImagePath()));
return card;
}
private void launchGoogleMap(RememberItem item) {
Location location=item.getLocation();
Intent intent=RememberUtils.getGeoIntentFromLocation(location);
Find.this.startActivity(intent);
}
private void displayRememberItems(final List<RememberItem> items) {
List<Card> mCards = new ArrayList<Card>();
for(RememberItem item: items){
Card card=createCardOfRememberItem(item);
mCards.add(card);
}
CardScrollView mCardScrollView = new CardScrollView(this);
final ScrollAdapter adapter = new ScrollAdapter(mCards);
mCardScrollView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Card card=(Card)adapter.getItem(arg2);
RememberItem item=SqlHelper.getInstance(getApplicationContext()).findRememberItem(card.getText().toString());
openOptionsMenu();
}
});
mCardScrollView.setAdapter(adapter);
mCardScrollView.activate();
setContentView(mCardScrollView);
}
private void showSucessDeleteCard(RememberItem item){
Card card = new Card(this);
card.setText(R.string.object_delete);
card.setImageLayout(ImageLayout.FULL);
card.addImage(R.drawable.finditlogobg);
setContentView(card.getView());
Handler handler=new Handler(this);
handler.sendEmptyMessageDelayed(0, 3000);
}
#Override
public boolean handleMessage(Message msg) {
finish();
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.saveditemmenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuitem, RememberItem item) {
switch (menuitem.getItemId()) {
case R.id.menu_getdirections:
launchGoogleMap(item);
return true;
case R.id.menu_delete:
SqlHelper.getInstance(getApplication()).deleteRememberItem(item);
showSucessDeleteCard(item);
return true;
default:
return super.onOptionsItemSelected(menuitem);
}
}
}

You must override public boolean onOptionsItemSelected(MenuItem item) which is the event and then call onOptionsItemSelected(MenuItem menuitem, RememberItem item) from that method.

Maybe it is too late. Can you try this please
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
Log.d("TOUCH","DPAD_CENTER");
this.openOptionsMenu();
return true;
}
return super.onKeyDown(keyCode, event);
}

Related

Checkbox,ImageView and GridView

I have a GridView where each grid item consists of an ImageView and a Checkbox. Now, when I select one checkbox, lets say number 5, another checkbox like number 12 gets selected automatically. Similar for deselection.
I cannot figure out why this is happening. Any help will be appreciated.
package com.example.vasylpaliy.mediaview;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.adapter.ImageAdapter;
import java.io.File;
import java.util.ArrayList;
public class ImageSelecter extends AppCompatActivity
implements AdapterView.OnItemClickListener {
private GridView view;
private boolean colNum=false;
private ArrayList<String> imagePaths;
private final static int IMAGE_PATH_REQUEST=1;
private ImageAdapter imageAdapter;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.image_selector);
view=(GridView)findViewById(R.id.gridView);
imagePaths=getIntent().getStringArrayListExtra("images");
getSupportActionBar().setHomeButtonEnabled(true);
if(imagePaths!=null){
setAdapter(false);
setMultiChoiceMode();
view.setOnItemClickListener(this);
}
setResult(RESULT_CANCELED);
}
private void setMultiChoiceMode(){
view.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
view.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
private ArrayList<String> imageItems=new ArrayList<String>();
private boolean isChecked=false;
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
imageItems.add(imagePaths.get(position));
mode.setTitle("Selected:"+Integer.toString(view.getCheckedItemCount()));
if(!isChecked)
imageAdapter.setCheckMark();
//imageAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.multiple_images, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId())
{
case R.id.multiple_image_select_all:
{
imageItems=imagePaths;
for(int i=0;i<imageItems.size();i++)
view.setItemChecked(i,true);
break;
}
case R.id.multiple_image_deleting:
{
if(imageItems!=null)
deleteItems(imageItems);
imageItems=null;
mode.setTitle("");
break;
}
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
Toast.makeText(getApplicationContext(),"Destroy",Toast.LENGTH_SHORT).show();
setAdapter(false);
//mode.finish();
}
});
}
private void setAdapter(boolean checked){
imageAdapter=new ImageAdapter(this,imagePaths,
R.layout.grid_item,R.id.grid_item_image,checked);
view.setAdapter(imageAdapter);
}
private void deleteItems(ArrayList<String> imageItems){
boolean isDeletingFolder=imagePaths.size()==imageItems.size();
for(String image:imageItems){
File file=new File(image);
file.delete();
imagePaths.remove(image);
}
setResult(RESULT_OK);
if(isDeletingFolder)
finish();
}
#Override
public void onItemClick(AdapterView<?> parent,View view,
int position, long id){
Toast.makeText(this, Integer.toString(position),Toast.LENGTH_LONG).show();
Intent intent=new Intent(this,ImageSlider.class);
intent.putStringArrayListExtra("images", imagePaths);
intent.putExtra("position", position);
startActivityForResult(intent, IMAGE_PATH_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==IMAGE_PATH_REQUEST){
if(resultCode==RESULT_OK){
imagePaths=data.getStringArrayListExtra("images");
setResult(RESULT_OK);
setAdapter(false);
setMultiChoiceMode();
}
else if(resultCode==RESULT_CANCELED){
setResult(RESULT_OK);
finish();
}
}
}
and here is my adapter
package com.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import com.example.vasylpaliy.mediaview.R;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.ArrayList;
public class ImageAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private Picasso mPicasso;
private int typeLayout;
private int idImage;
private boolean checked;
public ImageAdapter(Context context, ArrayList<String> imagesPaths,
int typeLayout, int idImage, boolean checked) {
super(context, typeLayout,imagesPaths);
mInflater = LayoutInflater.from(context);
mPicasso = Picasso.with(context);
this.typeLayout=typeLayout;
this.idImage=idImage;
this.checked=checked;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = mInflater.inflate(typeLayout, parent, false);
}
ImageView imageView = (ImageView) view.findViewById(idImage);
mPicasso.load(new File(getItem(position))).
resizeDimen(R.dimen.image_width, R.dimen.image_size).
centerCrop().into(imageView);
if(checked){
final CheckBox checkMark=(CheckBox)view.findViewById(R.id.checkImageMark);
checkMark.setVisibility(View.VISIBLE);
// checkMark.setButtonDrawable(R.drawable.checked24);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkMark.setButtonDrawable(!checkMark.isChecked() ? R.drawable.checked24_1 : R.drawable.checked24);
checkMark.setChecked(!checkMark.isChecked());
}
});
}
return view;
}
public void setCheckMark(){
checked=!checked;
}
}`
adapter view reuse it's views when scrolling
so you need a way to save state of the checked items in the list and also clear the views when reusing
so handle both cases checked and unchecked
if(checked){
checkMark.setVisibility(View.VISIBLE);
} else {
checkMark.setVisibility(View.GONE);
}
Also
i don't think checked variable should be global it should be specfic for each item in the list
It happen because GridView cache views and OnClickListener are not cleared.
You need handle false case
For example:
final CheckBox checkMark=(CheckBox)view.findViewById(R.id.checkImageMark);
if(checked){
checkMark.setVisibility(View.VISIBLE);
// checkMark.setButtonDrawable(R.drawable.checked24);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkMark.setButtonDrawable(!checkMark.isChecked() ? R.drawable.checked24_1 : R.drawable.checked24);
checkMark.setChecked(!checkMark.isChecked());
}
});
} else {
checkMark.setVisibility(View.GONE);
imageView.setOnClickListener(null);
}

How I can remove items of ListView?

The apk is a memo pad or something like that. First you can put the title and then the note and if you press the button "Save" the note is saved and it saves in database. And if you press the button "Notes", you can view a list with all notes saved in database and you can select all notes and in the top of screen, you can read how many notes are selected. Ok, it's fine but I need remove notes when the are selected and I press the button with bin icon in the top menu.
The code:
package com.example.u2tarea3;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AnotacionesOpenHelperSingleton extends SQLiteOpenHelper {
private static AnotacionesOpenHelperSingleton instancia = null;
private Context mCtx;
public static AnotacionesOpenHelperSingleton getInstance(Context ctx){
if(instancia == null){
instancia = new AnotacionesOpenHelperSingleton(ctx);
}
return instancia;
}
private AnotacionesOpenHelperSingleton(Context ctx) {
super(ctx,"anotaciones",null,2);
}
#Override
public void onCreate(SQLiteDatabase bd) {
StringBuilder sql = new StringBuilder();
sql.append("create table IF NOT EXISTS anotaciones (");
sql.append("_id integer primary key autoincrement,");
sql.append("texto text not null,");
sql.append("fecha text not null)");
bd.execSQL(sql.toString());
}
#Override
public void onUpgrade(SQLiteDatabase bd, int oldVersion, int newVersion) {
//bd.execSQL("drop table anotaciones");
bd.execSQL("ALTER TABLE anotaciones ADD titulo text");
bd.execSQL("UPDATE anotaciones SET titulo = 'sin titulo' WHERE titulo is NULL");
onCreate(bd);
}
}
package com.example.u2tarea3;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText editText;
EditText editTitulo;
Button btnGuardar;
Button btnAnotaciones;
SQLiteDatabase bd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton.getInstance(this);
bd = openHelperSingleton.getWritableDatabase();
editText = (EditText)findViewById(R.id.editText);
editTitulo = (EditText) findViewById(R.id.editTitulo);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnGuardar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
ContentValues valores = new ContentValues();
valores.put("texto", editText.getText().toString());
valores.put("fecha", sdf.format(c.getTime()));
valores.put("titulo", editTitulo.getText().toString());
bd.insert("anotaciones", null, valores);
editText.setText("");
}
});
btnAnotaciones = (Button) findViewById(R.id.btnAnotaciones);
btnAnotaciones.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ListAnotaciones.class);
startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
}
package com.example.u2tarea3;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ListAnotaciones extends ListActivity {
SQLiteDatabase bd;
Cursor cursor;
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton
.getInstance(this);
int cont = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelperSingleton.getReadableDatabase();
cursor = bd.rawQuery("SELECT * FROM anotaciones", null);
try {
String[] from = { "fecha", "titulo" };
int[] to = { R.id.anotacionesFecha, R.id.anotacionesTitulo };
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.anotacion, cursor, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
MenuInflater inflater = arg0.getMenuInflater();
inflater.inflate(R.menu.anotaciones, arg1);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch(arg1.getItemId()){
case R.id.delete_id:
//arg0.finish();
default:
break;
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
int seleccionados = getListView()
.getCheckedItemCount();
switch (seleccionados) {
case 1:
mode.setTitle("1 nota seleccionada");
break;
default:
mode.setTitle("" + seleccionados
+ " notas seleccionadas");
break;
}
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}
}
You'll need to remove the note from the database and the ListView, and then call ListViewAdapter.notifyDataSetChanged()
To delete from the datasource have a method in the class that deals with the datasource:
/**
* Delete a note given an id.
* #param id Key used to identify a note to delete.
*/
public void deleteNote(long id) {
System.out.println("Note deleted with id: " + id);
database.delete(ListOpenHelper.TABLE_MEMOS,
ListOpenHelper.ID + " = " + id,
null);
}
To refresh the ListView you could simply clear and re-add all the Views via the ListViewAdapter:
// Refresh adapter view with new data
ListAdapter.clear();
ListAdapter.addAll(dataSource.getAllNotes());
ListAdapter.notifyDataSetChanged();
Alternatively remove only a single element from the ListViewAdapter and call notifyDataSetChanged();.

How to return list item selected to parent activity - android

I'm learning android development. And I trying to do the following:
An wellcome activity, with a TextView with the following text: "Please Select"
This Textview, has an OnClick Listener setted.
My intent is, when the user click on this textview, one new activity with a listview must be opened.
This listview cointains some values like: Country 1, Country 2, Country 3 and so on;
So, when the user select one value, this value must be returned to the parent activity.
In my parent activity I have the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
countrySamples = (TextView)findViewById(R.id.countrySamples);
countrySamples.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListCountrySelectedFragment whatKindOjectIsThis = new ListCountrySelectedFragment();
whatKindOjectIsThis.setListCountrySelectedActivityDelegate(new ListCountrySelectedFragment.ListCountrySelectedActivityDelegate() {
#Override
public void selectCountry(String name) {
selectItem(name);
}
});
}
});
}
[...]
public void selectItem(String name) {
int index = valuesArray.indexOf(name);
if (index != -1) {
countryButton.setText(name);
}
}
And I've created an blank fragment with a list.
And added the following code:
public static interface ListCountrySelectedActivityDelegate {
public abstract void selectCountry(String name);
}
private ListCountrySelectedActivityDelegate delegate;
[...]
But, my fragment is never started.. The true is.. I have to create a Fragment to this? Or, must by an activity? Or I'm totally wrong?
Thanks
Edited (complete code):
Login Activity:
package com.testenum_13;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.testenum_13.R;
import com.testenum_13.adapters.CountryAdapter;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
public class Login extends ActionBarActivity {
TextView countryButton;
private EditText codeField;
private int countryState = 0;
private ArrayList<String> countriesArray = new ArrayList<String>();
private HashMap<String, String> countriesMap = new HashMap<String, String>();
private boolean ignoreOnTextChange = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
countryButton = (TextView)findViewById(R.id.countryButton);
countryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(Login.this, CountrySelected.class);
CountrySelected fragment = new CountrySelected();
fragment.setCountrySelectActivityDelegate (new CountrySelected.CountrySelectActivityDelegate() {
#Override
public void countryWSelected(String name) {
selectCountry(name);
}
});
//startActivity(intent);
}
});
}
#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_login, 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 void selectCountry(String name) {
int index = countriesArray.indexOf(name);
if (index != -1) {
ignoreOnTextChange = true;
codeField.setText(countriesMap.get(name));
countryButton.setText(name);
countryState = 0;
}
}
}
Country Activity:
package com.testenum_13;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.internal.widget.ActionBarOverlayLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.testenum_13.adapters.CountryAdapter;
import com.testenum_13.adapters.CountryAdapter.Country;
import java.util.List;
public class CountrySelected extends FragmentActivity {
public static interface CountrySelectActivityDelegate {
public abstract void countryWSelected(String name);
}
private CountryAdapter listViewAdapter;
private CountrySelectActivityDelegate delegate;
ListView countryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_selected);
countryList = (ListView)findViewById(R.id.countryList);
listViewAdapter = new CountryAdapter(getBaseContext());
countryList.setAdapter(listViewAdapter);
countryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Country country = null;
int section = listViewAdapter.getSectionForPosition(position);
int row = listViewAdapter.getPositionInSectionForPosition(position);
if (row < 0 || section < 0) {
return;
}
country = listViewAdapter.getItem(section, row);
if (position < 0) {
return;
}
if (country != null && delegate != null)
{
delegate.countryWSelected(country.name);
}
finish();
}
});
}
public void setCountrySelectActivityDelegate(CountrySelectActivityDelegate delegate) {
this.delegate = delegate;
}
#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_country_selected, 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);
}
}
Thanks
You could use startActivityForResult(Intent, int) in the parent Activity and override onActivityResult() in the child activity. See this tutorial for more details on how to implent this pattern.

Android listview item.setSelected() cannot keep it highlighted when showing contextual action mode

I am studying how to use the contextual action mode according to the official document at http://developer.android.com/guide/topics/ui/menus.html#CAB
However, everything works fine except for that the selected item cannot keep highlighted as expected(am I supposed to?) when I show the contextual action mode.
I tried to set the list selector with selective drawables, set the item view background with selective drawables but all ended in vain.
Could anybody help me out?
My code is listed below:
import com.robin.huangwei.omnigif.content.GifStore;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Cursor>, OnItemLongClickListener{
private static final int LOADER_ID_GIFIMAGES = 0;
private SimpleCursorAdapter mAdapter;
private ListView mListView;
private ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportLoaderManager().initLoader(LOADER_ID_GIFIMAGES, null, this);
String[] from = new String[] {GifStore.GifImages.Media._ID, GifStore.GifImages.Media.DISPLAY_NAME};
int[] to = new int[] {R.id.item_icon, R.id.item_name};
mAdapter = new SimpleCursorAdapter(this, R.layout.icon_text_item, null, from, to, 0);
mListView = (ListView) findViewById(R.id.listview);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mListView.setAdapter(mAdapter);
mListView.setOnItemLongClickListener(this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME};
CursorLoader cursorLoader = new CursorLoader(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
mAdapter.swapCursor(c);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
return false;
}
mActionMode = startSupportActionMode(mActionModeCallback);
view.setSelected(true);
mListView.setDrawSelectorOnTop(true);
return true;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
/**
* Called each time the action mode is shown. Always called after
* onCreateActionMode, but may be called multiple times if the mode is invalidated.
*/
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
return false;
}
/*
* // Called when the user exits the action mode
*/
#Override
public void onDestroyActionMode(ActionMode arg0) {
mActionMode = null;
}
/*
* Called when the action mode is created; startActionMode() was called
*/
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_list_item_context, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_list_item_context_edit:
break;
case R.id.menu_list_item_context_star_unstar:
break;
case R.id.menu_list_item_context_delete:
break;
default:
return false;
}
mode.finish();
return true;
}
};
}

Android - checked perform action

As I'm new to android, My problem is I'm Developing an application I want to increment/decrement the numbers by clicking on the buttons in the home page,but first of all it should check for in the settings menu the check box is checked,if it is checked then only to perform the actions...
MainActivity.java
package com.example.sanple;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public Button incre;
public Button dec;
public TextView nub;
public static int count = 0;
public String string;
/*
* #Override protected void onStart() { super.onStart();
*
* Bundle bundle = getIntent().getExtras(); if (bundle != null) { if
* (bundle.getBoolean("checked")) { MainActivity activity = new
* MainActivity(); activity.addListenerOnCheckbox(); } else {
* Toast.makeText(getApplicationContext(), "try to check the checkbox",
* Toast.LENGTH_SHORT).show(); }
*
* } }
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
addListenerOnCheckbox();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
void addListenerOnCheckbox() {
incre = (Button) findViewById(R.id.increment);
dec = (Button) findViewById(R.id.decrement);
nub = (TextView) findViewById(R.id.brakecounter);
incre.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("src", "button clciked");
count++;
string = Integer.toString(count);
nub.setText(string);
}
});
dec.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("src", "button clciked");
count--;
string = Integer.toString(count);
nub.setText(string);
}
});
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keycode = event.getKeyCode();
switch (keycode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_UP) {
int i = count++;
if (i > 10) {
Toast.makeText(getApplicationContext(),
"applying too many times brake", Toast.LENGTH_SHORT)
.show();
}
string = Integer.toString(count);
nub.setText(string);
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
count--;
string = Integer.toString(count);
nub.setText(string);
}
default:
break;
}
return super.dispatchKeyEvent(event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater inflater = new MenuInflater(getApplicationContext());
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent startActivity = new Intent(this, Settings.class);
startActivity(startActivity);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
Settings.java
package com.example.sanple;
import android.R.color;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class Settings extends Activity {
public TextView view;
public CheckBox box;
public Button button;
// KeyEvent KeyEvent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
view = (TextView) findViewById(R.id.enable_counter);
box = (CheckBox) findViewById(R.id.checkBox1);
box.setBackgroundColor(color.black);
button = (Button) findViewById(R.id.save);
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
/*//here we r setting checked true
box.setChecked(true);
Intent intent = new Intent();
intent.putExtra("Checked", true);*/
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
}
Check Box xml..
activity_settings.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"
tools:context=".Settings" >
<TextView
android:id="#+id/enable_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="51dp"
android:layout_marginTop="34dp"
android:text="enable_counter"
android:textColor="#f00" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/enable_counter"
android:layout_alignBottom="#+id/enable_counter"
android:layout_alignParentRight="true"
android:layout_marginRight="39dp" />
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/checkBox1"
android:layout_marginBottom="64dp"
android:text="save" />
</RelativeLayout>
Do this, in your button click event code :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent startActivity = new Intent(this, Settings.class);
startActivityForResult(startActivity);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
In settings do this :
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Intent intent = getIntent();
if(isChecked)
intent.putExtra("Checked", true);
else
intent.putExtra("Checked",false);
setResult(i,100);
}
//put this in main activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 100) {
boolean val = data.getBooleanExtra("checked",false);
if(val==true)
//allow to increment decrement
else
//not
}
}
}

Categories

Resources