I have two button at bottom i.e after listview ends.
I am using a custom listview which display list items with alternate colors.
how to set setOnClickListener for both button at bottom?
public class PieMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRes = getResources();
new Random(new Date().getTime());
solbtn = (Button)findViewById(R.id.solution);
String recive ;
Bundle b = getIntent().getExtras();
final int piewrong=b.getInt("piewrong");
final int pieright=b.getInt("pieright");
final int pieunclick=b.getInt("pieunclick");
setContentView(R.layout.piechart_result);
recive = pieright+"/20";
mPie.setUnit(recive);
data1 = new ArrayList<String>();
fillData() ;
listtotal =getIntent().getStringArrayListExtra("listtotal");
timeuse =getIntent().getStringArrayListExtra("timeused");
adapter1 = new ListAdapter(this, data1, listtotal,timeuse);
ListView lvMain = (ListView) findViewById(R.id.list);
lvMain.setAdapter(adapter1);
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int questionno = position+1;
Bundle b = new Bundle();
b.putInt("questionno",questionno);
b.putInt("piewrong",piewrong);
b.putInt("pieright",pieright);
b.putInt("pieunclick",pieunclick);
Intent in=new Intent(PieMainActivity.this,Solution.class);
in.putStringArrayListExtra("listtotal", (ArrayList<String>) listtotal);
in.putStringArrayListExtra("timeused", (ArrayList<String>) timeuse);
in.putExtras(b);
startActivity(in);
finish();
}
});
}
void fillData() {
for (int i = 1; i <= 20; i++) {
data1.add("Question " + i);
}
}
void fillcmp() {
for (int i = 1; i <= 20; i++) {
cmp.add("cmp " + i);
}
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.staritsolutions.apptitude"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:layout_weight="1.0">
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<Button
android:id="#+id/home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Main Menu"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
<Button
android:id="#+id/solution"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Solutions"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
BaseAdapter file
public class ListAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
List<String> data1;
List<String> cmp;
List<String> timeused;
ListAdapter(Context context, List<String> data1 ,List<String> cmp ,List<String> timeused) {
ctx = context;
this.data1 = data1;
this.cmp = cmp;
this.timeused = timeused;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data1.size();
}
public int getCount1() {
return cmp.size();
}
#Override
public Object getItem(int position) {
return data1.get(position);
}
public Object getItem1(int position1) {
return cmp.get(position1);
}
#Override
public long getItemId(int position) {
return position;
}
public long getItemId1(int position1) {
return position1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.listitem, parent, false);
}
/*if (position % 2 == 0) {
view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
} else {
view.setBackgroundResource(R.drawable.artists_list_background_alternate);
}*/
TextView text = (TextView) view.findViewById(R.id.heading);
int no = position;
if(cmp.get(position).equals("GREEN"))
{
text.setTextColor(Color.parseColor("#00D50E"));
}else if(cmp.get(position).equals("RED"))
{
text.setTextColor(Color.parseColor("#e84040"));
}else
{
text.setTextColor(Color.parseColor("#B441E9"));
}
((TextView) view.findViewById(R.id.heading)).setText(data1.get(position));
((TextView) view.findViewById(R.id.duration)).setText(timeused.get(position));
return view;
//String.valueOf(value);
}
}
So these buttons are not part of your ListView? Well, than in your onCreate do something like:
solbtn = (Button)findViewById(R.id.solution);
solbth.setOnClickListener( toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourMethod();
}
});
And the same goes for the second button.
Or you can make your Activity implement View.OnClickListener, after doing this you can set your click listeners like this:
//this two lines in your OnCreate
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//somewhere later in the code
#Override
public void onClick(View v) {
//do something
}
Just add the clickListeners in your onCrete() method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
solbtn = (Button) findViewById(R.id.home);
homebtn = (Button) findViewById(R.id.solution);
solbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for solution button
}
});
homebtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for home button
}
});
.....
}
Related
In my Activity I have an EditText, a Button and a GridView. The user selects the image from the GridView and enters the name in the EditText, and then clicks the done button.
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="#+id/l1"
>
<View
android:layout_width="#dimen/btm_sht_line"
android:layout_height="#dimen/btm_sht_height"
android:layout_marginTop="#dimen/btm_top"
android:layout_gravity="center_horizontal"
android:background="#color/colorPrimaryDark"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/header_create_a_new_list"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textStyle="bold"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/l2"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/marin_top"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listname"
android:hint="#string/list_title_name"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="#dimen/marin_top"
android:layout_marginStart="#dimen/marin_top"
android:inputType="text"
android:autofillHints="#string/list_title_name" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/done"
android:src="#drawable/ic_check_circle"
android:layout_marginRight="15dp"
android:layout_marginEnd="#dimen/marin_top"
android:layout_marginLeft="#dimen/margin_left"
android:layout_marginStart="#dimen/margin_left"
tools:ignore="ContentDescription"
/> </LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/l3"
android:orientation="vertical"
>
<View style="#style/Divider"
android:layout_marginTop="#dimen/marin_top"
/>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/r1"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scroll"
><GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/gridview"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</ScrollView>
</RelativeLayout>
</LinearLayout>
I want to move the selected image and the entered text to another Activity
<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=".CheckslateHome">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:id="#+id/ima"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/getlistname"
android:text="hi welcome"
android:layout_below="#+id/ima"
/>
</RelativeLayout>
In my code when the user selects the image, before entering the name, it loads to a new empty window. Also I have 6 images in my drawable Folder and only 3 images are being displayed in the GridView.
Java class
public class NewListCreate extends BottomSheetDialogFragment {
Integer[] images={R.drawable.menu,R.drawable.musicbox,R.drawable.shoppingbag,R.drawable.shoppingcart,R.drawable.wallet,R.drawable.weddingdress};
GridView gridView;
ArrayList<imageModel> arrayList;
public NewListCreate() {}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.new_list_create, container, false);
ImageButton done = view.findViewById(R.id.done);
final EditText listname = (EditText) view.findViewById(R.id.listname);
final GridView gridView = (GridView) view.findViewById(R.id.gridview);
arrayList = new ArrayList<imageModel>();
for (int i = 0; i < images.length; i++) {
imageModel imagemodel = new imageModel();
imagemodel.setmThumbIds(images[i]);
//add in array list
arrayList.add(imagemodel);
}
final ImageAdapterGridView adapterGridView = new ImageAdapterGridView(getContext(), arrayList);
gridView.setAdapter(adapterGridView);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
adapterGridView.setSelectedPosition(i);
adapterGridView.notifyDataSetChanged();
int imageRes = images[i];
Intent intent = new Intent(getContext(),CheckslateHome.class);
intent.putExtra("IMAGE_RES", imageRes);
startActivity(intent);
}
});
return view;
}
}
AdapterClass
public class ImageAdapterGridView extends BaseAdapter {
private int selectedPosition = -1;
Context context;
ArrayList<imageModel> arrayList;
public ImageAdapterGridView(Context context, ArrayList<imageModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return arrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view==null)
{
view = LayoutInflater.from(context).inflate(R.layout.image_list, viewGroup, false);
}
ImageView imageView;
imageView = (ImageView) view.findViewById(R.id.image);
imageView.setImageResource(arrayList.get(i).getmThumbIds());
if (i == selectedPosition) {
view.setBackgroundColor(Color.WHITE);
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
return view;
}
public void setSelectedPosition(int position) {
selectedPosition = position;
}
}
what i was Looking was Something Like this
[![enter image description here][1]][1]
Copy and paste this hope it solve ur Problem
public class NewListCreate extends BottomSheetDialogFragment {
int[] images={R.drawable.menu,R.drawable.musicbox,R.drawable.shoppingbag,R.drawable.shoppingcart,R.drawable.wallet,R.drawable.weddingdress};
int imageRes = images[0];
public NewListCreate() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_list_create, container, false);
ImageButton done = view.findViewById(R.id.done);
final EditText listname = (EditText) view.findViewById(R.id.listname);
final GridView gridView = (GridView) view.findViewById(R.id.gridview);
final CustomAdpter customAdpter = new CustomAdpter(images,getContext());
gridView.setAdapter(customAdpter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
customAdpter.selectedImage = i;
customAdpter.notifyDataSetChanged();
imageRes = images[i];
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemname = listname.getText().toString();
if (!TextUtils.isEmpty(listname.getText().toString())) {
startActivity(new Intent(getContext(), CheckslateHome.class).putExtra("data", itemname).putExtra("image",imageRes));
dismiss();
} else {
Toast.makeText(getContext(), "List Name not Empty ", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
public class CustomAdpter extends BaseAdapter{
private int[] icons;
private Context context;
private LayoutInflater layoutInflater;
public int selectedImage = 0;
public CustomAdpter(int[] icons, Context context) {
this.icons = icons;
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null)
{
view = layoutInflater .inflate(R.layout.image_list,viewGroup,false);
}
ImageView imageicons = view.findViewById(R.id.image);
if (i < icons.length) {
imageicons.setImageResource(icons[i]);
if (i != selectedImage) {
imageicons.setImageAlpha(50);
}
imageicons.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageicons.setLayoutParams(new GridView.LayoutParams(150, 150));
if (i == selectedImage) {
view.setBackgroundColor(Color.WHITE);
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
};
return view;
}
}
I think what you're looking for is passing data through navigation.
It will allow you send your image and name data from one activity/fragment to the next one.
Check out data-binding as well, might be useful.
I have a custom list view with layout contain two layouts, called upper and bottom.
upper layout contain spinner, set and remove buttons.
bottom layout contain text view and back button.
By default bottom layout is in GONE state and when the user clicks on set button upper layout is GONE and bottom is VISIBLE (clicking on back button in bottom layout will return upper bottom back).
my problem is spinner value is disappear after specific flows:
Flow 1:
Add two items
Click on SET button on the first item
Remove the second item
Click on 'Back' button on the first item
Flow 2:
Click on SET
Rotate screen
Click on Back
Just to be clear, spinner values are exist and if drop it down you'll found the names (and I have android:configChanges="keyboardHidden|orientation|screenSize" in my manifest).
So, why spinner value is disappear after those flows ?
Here is my code:
Names.java
public class Names
{
private String name;
private int nameIndex;
private Boolean isNameOnTop;
public Names()
{
name = "";
isNameOnTop = true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNameIndex() {
return nameIndex;
}
public void setNameIndex(int nameIndex) {
this.nameIndex = nameIndex;
}
public Boolean getIsNameOnTop() {
return isNameOnTop;
}
public void setIsNameOnTop(Boolean isNameOnTop) {
this.isNameOnTop = isNameOnTop;
}
}
MainActivity.Java
public class MainActivity extends Activity
{
ArrayList<Names> namesArray = new ArrayList<>();
ListView lvNames;
ListviewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvNames = (ListView) findViewById(R.id.listView);
adapter = new ListviewAdapter(this, namesArray);
lvNames.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add)
{
namesArray.add(new Names());
adapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
}
ListviewAdapter.java
public class ListviewAdapter extends BaseAdapter
{
public Activity context;
public LayoutInflater inflater;
private ArrayList<Names> namesID;
private boolean isDeleted;
public ArrayList<Names> getNamesID() {
return namesID;
}
public void setNamesID(ArrayList<Names> namesID) {
this.namesID = namesID;
}
// Constructor
public ListviewAdapter(Activity context, ArrayList<Names> names)
{
super();
setNamesID(names);
this.context = context;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return getNamesID().size();
}
#Override
public Names getItem(int position) {
return getNamesID().get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder
{
RelativeLayout relativeLayout_Upper;
RelativeLayout relativeLayout_Bottom;
Spinner spNames;
Button btn_set, btn_remove, btn_back;
TextView tvChosen;
int index;
}
#Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_row, null);
holder.relativeLayout_Upper = (RelativeLayout) view.findViewById(R.id.lvRow_upper_layout);
holder.relativeLayout_Bottom = (RelativeLayout) view.findViewById(R.id.lvRow_bottom_layout);
holder.spNames = (Spinner) view.findViewById(R.id.spNames);
holder.btn_set = (Button) view.findViewById(R.id.btn_set);
holder.btn_remove = (Button) view.findViewById(R.id.btn_remove);
holder.btn_back = (Button) view.findViewById(R.id.btn_back);
holder.tvChosen = (TextView) view.findViewById(R.id.tv_chosen);
view.setTag(holder);
}
else
holder = (ViewHolder) view.getTag();
holder.index = i;
if (isDeleted)
{
holder.spNames.setSelection(getItem(holder.index).getNameIndex());
holder.tvChosen.setText("Chosen: " + getItem(holder.index).getName());
if (getItem(holder.index).getIsNameOnTop())
{
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
}
else
{
holder.relativeLayout_Upper.setVisibility(View.GONE);
holder.relativeLayout_Bottom.setVisibility(View.VISIBLE);
}
}
// pop spinner names
String[] names = new String[]{"Tom", "Ben", "Gil", "Adam", "Moshe", "Adi", "Michael", "Yasmin", "Jessica", "Caroline", "Avi", "Yael"};
final ArrayAdapter<String> spNamesAdapter = new ArrayAdapter<String>
(view.getContext(), android.R.layout.simple_spinner_dropdown_item, names);
spNamesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spNames.setAdapter(spNamesAdapter);
holder.spNames.setSelection(getItem(holder.index).getNameIndex());
holder.spNames.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//holder.spNames.setTag(position);
getItem(holder.index).setNameIndex(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.btn_set.setTag(i);
holder.btn_set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getItem(holder.index).setName(holder.spNames.getSelectedItem().toString());
int position = (Integer) v.getTag();
holder.tvChosen.setText("Chosen: " + getItem(position).getName());
holder.relativeLayout_Upper.setVisibility(View.GONE);
holder.relativeLayout_Bottom.setVisibility(View.VISIBLE);
getItem(holder.index).setIsNameOnTop(false);
}
});
// remove
holder.btn_remove.setTag(i);
holder.btn_remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
namesID.remove(position);
notifyDataSetChanged();
isDeleted = true;
}
});
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
}
});
return view;
}
}
activity_main.xml: contain ListView only.
upper_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spNames" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SET"
android:id="#+id/btn_set" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REMOVE"
android:id="#+id/btn_remove" />
</LinearLayout>
bottom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Chosen:"
android:id="#+id/tv_chosen"
android:layout_marginRight="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BACK"
android:id="#+id/btn_back" />
</LinearLayout>
listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvRow_upper_layout">
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/upper_view"
android:id="#+id/includeRow_register"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
</RelativeLayout>
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvRow_bottom_layout"
android:visibility="gone">
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/bottom_view"
android:id="#+id/includeRow_showData"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
</RelativeLayout>
</LinearLayout>
In your ListviewAdapter, change:
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
}
});
to:
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
notifyDataSetChanged();
// OR you can use this
// holder.spNames.requestLayout();
}
});
Whenever you click on "Add" in the method onOptionsItemSelected() you add an object new names() into the list, and in the Names class, the value of attribute name is set to ""
I guess that's why you getting an empty item in the spinner.
I currently have ListFragment with a ArrayAdapter class
The codes are below.
1)I want to implement a checkbox from listview main xml to check all the checkboxes that are present in custom list row xml which is inflated using Array adapter.
2)how to refresh view in this code by clearing all checkboxes when a button is clicked.
listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
android:background="#fff2fff2" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="10"
android:choiceMode="multipleChoice" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
/>
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="#+id/btnin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In" />
<Button
android:id="#+id/btndelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/checkAll"
android:checked="false" />
</LinearLayout>
</RelativeLayout>
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/paackage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent">
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Adapter class
public class FileAdapter extends ArrayAdapter<String>{
private List<String> filelist = null;
private Context context;
CheckBox checkAll;
public FileAdapter(Context _context, int _resource,List<String> _filelist) {
super(_context,_resource,_filelist);
this.context = _context;
this.filelist = _filelist;
this.itemChecked = new boolean[_filelist.size()];
}
private class ViewHolder {
TextView Name;
TextView pName;
CheckBox ck1;
ImageView iconview;
}
#Override
public int getCount() {
return ((null != filelist) ? filelist.size() : 0);
}
#Override
public String getItem(int position) {
return ((null != filelist) ? filelist.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder();
holder.Name = (TextView) view.findViewById(R.id.name);
holder.pName = (TextView) view
.findViewById(R.id.paackage);
holder.ck1 = (CheckBox) view.findViewById(R.id.checkBox1);
holder.iconview = (ImageView) view.findViewById(R.id.app_icon);
view.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.appName.setText();
holder.packageName.setText();
holder.iconview.setImageDrawable();
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
holder.ck1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
} else {
itemChecked[position] = false;
}
}
});
return view;
}
}
ListFragment class
public class FragmentA extends ListFragment implements View.OnClickListener {
public ArrayList<String> filelist;
Button in, delete;
ListView lv;
CheckBox cb;
private FileAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filelist = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View inflatedView = inflater.inflate(R.layout.fragment_app_restore, container, false);
in = (Button) inflatedView.findViewById(R.id.btnin);
delete= (Button) inflatedView.findViewById(R.id.btndelete);
lv = (ListView) inflatedView.findViewById(android.R.id.list);
empty = inflatedView.findViewById(android.R.id.empty);
//calling asynctask to load files here
delete.setOnClickListener(this);
in.setOnClickListener(this);
return inflatedView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
cb = (CheckBox) v.findViewById(R.id.checkBox1);//this is the checkbox in row only
cb.performClick();
if (cb.isChecked()) {
} else {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btndelete:
break;
case R.id.btnin:
break;
}
}
private class LoadFiles extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
filelist = GetFiles(root_path);
if (filelist != null) {
listadaptor = new AppRestoreFileAdapter(getActivity(),
R.layout.custom_row, filelist);
} else {
// lv.setEmptyView(empty);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
lv.setAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
}
}
I have prepared custom Listview in that i want to select one item from view so for that i have used RadioButton view for single choice item,but i customized it.Following is my total code ,because there may be error in the layout so please help me in solving this.
Activity:-
public class MainActivity extends Activity {
TextView tvEmpty;
ListView listView;
Spinner spnStage;
Button btnGet;
String sfrom;
ArrayList<String> arrayList;
StartFromAdapter arrayAdapter;
String[] stages = { "School", "Collage", "Office" };
String resultdata = "{\"Age\":{\"School\":[{\"Stage\":\"class1\",\"Name\":\"Classname1\"},{\"Stage\":\"class2\",\"Name\":\"ClassName2\"}],\"Collage\":[],\"Office\":[{\"Stage\":\"Office1\",\"Name\":\"Officename1\"},{\"Stage\":\"Office2\",\"Name\":\"Officename2\"}]}}";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvEmpty = (TextView) findViewById(R.id.emptytv);
listView = (ListView) findViewById(R.id.lstDemo);
spnStage = (Spinner) findViewById(R.id.spinner1);
btnGet = (Button) findViewById(R.id.button1);
ArrayAdapter<String> stageAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_spinner_item, stages);
stageAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStage.setAdapter(stageAdapter);
arrayList = new ArrayList<String>();
spnStage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
if (arrayList.size() > 0 && arrayList != null) {
arrayList.clear();
}
loadListView(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = (Integer) v.getTag();
Log.i("SELECTED IN GET", "" + selectedPosition);
}
});
}
public void loadListView(String selectedItem) {
try {
JSONObject jObject = new JSONObject(resultdata);
JSONObject jAge = jObject.getJSONObject("Age");
JSONArray jSelectedItem = jAge.getJSONArray(selectedItem);
if (jSelectedItem.length() != 0) {
for (int i = 0; i < jSelectedItem.length(); i++) {
JSONObject jObj = jSelectedItem.getJSONObject(i);
arrayList.add(jObj.getString("Name"));
}
}
arrayAdapter = new StartFromAdapter(this, arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setEmptyView(tvEmpty);
Log.i("BEFORE LISTVIEW ONCLICK", "THIS IS ADDRESSLIST");
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
sfrom = ((RadioButton) v.findViewById(R.id.startfromrb))
.getText().toString();
Log.i("STARTFROM", sfrom);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Adapter:-
public class StartFromAdapter extends BaseAdapter {
ArrayList<String> detailsArrayList;
Context context;
int selectedPosition = 0;
public StartFromAdapter(Context context, ArrayList<String> detailsArrayList) {
this.detailsArrayList = detailsArrayList;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return detailsArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return detailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowLayout = null;
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.listitem_view, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
RadioButton rbStartFrom = (RadioButton) rowLayout
.findViewById(R.id.startfromrb);
rbStartFrom.setChecked(position == selectedPosition);
rbStartFrom.setTag(position);
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
rbStartFrom.setText(detailsArrayList.get(position));
return rowLayout;
}
}
MAINLAYOUT:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
listitem_view:-
<?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:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/startfromrb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:focusable="false"
android:focusableInTouchMode="false"
android:lines="3"
android:paddingLeft="20dp"
android:text="RadioButton" />
</LinearLayout>
Update use code as per below
// On item click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long itemId) {
RadioButton btn=(RadioButton) view.findViewById(R.id.startfromrb);
String sfrom = btn.getText().toString();
arrayAdapter.setSelected((int)itemId);
Log.i("STARTFROM", sfrom);
}
});
//Add below function in adapter class
public void setSelected(int selectedPosition){
this.selectedPosition=selectedPosition;
notifyDataSetChanged();
}
Also remove from adapter
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
And add android:clickable="false" and set selectedPosition to -1 by default
The first I see is, that You have to change the reference to the Views where You want to set the other views below :
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
But anyway, Your TextView is sitten directly above the listView, is this Your intention? If not, You have to set
android:layout_below="#+id/lstDemo"
Also, if You get any errors, please post the logcat output. If You just have problems with Your layout, please explain clear enough what exactly You want.
EDIT
try to get the selected item String like this:
final String item = (String) parent.getItemAtPosition(position);
loadListView(item);
I have a problem syncing the list items isChecked state with the checkboxes that in the same raw. I am able to set the 'checked' state in list items but can't figure how to set the 'checked' state of the CheckBoxes. I thought mainListView.setItemChecked should do the work but it doesn't.
This is the code i'm using:
public class Reservation_Activity extends ListActivity {
int total=0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reservation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total=0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_multiple_choice,lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if(mainListView.isItemChecked(position))
{
mainListView.setItemChecked(position, false);
total = total - item._price;
} else {
mainListView.setItemChecked(position, true);
total += item._price;
}
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total=0;
// user has clicked clear button so uncheck all the items
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id=0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id,todolistXml.getAttributeValue(null, "title"), Integer.parseInt(todolistXml.getAttributeValue(null, "price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
public MyAdapter(Context context, int textViewResourceId,
name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_raw_resevation, parent, false);
TextView name,price;
CheckBox ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price)
{
this._id=id;
this._name = name;
this._price = price;
}
public name_price() {
// TODO Auto-generated constructor stub
}
}
I think I should change the checked state of the specific checkbox in mainListView.setOnItemClickListener according to this but I can't find a way to do it.
in addition, This is the raw layout and the list layout (of others to use):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<LinearLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<TextView
android:id="#+id/res_name"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:gravity="center|left"
android:singleLine="true"
android:text="lalalalalalalalalallaallllaaaa"
android:textColor="#ffffff" />
<TextView
android:id="#+id/res_price"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginRight="10dp"
android:gravity="center"
android:text="90"
android:textColor="#ffffff"
android:textSize="15dp" />
</LinearLayout>
<CheckBox android:text=""
android:id="#+id/UpdateCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
</LinearLayout>
List layout:
<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#81BEF7"
android:scrollbars="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout" android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:height="32dp" android:gravity="left|top" android:background="#2B60DE"
android:paddingTop="2dp" android:paddingBottom="2dp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout2" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="left|center_vertical"
android:layout_width="wrap_content" android:layout_gravity="left|center_vertical">
<TextView android:id="#+id/total_sum" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textStyle="bold"
android:textColor="#FFFFFF" android:text="#string/list_header"
android:textSize="15sp" android:gravity="center_vertical"
android:paddingLeft="5dp">
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout22" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="right"
android:layout_width="fill_parent" android:layout_gravity="right|center_vertical">
<Button android:id="#+id/btnSave" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Send" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
<Button android:id="#+id/btnClear" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Clear" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
</LinearLayout>
</LinearLayout>
<TableLayout android:id="#+id/TableLayout01" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<ListView android:id="#android:id/list" android:layout_width="wrap_content"
android:textColor="#000000" android:layout_height="wrap_content">
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
Thanks!
Y
Good morning, I understand this should solve your problem:
public class Reservation_Activity extends ListActivity {
int total = 0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_raw_resevation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total = 0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_multiple_choice, lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
name_price item = (name_price) mainListView
.getItemAtPosition(position);
if (mainListView.isItemChecked(position)) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,
mainListView.isItemChecked(position));
item.ckbx.setChecked(mainListView.isItemChecked(position));
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total = 0;
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id = 0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id, todolistXml.getAttributeValue(null, "title"),Integer.parseInt(todolistXml.getAttributeValue(null,"price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
View row;
CheckBox ckbx;
public MyAdapter(Context context, int textViewResourceId,name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.reservation, parent, false);
TextView name, price;
ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
ckbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if (ckbx.isChecked()) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,ckbx.isChecked());
total_tv.setText("Total: " + total);
}
});
items[position].setCkbx(ckbx);
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
and:
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price) {
this._id = id;
this._name = name;
this._price = price;
}
public void setCkbx(CheckBox ckbx) {
this.ckbx = ckbx;
}
}