I want to make a custom list of radio groups, that should has a text view and a radio group in each item and each radio group contains radio buttons, i could do it but there's a problem...., the radio buttons are repeated more than it should be in each item and i can select more than one radio button in a radio group which is wrong,
here's what i've done:
PollsQuestionsAdapter
public class PollsQuestionsAdapter extends ArrayAdapter {
Context context;
List<PollQuestion> pollQuestionList;
public PollsQuestionsAdapter(Context context, List<PollQuestion> pollQuestionList) {
super(context, R.layout.polls_questions_list_item, pollQuestionList);
this.context = context;
this.pollQuestionList = pollQuestionList;
}
#Override
public int getCount() {
return pollQuestionList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.polls_questions_list_item, parent, false);
}
RadioGroup rgAnswer;
TextView tvQuestion;
tvQuestion = (TextView) convertView.findViewById(R.id.polls_questions_list_item_question_name);
rgAnswer = (RadioGroup) convertView.findViewById(R.id.polls_questions_list_item_answer);
String questionName;
List<PollAnswer> answerList;
if (Language.lang.equals("EN") || Language.lang.equals("En") || Language.lang.equals("en"))
questionName = pollQuestionList.get(position).getQuestionTextEN();
else
questionName = pollQuestionList.get(position).getQuestionTextAR();
answerList = pollQuestionList.get(position).getAnswersList();
rgAnswer.setTag(pollQuestionList.get(position).getQuestionId()); // to use it when you get the value of question id
for (int i = 0; i < answerList.size(); i++) {
RadioButton radioButton = new RadioButton(context);
if (Language.lang.equals("EN") || Language.lang.equals("En") || Language.lang.equals("en"))
radioButton.setText(answerList.get(i).getAnswerTextEN());
else
radioButton.setText(answerList.get(i).getAnswerTextAR());
radioButton.setId(answerList.get(position).getAnswerId()); // to use it when you get the value of the answer id
rgAnswer.addView(radioButton);
}
tvQuestion.setText(questionName);
return convertView;
}
}
polls_questions_list_item
<?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="match_parent"
android:background="#1E5BAC"
android:orientation="vertical"
android:padding="#dimen/padding_normal">
<TextView
android:id="#+id/polls_questions_list_item_question_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#android:color/white"
android:textSize="#dimen/font_large"
android:textStyle="bold" />
<RadioGroup
android:id="#+id/polls_questions_list_item_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white">
</RadioGroup>
</LinearLayout>
and here's how i called the adapter in my activity:
List<PollQuestion> pollQuestionList = new ArrayList<>();
ArrayList<PollAnswer> pollAnswerList = new ArrayList<>();
pollAnswerList.add(new PollAnswer(1, "Yes", "نعم"));
pollAnswerList.add(new PollAnswer(2, "No", "لا"));
pollQuestionList.add(new PollQuestion("مواعيد المحاضرات بها تعارض", "Schedule has conflict", 1, pollAnswerList));
pollAnswerList = new ArrayList<>();
pollAnswerList.add(new PollAnswer(3, "High", "مرتفعة"));
pollAnswerList.add(new PollAnswer(4, "Medium", "متوسطة"));
pollAnswerList.add(new PollAnswer(5, "Low", "منخفضة"));
pollQuestionList.add(new PollQuestion("مواعيد المحاضرات موزعة بالتساوى خلال الاسبوع", "The lectures schedule is balanced during week",2, pollAnswerList));
PollsQuestionsAdapter adapter = new PollsQuestionsAdapter(PollsQuestionsActivity.this, pollQuestionList);
listView.setAdapter(adapter);
and this is the result :
result1
result2
the first item should contain:
Yes and No only
the second item should contain:
High, Medium and Low only
and the radio buttons in each radio group should should be selected together, only one button is pressed and the others are disabled which doesn't happen in the items here.
so, could any one tell me what did i do wrong ?
Thanks in advance.
Related
I'm trying to better understand the following situation that arose while refactoring some "selection highlighting" code (to take advantage of tinting).
There's a list that's populated with an adapter, CodebookAdapter, where each item's defined as:
CodebookAdapter List Item Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#FFFFFFFF">
<ImageView
android:id="#+id/item_icon_iv"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center_vertical" />
<TextView
android:id="#+id/item_header_tv"
android:layout_width="match_parent"
android:layout_height="20dp"
android:textColor="#FF000000"
android:textSize="14dp"/>
<!--android:background="#FFFFFFFF"-->
</LinearLayout>
The method below, HiliteCodeItem(), sets the TextView, item_header_tv, to selected.
I've set the background-tint first on the list-item itself, and then just on the enclosed TextView (to avoid undesired highlighting of the entire layout):
// option 1 - item_header_tv's background can be omitted/null, highlights ok
/////////////////////////////////////////////////////////////
v.Background.SetTintList(_csl);
// option 2 - item_header_tv's background cannot be omitted/null
/////////////////////////////////////////////////////////////
tv.Background.SetTintList(_csl);
Why if in option 2 the background must be explicitly set (or else tv.Background.SetTintList(_csl); throws null ex), but in option 1 item_header_tv's background get's highlighted?
Is the enclosing list item's LinearLayout doing a null check on the background of TextView and instantiating one?
public class Codebook : LinearLayout
{
protected virtual void HiliteCodeItem(TextView codeDesc, Code code)
{
_codebookAdapter.SelectedCode = code;
//codeDesc.SetBackgroundColor(SelectedCodeListItemBgColor);
codeDesc.Selected = true;
_codebookAdapter.NotifyDataSetChanged();
}
protected class CodebookAdapter : ArrayAdapter<Code>
{
private Codebook _; // explicit outer object ref
private int _listItemRes;
private List<Code> _items;
private Android.Content.Res.ColorStateList _csl;
public Code SelectedCode { get; set; }
public CodebookAdapter(Context context, int listItemRes, List<Code> items, Codebook outer)
: base(context, listItemRes.Layout, items)
{
_ = outer;
_listItemRes = listItemRes;
_items = items;
_csl = _._context.Resources.GetColorStateList(Resource.Color.codebook_code_list_item_color_state_list);
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
TextView tv;
if (v == null)
{
v = _._inflater.Inflate(_listItemRes, parent, false);
tv = v.FindViewById<TextView>(Resource.Id.item_header_tv);
// option 1 - item_header_tv's background can be omitted/null, highlights ok
/////////////////////////////////////////////////////////////
v.Background.SetTintList(_csl);
// option 2 - item_header_tv's background cannot be omitted/null
/////////////////////////////////////////////////////////////
tv.Background.SetTintList(_csl);
}
else
tv = v.FindViewById<TextView>(Resource.Id.item_header_tv);
if (_items == null || _items.Count == 0)
{
return v;
}
Code code = _items[position];
if (code != null)
{
if (code == SelectedCode)
{
//tvCodeHeader.SetBackgroundColor(_.SelectedCodeListItemBgColor);
tvCodeHeader.Selected = true;
}
else
{
//tvCodeHeader.SetBackgroundColor(_.UnselectedCodeListItemBgColor);
tvCodeHeader.Selected = false;
}
}
}
}
}
Why if in option 2 the background must be explicitly set (or else tv.Background.SetTintList(_csl); throws null ex), but in option 1 item_header_tv's background get's highlighted?
The first works because you've set android:background="#FFFFFFFF" to the LinearLayout, the code v = _._inflater.Inflate(_listItemRes, parent, false); points to the this LinearLayout. So it's background is not omitted/null.
The Background cannot be null if you want to SetTintList, the second line doesn't work because Background of your TextView v is null.
By the way, controls like Button has Background set by default, you don't need to specify the Background property for them to use SetTintList.
I am Using the this as swipe to delete. but I am having problem in implementing only the delete menu item of the list.
What I am doing is creating just one single delete Item. I really do not want to use any other item such like Open as shown in demo.
here is my design
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dadada">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/segmented_buttons">
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:orientation="vertical">
<!--<ScrollView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:layout_gravity="center"-->
<!--android:gravity="center"-->
<!--android:clickable="false">-->
<TextView
android:id="#+id/swipeRefreshLayout_emptyView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|center_vertical"
android:enabled="false"
android:gravity="center"
android:visibility="gone" />
<com.baoyz.swipemenulistview.SwipeMenuListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:clipChildren="false"
android:divider="#android:color/transparent"
android:dividerHeight="5.0sp" />
<!--</ScrollView>-->
</FrameLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</RelativeLayout>
and here is How I Am creating my menu in my Fragment
SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getActivity());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
0x3F, 0x25)));
// set item width
deleteItem.setWidth(dp2px(90));
// set a icon
deleteItem.setIcon(R.drawable.ic_delete);
// add to menu
menu.addMenuItem(deleteItem);
}
};
here is how I am setting creator
// set creator
mListView.setMenuCreator(creator);
My Problem I have couple of problems regarding to the delete, as mentioned
When I have too many data in the list , say that the number of rows are 10 and need to scroll down , the delete option work like a charm even from the first row of the listview.
When there are lesser item in the list or if I continue to delete items from the bottom I mean the last row , when there are less item which do not need to scroll down, does not delete smoothly , it takes many times to refresh list , or open and close again the menu right to left , takes many touch down on delete menu and then it delete some how after too many tries.
I do not know what is problem behind , but When I made the two menu , like Open and Delete as shown in the demo , then I made both open and delete as delete button , so in Case 0 , and Case 1 , I wrote code of delete , then I noticed that the deleting is working every time when I touch on open , but again when I touch on delete it some times deletes the item or some time it takes to many tries.
What could be problem ? Any guess ? Is there any work around ?
And Yeah On thing for sure , When I touch the delete menu it gives me a Log , look down below, It show me this in log , when I Touch to delete and delete is in fact not working , but when it does start working this message in log never shows up.
D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
Edit One
Here is my whole code of adapter :
public class SwipeListOfferAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<OfferStatusData> offerList;
OfferStatusData offerStatusData;
public SwipeListOfferAdapter(Activity activity, List<OfferStatusData> offerList) {
this.activity = activity;
this.offerList = (ArrayList)offerList;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return offerList.size();
}
#Override
public Object getItem(int location) {
return offerList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_offer_status, null);
holder = new ViewHolder();
// holder.tvCustomerName = (TextView) convertView.findViewById(R.id.tv_row_customer_name);
holder.tvOfferName = (TextView) convertView.findViewById(R.id.row_offer_name);
// holder.tvEmail = (TextView) convertView.findViewById(R.id.row_email);
holder.tvPhoneNumber = (TextView) convertView.findViewById(R.id.row_phone_number);
holder.tvAddress = (TextView) convertView.findViewById(R.id.row_address);
holder.tvTmcBrand = (TextView) convertView.findViewById(R.id.row_tmc_brand);
holder.tvStartEndTime = (TextView) convertView.findViewById(R.id.row_offer_time);
holder.tvNoOfPerson = (TextView) convertView.findViewById(R.id.tv_row_total_person);
holder.tvNoOfAcceptors = (TextView) convertView.findViewById(R.id.tv_row_total_acceptors);
holder.tvMonth = (TextView) convertView.findViewById(R.id.tv_row_month);
holder.tvDay = (TextView) convertView.findViewById(R.id.tv_row_day);
// holder.tvCustomerName = (TextView) convertView.findViewById(R.id.tv_row_customer_name);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
if(offerList.size()>0){
offerStatusData = (OfferStatusData)offerList.get(position);
// holder.tvCustomerName.setText(offerStatusData.getName());
holder.tvOfferName.setText(offerStatusData.getOffer_name());
// holder.tvEmail.setText(offerStatusData.getEmail());
holder.tvPhoneNumber.setText(offerStatusData.getPhone_number());
holder.tvAddress.setText(offerStatusData.getAddress());
holder.tvTmcBrand.setText(offerStatusData.getTmc_brand());
holder.tvStartEndTime.setText(offerStatusData.getStart_time()+"-"+offerStatusData.getEnd_time());
holder.tvNoOfPerson.setText(offerStatusData.getNo_of_person());
holder.tvNoOfPerson.setTextColor(Color.parseColor("#F66D0D"));
holder.tvNoOfAcceptors.setText(offerStatusData.getCurrent_acceptors()+"/"+offerStatusData.getNo_of_person());
holder.tvNoOfAcceptors.setTextColor(Color.parseColor("#2B5BD2"));
// holder.tvMonth.setText("july");
// holder.tvDay.setText("29");
String dateFromService = offerStatusData.getDate();
String[] monthFromService = dateFromService.split("-");
Log.d("date split", dateFromService.toString());
holder.tvDay.setText(monthFromService[2].toString());
holder.tvDay.setTextColor(Color.parseColor("#57902B"));
holder.tvMonth.setText(getMonth(Integer.parseInt(monthFromService[1])));
holder.tvMonth.setTextColor(Color.parseColor("#57902B"));
}
return convertView;
// String color = bgColors[position % bgColors.length];
// serial.setBackgroundColor(Color.parseColor(color));
}
void delete (int post){
offerList.remove(post);
}
class ViewHolder{
TextView tvOfferName,tvPhoneNumber,tvAddress,
tvTmcBrand,tvStartEndTime,tvNoOfPerson,tvNoOfAcceptors,tvMonth,tvDay;
}
public String getMonth(int month) {
return new DateFormatSymbols().getShortMonths()[month-1];
// return new DateFormatSymbols().getMonths()[month-1];
}
}
So I really do not know what is the main reason behind this , No clue left for me. Please tell me what could be the problem.
Try this,
listView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow View pager to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow View pager to intercept touch events.
// v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle Listview touch events.
v.onTouchEvent(event);
return true;
}
});
I am new to android,I know access of spinner but I want to add default text in spinner and want set lay out like below image,can any one help me with this,
final String[] items = new String[] {"One", "Two", "Three"};
final ArrayAdapter<String> adapter123 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, items);
sp3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(RegistrationForm.this)
.setTitle("the prompt")
.setAdapter(adapter123, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
});
My suggestion for your case is use Button initially set text and set gravity (not layout_gravity) to left|center_vertical instead of opening an AlertDialog open a PopupWindow set that Button as anchor of that PopUpWindow. In that PopUpWindow place a ListView and in OnItemClick change text with selected value in that Button using setText(java.lang.CharSequence)
code snippet
XML for that Button
<Button
android:id="#+id/propertyBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#dimen/dp_4"
android:background="#drawable/property_btn_large"
android:ellipsize="marquee"
android:gravity="left|center_vertical"
android:marqueeRepeatLimit="marquee_forever"
android:minHeight="0dp"
android:minWidth="0dp"
android:onClick="showPropertyPopUp"
android:paddingLeft="42dp"
android:paddingRight="22dp"
android:shadowColor="#android:color/white"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1"
android:text="#string/select_property" />
Java code for opening PopUpWindow in that Button click
//don't forget to initialize that button in onCreate(...)
public void showPropertyPopUp(View v) {
propertyList = dbHelper.getAllProperties();
dbHelper.closeDB();
if(propertyList != null && propertyList.size() > 0) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popUpView = inflater.inflate(R.layout.pop_up, null, false);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.select_dropdown);
popupWindowProperty = new PopupWindow(popUpView, propertyBtn.getWidth(),
300, true);
popupWindowProperty.setContentView(popUpView);
popupWindowProperty.setBackgroundDrawable(new BitmapDrawable(getResources(),
bitmap));
popupWindowProperty.setOutsideTouchable(true);
popupWindowProperty.setFocusable(true);
popupWindowProperty.showAsDropDown(propertyBtn, 0, 0);
ListView dropdownListView = (ListView) popUpView.
findViewById(R.id.dropdownListView);
PropertyDropdownAdapter adapter = new PropertyDropdownAdapter(
AddIncomeActivity.this,
R.layout.row_pop_up_list, propertyList);
dropdownListView.setAdapter(adapter);
dropdownListView.setOnItemClickListener(this);
}
}
code for setting text on that Button in OnItemClick
PropertyInfo addPropertyInfo = propertyList.get(position);
String propertyName = addPropertyInfo.getPropertyName();
propertyBtn.setText(propertyName);
popupWindowProperty.dismiss();
pop_up layout
<?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="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/dropdownListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#null"
android:fadeScrollbars="false" >
</ListView>
</LinearLayout>
Screenshot on clicking on that Button
Screenshot after item click of ListView
Add one more element in array which you are passing in spinner and if you want to add validation you can check it by runtime using -
if (spnType.getSelectedItemPosition() == 0) {
View view = spnType.getSelectedView();
SpinnerView adapter = (SpinnerView) spnType.getAdapter();
adapter.setError(view, getString(R.string.err_leadtype));
return false;
} else {
strType = arllistType.get(spnType.getSelectedItemPosition()).get(
WebServiceResponseParameter.LIST_VALUE);
}
As Nitish explained, You need to add default value on top of your array R.array.day_birthdate. Suppose you your array is day_birthdate then add day in top where you define
<string-array name="day_birthdate">
<item name="0">day</item>
<item name="1">1</item>
...
</string-array>
Add validaton on Spinner, if option first is selected then,
if (mSpinnerBirthDate.getSelectedItemPosition() == 0) { //where mSpinnerBirthDate is Spinner for Birthdate
//show invalid selection message
}else{
//get selected value from spinner
}
Add one more element in array which you are passing in spinner and then write this code in java file.
String array[]=getResources().getStringArray(R.array.name_Of_array);
ArrayAdapter<String> ad=new ArrayAdapter<String>(this,layoutid, array);
spinner.setAdapter(ad);
You can not do that, for that you have to create custom spinner or you have to show alertdialog as a action when text view is clicked.
Edited :
Create a array
String a [] = new String [4] ;
a[0] = "ram";
a[1] = "shyam";
a[2] = "mohan";
a[3] = "krishna";
use this array as a source of listview data, now as a action listview will be displayed and set a listener for listview which will provide you a position of clicked item in the listview,
use that position for array[position], lets position = 2, then clicked item text will be mohan set this text as a item of textview .
Edited 2:
Create custom Dialog with listview inside it.
set onItemClickListener in listview.
onCreate
{
dayTextView.setText("day");
}
onItemClickListener ()
{
dayTextView.setText("Sunday");
}
Edited 3 :
Follow this tutorial for custom dilaog : http://rajeshvijayakumar.blogspot.in/2013/04/alert-dialog-dialog-with-item-list.html
I have a hidden textView in listView item layout and when the item is clicked, I am displaying that hidden textView. However, when I click another item, I want the other visible textview in item to be hidden again. So how can I access the textView of this other item?
theListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView itemView2 = (TextView)view.findViewById(R.id.textView2);
itemView2.setVisibility(View.VISIBLE);
itemView2.setBackgroundColor(color.white);
Double lat = Double.parseDouble(((KioskInfo)parent.getItemAtPosition(position)).getLat());
Double lng = Double.parseDouble(((KioskInfo)parent.getItemAtPosition(position)).getLng());
LatLng itemLocation = new LatLng(lat,lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(itemLocation, 18 ));
}
});
item_layout.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="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp"
android:textSize="15sp"
android:textColor="#color/loginblue"></TextView>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp"
android:textSize="12sp"
android:visibility="gone"
android:textColor="#color/loginblue"></TextView>
</LinearLayout>
You need to remember the index/position of the selected item in your ListView. Then, if another item is selected, you test if there already is another selected item. If so you can get that item's view like so:
// Hide previously selected text view
if (selectedIndex > -1) {
int viewIndex = selectedIndex - listView.getFirstVisiblePosition();
// if previously selected list item is still visible, hide its text view
if (viewIndex > -1 && viewIndex < listView.getChildCount()) {
View itemView = listView.getChildAt(viewIndex);
TextView textView = itemView.findViewById(R.id.textView2);
textView.setVisibility(View.GONE);
}
}
// Now you make the newly selected text view visible and remember the selected item
selectedIndex = position;
selectedIndex is an instance variable of either your click listener or any other surrounding class. Initialize it with -1 as no item is selected in the beginning.
Obviously you can optimize the code. It just to clarify to basic steps to accomplish your task.
define this as member variable in your activity,
int clickedPosition = -1;
then use this code,
heListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(clickedPosition!= position && clickedPosition != -1){
clickedPosition = position;
View previousView = heListView.getChildAt(clickedPosition);
TextView itemView2 = (TextView)view.findViewById(R.id.textView2);
itemView2.setVisibility(View.INVISIBLE);
}
TextView itemView2 = (TextView)view.findViewById(R.id.textView2);
itemView2.setVisibility(View.VISIBLE);
itemView2.setBackgroundColor(color.white);
Double lat = Double.parseDouble(((KioskInfo)parent.getItemAtPosition(position)).getLat());
Double lng = Double.parseDouble(((KioskInfo)parent.getItemAtPosition(position)).getLng());
LatLng itemLocation = new LatLng(lat,lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(itemLocation, 18 ));
}
});
I would like to implement multi item selection in a GridView with ImageView changing color to blue.
I mean I have a GridView with ImageView where I load user's image from url.
In my GridView I would like to highlight the multiple selection image (es blue) like in picture
My GridView :
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:scrollbarStyle="insideOverlay"
android:scrollbars="vertical"
android:listSelector="#null" />
Imem in a GridView:
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/userLikesimg"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#color/blu_facebook_transparent"
android:scaleType="centerCrop" />
You could create an OnItemClickListener that changes a flag on the item from 0 to 1 or true to false.
boolean isSelected = 0;
as the standard value.
in the OnItemClickListener you can change this to
boolean isSelected=1;
then after they complete the activity you can parse the objects in the gridview / listview and see which has isSelected=1 and perform whatever activity based off of that.
I solved unisng LayerDrawable in my adapter:
numElement is int and define num elements chosen
selectedElements is array of boolean with position elements chosen
public boolean[] selectedElements= new boolean[n];
private int selectedElements= m;
public View getView(final int position, View amico, ViewGroup parent) {
...
viewHolder.userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedElements[position] == false) {
if (numElementi == 0) {
Toast.makeText(mContext, R.string.error, Toast.LENGTH_LONG).show();
} else {
BitmapDrawable bd = new BitmapDrawable(mContext.getResources(), viewHolder.userImage.getDrawingCache())userUrl;
//you can check if the bd is null (if it is null I download image again -it is in cache- and I add blue trasparency like bellow
//R.drawable.blue is image with trasparency
LayerDrawable d = new LayerDrawable(new Drawable[] { bd, mContext.getResources().getDrawable(R.drawable.blue) });
viewHolder.userImage.setImageDrawable(d);
selectedElements[position] = true;
numElementi--;
}
} else {
String imgUserurl = userUrl;
Picasso.with(mContext).load(imgUserurl).placeholder(R.drawable.ll_friend_placeholder).into(viewHolder.userImage);
viewHolder.userImage.setDrawingCacheEnabled(true);
selectedElements[position] = false;
numElementi++;
}
}
});
...
}
public boolean[] getSelectedElements()
{
return selectedElements;
}
In my activity or fragment:
boolean[] selectedElement = adapter.getSelectedElements();
(I need position of selected element)