I have a GridView with an ArrayAdapter and I'd like to detect the context item selection and show a "Delete" option for deleting the object selected. I fill the grid with imageviews correctly only need the detect the delete petition. My Code:
ArrayList<MyClass> array;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.maingrid);
array=Manager.getMyArray();
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new mArrayAdapter(this,array) );
registerForContextMenu(gridview);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(0, DELETE_ID, 0 , R.string.delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
return true;
}
return super.onContextItemSelected(item);
}
How can I guess whats the element of the array I have to remove? Thanks
In onContextItemSelected try this:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
you can get the selected item like this:
youradapter.getItem((int)info.id))
override the getItem() function in the adapter to return the selected item..
Related
I am a fairly novice android programmer and I need some help in regards to the use of a List fragmnet.
To begin:
I currently have three main components in my simple To-do List application.
The first is a Main activity that impliments a custom method I made that simply updates the arraylist through the array Adapepter I have made within it.
public class ToDoListActivity extends ActionBarActivity implements OnNewItemAddedListener{public void newItemAdded(String newItem)
{
todoItems.add(newItem);
arrayAdapter.notifyDataSetChanged();
}
public ArrayAdapter<String> arrayAdapter;
public ArrayList<String> todoItems;
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Inflate the root view
setContentView(R.layout.to_do_list_activity);
//Get references to the fragments
FragmentManager fragmentManager = getFragmentManager();
ToDoListFragment toDoListFragment = (ToDoListFragment)
fragmentManager.findFragmentById(R.id.ToDoListFragment);
//Create the array list of to do items
todoItems = new ArrayList<>();
//Create the array adapter to bind the array to the listView
arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, todoItems);
//Bind the array adapter to the listView
toDoListFragment.setListAdapter(arrayAdapter);
}
#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_to_do_list, 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();
//no inspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I Also have an edit text fragment that handles the input of text that would be the To-do items. The newItem variable that is fed through the onNewItemListner() method is populated using my edit text fragment.
`public class EditTextFragment extends Fragment{
//This variable stores a reference to the parent ToDoListActivity that implements
//this interface.
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//set the key listener on the edit text view on the UI. This handles the taps on the
//Edit text box on the UI
//inflate the view from the XML file
View view = inflater.inflate(R.layout.edit_text_fragment, container, false);
//Create the edit text variable where the reference to the UI XML file is
final EditText myEditText = (EditText)view.findViewById(R.id.myEditText);
//Set a key listener on the edit text field
myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String newItem = myEditText.getText().toString();
ToDoListActivity onItemAddedListener = new ToDoListActivity();
onItemAddedListener.newItemAdded(newItem);
myEditText.setText("");
return true;
}
}
return false;
}
});
return view;
}
public void onAttach(ToDoListActivity activity)
{
super.onAttach(activity);
}
}`
Finally I have a List fragment.
public class ToDoListFragment extends ListFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
//Inflate the XML UI component for the
View view = inflater.inflate(R.layout.to_do_list_fragment, container, false);
return view;
}
public void onAttach(ToDoListActivity activity)
{
super.onAttach(activity);
}
}
Now the problem I am running into is a null point exception. on the todoitems (arraylist) and the arrayAdapeter. They are for whatever reason not being instantiated. SO I can't pass any strings from my edit text field to them without crashing the app. I need to get them working and I would also like to use the list fragment to do so. Any help would be greatly appriciated. Any more information can be provided if needed.
Thank you.
Probably your edit text fragment have no access to the ArrayList or ArrayAdapter. I can't really tell without seeing its code.
As I see you have your fragments embedded in activity's layout and accessing them by ID.
The fragments are useful if you want to have parts of your UI dynamically loaded/unloaded. If you are planning to have just ListView and edit text on the screen then probably you can do it without fragments. It would be much easier. Just put a regular ListView and EditText in your activity's layout.
Actually the ListFragment is a Fragment that hosts a ListView.
i already created a navigation drawer bar with a menu but i want to highlight and disable the selected item on the menu bar when i check the drawer bar.
how can i do that ?
also i did not see the click animation when i click the item on the menu
please help
Thanks.
this is the code i used
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
if(child!=null && mGestureDetector.onTouchEvent(motionEvent)){
Drawer.closeDrawers();
Toast.makeText(MainActivity.this, "The Item Clicked is: " + recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();
int pos = recyclerView.getChildPosition(child);
if(pos== 1){
Intent intent = new Intent(getApplicationContext(),About.class);
startActivity(intent);
}
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
RecyclerView does not handle item selection or states like a ListView does. Instead you have to handle this manually in your view holder.
The first thing you can do is declare your item view as clickable, in your `ViewHolder constructor :
public ViewHolder(View itemView) {
super(itemView);
// Make this view clickable
itemView.setClickable(true);
// ...
}
http://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/
example to what kind of problem I am running into.
Let say I have 6 elements in a listview all in order from left to right [1,2,3,51,4,5].
When I search for 5 it displays "51" and "5". When I click on "51" it opens up "1". The problem is that the filtered list overlaps the listview that displays all the elements. I was wondering how I can fix this issue. I am using v7.widget.SearchView
#Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.recipe_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.search_recipe).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
lv.clearTextFilter();
} else {
lv.setFilterText(newText.toString());
}
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
I think that you make mistake in onItemClick(AdapterView<?> parent, View view, int position, long id) method. You take data by position from data list. The "position" is a position of clicked item on list. So if you filtered your list and click on first item the value of position will be "1". You have to take value from adapter which is corresponding to clicked position. You should take item from adapter like is shown in code below:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
...
String data = ((ExerciseDAO)parent.getAdapter().getItem(position)).getTitle() ;
...
}
});
If you have questions - just ask.
I am working with ContextMenu on my ListView. The problem I'm facing is I'm not getting ContextMenu on item that is already selected in ListView since it is not touchable at all.
call this inside onCreate():
registerForContextMenu(lv);
And to access the selected item during long click:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if (v.getId() == R.id.lv) {
ListView lv = (ListView) v;
AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
YourObject obj = (YourObject) lv.getItemAtPosition(acmi.position);
menu.add("One");
menu.add("Two");
menu.add("Three");
menu.add(obj.name);
}
}
Resolved!
What I did is "android:focusable="false" for all the buttons inside my ListView item, they were stealing the focus making selected list item non-touchable.
Reference: click-events-listview-gridview
I want to copy the text in the current TextView (within a fragment) in a ViewPager, but it copies the previous, or the text in the next TextView. I searched and found that it is because of the ViewPager's normal behaviour to create three pages: The previous, current and the next page. But I could not find how to determine the current one easily?
I use ViewPager with FragmentStatePagerAdapter.
Edit:
I have searched for this for two days but after asking my question I found nearly the same problem:
This is a better asked and explained question then mine. Atleast I learned how to ask and explain.
Wrong fragment in ViewPager receives onContextItemSelected call
but "getUserVisibleHint()" answer doesnot work for me?
...Fragment.java
onCreateView
.........
tvTextView = (TextView) v.findViewById(R.id.TextView);
tvTextView.setTextSize( TypedValue.COMPLEX_UNIT_PX, boyut);
registerForContextMenu(TextView);
.....
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
if (view.getId()== R.id.tvTextView) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
menu.setHeaderTitle("Copy...");
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if( getUserVisibleHint() == false )
{
return false;
}
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.copy:
copy();
return true;
default:
return true;
}
}
In ..FragmentContainer.java
....
mViewPager = (ViewPager) findViewById(R.id.viewPagerLayout);
FragmentManager fm = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
#Override
public int getCount() {
return myArray.size();
}
#Override
public Fragment getItem(int pos) {
return ...Fragment.newInstance(name, pos, checkedItems, fontsize);
}
});
After a lot of searching and I dont know how many trial and error, I found a solution for my problem.
Using "getUserVisibleHint()" or "getGroupId()" methods, I couldnot get the current textview's text.
I used "text = tvTextView.getText().toString();" in onContextItemSelected or in onCreateView methods, but it didnot work.
#Override
public boolean onContextItemSelected(MenuItem item) {
if( ! getUserVisibleHint() )
{
return false;
}
// this is not working
text = tvTextView.getText().toString();
Then I tried making setText and getText methods for fragment and getting the text in onContextItemSelected method using getText method. It works great!
First I added two methods to Fragment:
public String getText() {
return mText;
}
public void setText(String text) {
mText = text;
}
In onCreateView I set the text
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, parent, false);
tvTextView = (TextView) v.findViewById(R.id.tvTextView);
registerForContextMenu(tvTextView);
String tvText = tvTextView.getText().toString();
// I set the text
setText(tvText);
Then in onContextItemSelected I get it using getText
#Override
public boolean onContextItemSelected(MenuItem item) {
if( ! getUserVisibleHint() )
{
return false;
}
// I get the text
mCopyText = getText();
Both "getUserVisibleHint()" or "getGroupId()" methods works great in this way. I hope this help other people.