Depending on the clicked button out of 3 button, different data gets populated in listView.
I've used this
onListItemClick snippet
//ltable refers to list
String item = ltable.getItemAtPosition(position).toString();
Intent i = new Intent(getApplicationContext(),NextClass.class);
i.putExtra("name", item);
startActivity(i);
Now on any button click, corresponding data gets populated in listView. Then on listItelClick, it navigates to NextClass.class and hence new activity gets launched.
What if I want app to navigate to next view if and only if listView is populated when Gainers or Losers button is pressed????
If listView is populated on Index button click, it should not navigate.
i.e. Clicked button should be captured.
I tried to use flag, but only final variables are permitted within buttonClickListener, so it doesn't work.
How can I implement this??
ANY HELP WILL BE LIFE-SAVER !!!
Take a class level variable
boolean shouldNavigate = false;
and in onClick() of Index Button. set shouldNavigate to false:
public void onClick(View v)
{
// Update adapter for Index..
shouldNavigate = false;
}
But in onClick() of other than Index Button. set shouldNavigate to true:
public void onClick(View v)
{
// Update adapter for Gainer or Losers..
shouldNavigate = true;
}
and inside your onItemClick() check for the flag and navigate accordingly
public void onItemClick(AdapterView parent, View view, int position, long id) {
if(shouldNavigate)
{
// you can navigagte...
}
else
{
// do other task
}
}
When you are in the 'Index' mode, remove the onItemClickListener. Add it back for the other two buttons.
Related
Just wondering if what I'm trying to do is possible. So i have a custom adapter for a listview. It contains a textview and two buttons. I would like one of the listview buttons to remain hidden unless a specific button is pressed on the main activity.
So far I have the listview buttons performing their intended function but I have no idea how I would even begin to get what I'm wanting.
Sorry, for clarification, I have one button completely separate from the listview that is just always there. When I press this button I would like to toggle the visibility of a button that is on each listview item all together. The best example of this that I can think of is having a list of items and a button that can toggle off the 1. 2. 3. 4. that comes in front of each item.
Create a method in your adapter for knowing you have clicked the button from your main activity like this
public void buttonIsClicked(){ //in your adapter
buttonhide.setVisibility(visibility?View.VISIBLE:View.GONE);
}
And call this method from your activity on btnclick.
like
yourAdapter.buttonIsClicked();
and call this method for notifying the adapter about the change.
yourAdapter.notifyDatasetChanged().
or
You can use an interface for listening to the clicks in main activity and implement that listener in your adapter
Set visibility gone to the button you want to hide by calling code
buttonhide.setVisibilty(VIEW.GONE);
hide it in oncreate() of your activity and make it shown on the button click event by calling code buttonhide.setVisibilty(VIEW.VISIBLE);
Below is the code
btnView.setVisibility(View.GONE);
yes it is possible to do that.
First have a Model class to back the listview data and keep a flag in that model which indicates whether to show the button in that row's data model. On certain condition change that model's flag and call notifyDataSetChanged() on adapter.
Ex:
class Model{
String label;
boolean showBtn;
}
in adapter's getView()
Model model = list.get(position)
if(model.showBtn){
btn.setVisibility(View.VISIBLE);
}else{
btn.setVisibility(View.GONE);
}
in Activity
disableButton(){
modelList.get(0).setShowBtn(false);
adapter.notifyDataSetChanged();
}
This code will hide button in first row
Add a Boolean value in your dataset which represent the Visibility state of the button.
public class Dataset {
private boolean visible;
public boolean isVisible() {
return this.visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
//..more items
}
Then in your getView method of the Adapter check this Boolean value to show/hide the button.
boolean visibility = yourDataset.get(position).isVisible();
yourButton.setVisibility(visibility?View.VISIBLE:View.GONE);
And when the Button outside of your listview is clicked Update your dataset. And call yourAdapter.notifyDatasetChanged().
What you are attempting is: manipulating the visibility of the button declared in the Adapter from the containing activity. Simple, put a controlling variable in the activity and pass it a parameter to adapter.
Boolean mShowButton; //a controlling variable
void onCreate(Bundle savedInstanceState) {
...
mAdapter=new MyAdapter(...,mShowButton);
mButton.setOnClickListener(actionShow );
}
OnClickListener actionShow = new OnClickListener() {
#Override
public void onClick(View button) {
mShowButton=true;
mAdapter.notifyDataSetChanged();
mListView.invalidateViews();
}
};
And do this in your adapter,
Boolean showButton;
public MyAdapter(Context context, List<String> myList, Boolean showButton) {
...
this.showButton=showButton;
}
public View getView(int position, View rowView, ViewGroup parent) {
...
if(showButton){
mButtonTwo.setVisibility(View.GONE);
}else{
mButtonTwo.setVisibility(View.VISIBLE);
}
}
I've got a card-view that each card has a button on it. I'm trying to get the position of the card that holds the button when the users clicks the button.
I have an adapter that extends from RecyclerView.Adapter and implements the following method...
public void onBindViewHolder(MovieImageViewHolder movieImageViewHolder, int i) {
Movie movieItem = mMovieList.get(i);
movieImageViewHolder.details.setTag(i);
movieImageViewHolder.details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position = (Integer) v.getTag();
}
});
}
This works sucessfully, when I press a button on card 1, position equals 1 and when I press a button on card 4, position equals 4.
The question is, how do I get this value (position) out of the adapter and back into the Activity so I can use it? or do I even need to do that? I'm trying to create a new intent but don't think that should be done from the adapter?
I attempted to create a getter for the variable position, and call the primary button action with
public void buttonClick(View view) {
int position = adapter.getPosition();
Log.d(TAG, "Button Clicked::- " + String.valueOf(position));
}
Using
android:onClick="buttonClick"
In the XML, but nothing happens when clicking the button, I believe this is because the OnClick method in the adapter is fired instead?
EDIT:
Seems I've made some progress. Worked out that I can set the tag in the adapter
movieImageViewHolder.btn_details.setTag(i);
Then get that tag back in my onClick method with .getTag();
Only thing now is the tag seems to be zero for the first element, then zero for the second element, then starts at one for the third... Any reason why this would be?
This was actually very simple and a very common "issue" people face. I was set down the path that I couldn't create an activity from an adapter where infact that is exactly what I should have been trying to do.
movieImageViewHolder.details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
Integer taggedPosition = (Integer) v.getTag();
Intent intent = new Intent(mContext, ViewMovieDetailsActivity.class);
intent.putExtra(SearchMovie.MOVIE_TRANSFER, getMovie(taggedPosition));
v.getContext().startActivity(intent);
}
});
Correctly starts the correct activity.
Is there anyway to prevent double tap on ListView in Android? I found this when i accidentally tapped item on ListView and it opened up two new window. is there any way to prevent it from opening a same window twice.
Just add listView.setEnabled(false); on select of listview and after select when response will come or back button press just write---- listView.setEnabled(true);
You should restrict the target activity (one that opens when an item is clicked) to have only one instance at any point of time.
Answer to this SO question should help you in achieving that. That way if you accidentally double click, you will still see just one new screen.
Have a try with introducing and Override of isEnabled method
#Override
public boolean isEnabled(int position) {
return false;
}
for the listview.
introduce a boolean for flag and an int to maintain last clicked position
int recentlyClickedPoisition;
boolean flagRecentClickedPoisition;
override the isEnabled method as follows
#Override
public boolean isEnabled(int position) {
if (flagRecentClickedPoisition && recentlyClickedPoisition == position) {
return false;
} else {
return true;
}
}
than set the last clicked position from your click listener as follows
public void setLastClickedPoisition(int recentlyClickedPoisition) {
flagRecentClickedPoisition = true;
this.recentlyClickedPoisition = recentlyClickedPoisition;
}
Hope this will work for you to prevent from double tap, enhance accordinly.
If you are using just single item like TextView in list then just create a class implements OnItemClickListener in this call and then in to onItemClick() method initialize myListView.setOnItemClickListenet(null);
then use Handler.postDelayed method to again set onItemClickListener.
like
myListView.setOnItemClickListener(new MyClickListenerClass());
This is working for all time in my case.
In your XAML view page place isEnable property as a bindable and two way mode.
<ListView ItemsSource="{Binding items}"
x:Name="listview"
HasUnevenRows="True"
IsEnabled="{Binding IsEnable, Mode=TwoWay}"
RowHeight="10"
SelectionMode="Single"
VerticalScrollBarVisibility="Never">
In viewmodel of your xaml page :
private bool _isEnable = true;
public bool IsEnable
{
get => _isEnable;
set
{
_isEnable = value; OnPropertyChanged(nameof(IsEnable));
}
}
public ICommand TapCommand => new Command<//Model>(async (obj) =>
{
IsEnable = false;
//your stuff
IsEnable = true;
});
I have a two pane layout, a listview that controls a detail view. First I thought a delayed handler is the worst idea, but after testing it is the simplest. Otherwise I would have to communicate between activity and fragment to enable the listview item once another detail was loaded. Error prone and complex.
/*example with Handler():*/
final boolean[] allowClick = {true};
myview.setOnClickListener(v -> {
//exit if not allowed
if(!allowClick[0])
return;
//do stuff
//we clicked, block another click
allowClick[0] =false;
//wait 0.7 seconds and allow another click
new Handler().postDelayed(() -> allowClick[0] =true, 700);
});
This solution is implemented on a ListFragment. If the tap dismissed the ListFragment to show a detail view (which it normally would), the next time the ListFragment appears, the tap counter is reset in OnResume():
public class MyListFragment extends ListFragment {
int mTapCounter;
#Override
public void onResume() {
super.onResume();
//Set-Reset ListView clickListener
mTapCounter = 0;
}
//ListView item tap event handler
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
//Disable click listener to prevent double-tap
mTapCounter++;
//Only process single-tap
if(mTapCounter == 1) {
/* YOUR TAP HANDLER CODE HERE */
}
super.onListItemClick(l, v, position, id);
}
}
I have a ListView that contains items with checkboxes that should behave sometimes like a CHOICE_MODE_MULTIPLE and sometimes like a CHOICE_MODE_SINGLE. What I mean is for certain items in the list, when selected certain other items needs to be deselected whilst other can remain selected.
So when item A is checked I can find in my data the item B that needs to be unchecked but how do I get the UI to refresh to show this as I (I believe) cannot find the actual View that represents B but just it's data?
It sounds like you're off to a good start. You're right that you should be manipulating the underlying data source for item B when A is clicked.
Two tips that may help you:
Your getView() method in the Adapter should be looking at your data source and changing convertView based on what it finds. You cannot find the actual View that represents B because in a ListView, the Views are recycled and get reused as different data needs to be displayed. Basically, when an item is scrolled off the list, the View that was used gets passed to the getView() function as convertView, ready to handle the next element's data. For this reason, you should probably never directly change a View in a ListView based on user input, but rather the underlying data.
You can call notifyDataSetChanged() from within your adapter to signal that somewhere the underlying data has been changed and getView() should be called again for the elements currently displayed in your list.
If you're still having trouble, feel free to post some code that illustrates the specific problem that you're having. It's much easier to provide concrete advice when the problem is better defined. Hope this helps!
you can use singleChoice alartDialog, i have used like:
private int i = 0; // this is global
private final CharSequence[] items = {"Breakfast", "Lunch", "Dinner"}; // this is global
Button settings = (Button)view.findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
//Title of Popup
builder.setTitle("Settings");
builder.setSingleChoiceItems(items, i,
new DialogInterface.OnClickListener() {
// When you click the radio button
public void onClick(DialogInterface dialog, int item){
i=item;
}
});
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (i == 0) {
//it means 1st item is checked, so do your code
}
if (i == 1) {
//it means 2nd item is checked, so do your code
} /// for more item do if statement
}
});
//When you click Cancel, Leaves PopUp.
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
});
i have initialized i=0, so that for the very first time when user click on settings button, the first item is selected. and after then when user select other item, i have saved the i value so that next time when user click settings button, i can show user his/her previously selected item is selected.
I come across and solve this question today.
public class ItemChooceActivity extends Activity implements OnItemClickListener {
private int chosenOne = -1;
class Madapter extends BaseAdapter {
.....
.....
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
if (chosenOne != position) {
set the view in A style
} else {
set the view in B style
}
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
,,,,
chosenOne = position;
adapter.notifyDataSetChanged();
,,,
}
}
I'm new to Android. I'm working on a listView-based app: you have a main menu, when you click an item, a new activity starts with another menu; when you click again, a new activity starts with the content you selected. Since I've quite a lot of menu items, I've to create a listener which handles all possible cases, so I've something similar:
#Override public void onItemClick(AdapterView<?> listAdapter, View v, int position, long id) {
String text = ((TextView)v).getText().toString();
//main menu
if (text.equals(K.getStringById(K.ID_MAIN_THEORY))) {
...
} else if (text.equals(K.getStringById(K.ID_MAIN_EXERCISE))) {
...
}
else if (text.equals(K.getStringById(K.ID_MAIN_TABLES))) {
...
}
//here other menus' items: lots of items
...
//back item
else if (text.equals(K.getStringById(K.ID_BACK))) {
activity.finish();
}
Intent i = new Intent(...);
startActivity(i);
}
* K is a class that holds ids' references
There's a way I can avoid hard-coding listener behavior?
** PS: the lists' TextViews don't render properly: text appears light grey, not black! O.o
It's more useful to use the position rather than the view to switch the action of the click event. Your ListView should be populated from some sort of List, therefore when the onClick fires, giving you the position, you can reference that position in the List to know what was clicked.
If you want to click on item and in result it goes to another activity, for example if you have three item and when you click on item A it will redirect you to activity A and if B then to B and so on,
lstview.setOnItemClickListener(new OnItemClickListener()
{
private String input;
public void onItemClick(AdapterView<?> v, View arg1, int index,long arg3)
{
if(index==1)
{
Intent intnt=new Intent(v.getContext(),A.class);
startActivity(intnt);
}
else if (index==2)
{
Intent intnt=new Intent(v.getContext(),B.class);
startActivity(intnt);
}
else
{
Intent intnt=new Intent(v.getContext(),C.class);
startActivity(intnt);
}
}
}
Here in this case you are going to different activities on selection the items in a list view, put your comments for further query.
I solved this way: I think it's pretty good.
//This in K class, where MAPPED_HIERARCHY is a static field
static void activity(android.app.Activity a) {
MAPPED_HIERARCHY = new HashMap<String, ArrayList<String>>();
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.app_name), K.array2list(a.getResources().getStringArray(R.array.menu_main)));
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.main_theory), K.array2list(a.getResources().getStringArray(R.array.menu_theory)));
MAPPED_HIERARCHY.put(a.getResources().getString(R.string.main_exercise), K.array2list(a.getResources().getStringArray(R.array.menu_exercise)));
....
}
static ArrayList<String> getArrayListByString(String string) {
ArrayList<String> copy = new ArrayList<String>(MAPPED_HIERARCHY.get(string).size());
for (String s : MAPPED_HIERARCHY.get(string))
copy.add(s);
return copy; //defensive copy
}
//This in my listener class
#Override public void onItemClick(AdapterView<?> listAdapter, View v, int position, long id) {
String text = ((TextView)v).getText().toString();
ArrayList<String> params = K.getArrayListByString(text);
Intent i = new Intent(...);
i.putExtra("params", params);
activity.startActivity(i);
}
I have a map which links an arraylist containing the menu items with the string wihich causes the menu to be displayed; on the click event, I simply retrieve the arraylist according with the selected item's text.