I have ListView and it include 2 EditTextI want to initialize 6 empty EditText when activity started.How can I do that?
I can not add list null Model and set it so I dont know how can i handle it.
This is listview_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/SerialNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:ellipsize="end"
android:padding="5dp"
android:singleLine="true">
<requestFocus />
</EditText>
<EditText
android:id="#+id/countItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:padding="5dp"
android:singleLine="true"
android:inputType="number">
</EditText>
This is my layout;
activity_reader.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content""
android:text="btn" />
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="#null" />
</GridLayout>
Here is the ListView Adapter;
public class ListViewAdapter extends BaseAdapter {
public ArrayList<Model> productList;
Activity activity;
ViewHolder holder;
public ListViewAdapter(Activity activity, ArrayList<Census> productList) {
super();
this.activity = activity;
this.productList = productList;
}
#Override
public int getCount() {
return productList.size();
}
#Override
public Object getItem(int position) {
return productList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
EditText SerialNumber;
EditText countItem;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
holder = new ViewHolder();
holder.SerialNumber = (EditText) convertView.findViewById(R.id.SerialNumber );
holder.countItem = (EditText) convertView.findViewById(R.id.countItem );;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.SerialNumber.addTextChangedListener(new TextWatcher() { #Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
holder.SerialNumber.requestFocus();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
holder.censusRowSerialNumber.requestFocus();
}
#Override
public void afterTextChanged(Editable s) {
//holder.countItem.requestFocus();
}
});
Model item = productList.get(position);
holder.SerialNumber.setText(item.getID().toString());
holder.countItem.setText(String.valueOf(item.getQuantity()));
return convertView;
}
}
Here is the Activity;
public class ReaderActivity extends AppCompatActivity {
EditText countItem,SerialNumber;
private ArrayList<Model> csList;
Model item;
ListViewAdapter adapter;
ListView lview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
csList = new ArrayList<Model>();
lview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(this, csList);
SerialNumber= findViewById(R.id.SerialNumber);
countItem = findViewById(R.id.countItem );
lview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
For achieving CRUD operations, its good to go with Custom Layouts.
For instance a LinearLayout, who's default layout is already defined. Now according to runtime requirement/parameters you can add/edit/delete all these. For which the logic can be completely yours. This is handy than creating a static view and manipulating.
Let me show you custom layouts preparation and adding into a rootiew. I have given example where layout landing_hori_view is having an EditText and Button
public class LandingHorizontalView extends LinearLayout implements View.OnClickListener{
public LandingHorizontalView(Context context){
super(context);
initialize();
}
public LandingHorizontalView(Context context, ModelClassObject modelObject,ButtonClicked listener){
super(context);
mTypeContent = modelObject;//If you want to pass some params for population
mListener = listener;
initialize();
}
private void initialize(){
View view = LayoutInflater.from(getContext()).inflate(R.layout.landing_hori_view, this, true);
EditText edtOne =findViewById(R.id.txt_price_list);
Button button= findViewById(R.id.btn_place_order);
button.setTag(count);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v instanceof Button){
int count = (int) v.getTag();
mListener.onButtonClicked(count);
}
}
public interface ButtonClicked{
public void onButtonClicked(int index);
}
}
In your parent activity, implement the interface (here ButtonClicked) and handle click events/manipulating UI etc
#Override
public void onButtonClicked(int index) {
}
Now coming to , how to add these to parent layout, create a ScrollView and include one LinearLayout to which LandinghorizontalView will be added.
Below shows content of my parent Activity
<ScrollView
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#android:color/white"
app:layout_constraintTop_toBottomOf="#id/guideline"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/landingScrollLinearView"
>
</LinearLayout>
Now for adding this vew , the following can be done.
LandingHorizontalView horizontalView=new LandingHorizontalView(getActivity(),modelObject,this);
mScrollLinearView.addView(horizontalView);
Now as per your comment, create few LandingHorizontalView and add
to root. Now according to your logic/user interaction , keep on
modifying mScrollLinearView
Related
I know here we have a lot of questions like mine, but I don't know why none works for me.
My objective: I have an AlertDialog with a ListView with a check box in each row, I can select some of the items, and I wish to make an ArrayList with the elements selected.
For that reason, I'm calling the SetOnclickListener, I put a Log inside the method, but does nothing.
I tried with focusable and clickable almost everywhere, but my Log doesn't appear.
Here My alert Dialog
private void callAdditionalDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(ConfigProductActivity.this);
final View additionalView = layoutInflater.inflate(R.layout.dialog_additional, null);
additionalView.setFocusable(true);
// set the custom dialog components - text, buttons, accountants
TextView titleDialog = (TextView) additionalView.findViewById(R.id.title_additional);
titleDialog.setTypeface(boldFont);
Button buttonAccept = (Button) additionalView.findViewById(R.id.button_accept);
buttonAccept.setTypeface(boldFont);
Button buttonCancel = (Button) additionalView.findViewById(R.id.button_cancel);
buttonCancel.setTypeface(boldFont);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ConfigProductActivity.this);
alertDialogBuilder.setView(additionalView);
final AlertDialog alertD = alertDialogBuilder.create();
alertD.setCanceledOnTouchOutside(false);
//Fill object of additional
final ListView additionalListView = (ListView) additionalView.findViewById(R.id.list_additional);
TextView additionalNotFound = (TextView) additionalView.findViewById(R.id.additional_not_found);
if (!withoutModifiers){
additionalAdapter = new AdditionalAdapter(ConfigProductActivity.this, additionalList);
additionalListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
additionalListView.setAdapter(additionalAdapter);
final ArrayList<ModifierEntity> modifierList = new ArrayList<ModifierEntity>();
additionalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Object modifier = additionalListView.getAdapter().getItem(position).toString();
Log.d(TAG, "SOMETHIIIIING");
}
});
}
else{
additionalListView.setVisibility(View.GONE);
additionalNotFound.setVisibility(View.VISIBLE);
additionalNotFound.setTypeface(font);
buttonCancel.setVisibility(View.GONE);
}
//End of fill object of additional
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
buttonAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//additional.setText(additionalAdapter.getCount());
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
alertD.show();
}
Here my adapter:
public class AdditionalAdapter extends ArrayAdapter {
private static String TAG = AdditionalAdapter.class.getName();
private List<ModifierEntity> originalData = null;
private ConfigProductActivity activity;
private Typeface font;
private Typeface boldFont;
private static ModifierEntity modifier;
public AdditionalAdapter (ConfigProductActivity activity, List<ModifierEntity> listArray){
super(activity, R.layout.additional_item);
this.activity = activity;
this.originalData = listArray ;
font = Typeface.createFromAsset(activity.getAssets(),"HelveticaNeueThn.ttf");
boldFont = Typeface.createFromAsset(activity.getAssets(), "avgardm.ttf");
}
public static class Row
{
public TextView labelName;
public TextView labelPrice;
public CheckBox check;
}
#Override
public int getCount() {
return originalData.size();
}
#Override
public ModifierEntity getItem(int position) {
return originalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int colorFont = activity.getResources().getColor(R.color.brown_tataki);
final Row holder;
View rowView = convertView;
// reuse views
if (convertView == null) {
holder = new Row();
LayoutInflater inflater = LayoutInflater.from(activity);
rowView = inflater.inflate(R.layout.additional_item, null);
rowView.setClickable(true);
//rowView.setFocusable(false);
// configure view holder
holder.labelName = (TextView) rowView.findViewById(R.id.additional_name);
holder.labelPrice = (TextView) rowView.findViewById(R.id.additional_price);
holder.check = (CheckBox) rowView.findViewById(R.id.additional_check);
rowView.setTag(holder);
}
else {
holder = (Row) convertView.getTag();
// rowView.setClickable(true);
}
final ModifierEntity itm = originalData.get(position);
holder.labelName.setText(itm.getModifier_name());
holder.labelName.setTypeface(font);
holder.labelName.setTextColor(colorFont);
holder.labelPrice.setText(GlobalParameters.CURRENCY.concat(String.valueOf(itm.getModifier_cost())));
holder.labelPrice.setTypeface(boldFont);
holder.labelPrice.setTextColor(colorFont);
return rowView;
}
}
Here My Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange_tataki"
android:text="#string/additional_title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:id="#+id/title_additional"
android:padding="5dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title_additional"
android:gravity="center"
android:background="#color/white"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_additional"
android:divider="#color/brown_tataki"
android:dividerHeight="0.5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/list_additional"
android:gravity="center"
android:padding="10dp"
android:visibility="gone"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_not_found"
android:text="#string/additional_not_found"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttons"
android:layout_marginBottom="10dp"
android:layout_below="#+id/additional_not_found"
android:gravity="center"
android:layout_marginTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/button_cancel"
android:background="#color/green_tataki"
android:text="#string/button_cancel"
android:textSize="15sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_accept"
android:padding="10dp"
android:background="#color/green_tataki"
android:text="#string/button_accept"
android:textSize="15sp"
android:layout_marginLeft="15dp"
/>
</LinearLayout>
</RelativeLayout>
And Here my item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="QUESO"
android:singleLine="true"
android:padding="10dp"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/additional_price"
android:padding="10dp"
android:text="Bs. 500"
android:textColor="#color/brown_tataki"
android:layout_toRightOf="#id/additional_name"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="#+id/additional_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp" />
Using interfaces I can solve my problem, this link provided me the solution, and bassically consist in create an interface and implement in my activity.
Like this:
1.- Interface
public interface MyListener {
void folderClicked();
}
2.- Implements the interface in the activity
public class ActivityA extends Activity implements MyListener
3.- You will have to auto override the method folderClicked it will look like this:
#Override
protected void folderClicked() {
// Do your stuff here.
}
4.- Send the activity listener to the adapter with constructor like this:
MyAdpater adapter = new MyAdpater(ActivityA.this);
5.- Your adapter class your code should be like this:
public class TimeLineAdapter extends BaseAdapter {
private MyListener mListener;
public TimeLineAdapter(MyListener listener) {
super();
mListener = listener;
}
holder.iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onFolderClicked()
//code to do stuff when the image is clicked
}
I'm trying to implement Custom ListView (i.e. ListView with custom Adapter) with Search Box, for that I have written the following XML code--
<LinearLayout 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:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="20dp"
android:layout_weight="1" />
</LinearLayout>
My MenuListActivity code is---
public class MenuListActivity extends Activity
{
ListView list;
TextView txtInputSearch;
MenuListAdapter adapter;
public MenuListActivity CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_list);
CustomListView = this;
setListData();
Resources res =getResources();
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
list= ( ListView )findViewById( R.id.list ); // List defined in XML ( See Below )
adapter=new MenuListAdapter( CustomListView, CustomListViewValuesArr,res );
list.setAdapter( adapter );
txtInputSearch.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
String text = txtInputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3)
{
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
});
}
public void setListData()
{
for (int i = 0; i < 11; i++)
{
final ListModel objListModel = new ListModel();
objListModel.setMenu("Company "+i);
objListModel.setPrice("com.androidexample.customlistview:drawable/rihanna");
// sched.setUrl("http:\\www."+i+".com");
CustomListViewValuesArr.add(objListModel);
}
}
public void onItemClick(int mPosition)
{
ListModel tempValues = ( ListModel ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
Toast.makeText(CustomListView,"Clicked",Toast.LENGTH_LONG).show();
}
}
See my Adapter class Below--
public class MenuListAdapter extends BaseAdapter implements OnClickListener
{
private Activity activity;
private ArrayList data;
private ArrayList<ListModel> arrayList;
private static LayoutInflater inflater=null;
public Resources res;
ListModel tempValues=null;
int i=0;
public MenuListAdapter(Activity paramActivity, ArrayList paramDataList, Resources paramResource)
{
activity = paramActivity;
data=paramDataList;
res = paramResource;
arrayList=new ArrayList<ListModel>();
arrayList.addAll(data);
inflater = ( LayoutInflater )activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public static class ViewHolder
{
public TextView item_name;
public TextView item_price;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.menu_list_row, null);
holder = new ViewHolder();
holder.item_name = (TextView) vi.findViewById(R.id.item_name);
holder.item_price=(TextView)vi.findViewById(R.id.item_price);
// holder.image=(ImageView)vi.findViewById(R.id.list_image);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.item_name.setText("No Data");
}
else
{
tempValues=null;
tempValues = ( ListModel ) data.get( position );
holder.item_name.setText( tempValues.getMenu() );
holder.item_price.setText( tempValues.getPrice());
/* holder.image.setImageResource(
res.getIdentifier(
"com.androidexample.customlistview:drawable/"+tempValues.getImage()
,null,null));*/
vi.setOnClickListener(new OnItemClickListener( position ));
}
return vi;
}
public void onClick(View v)
{
Log.v("CustomAdapter", "=====Row button clicked=====");
}
private class OnItemClickListener implements OnClickListener
{
private int mPosition;
OnItemClickListener(int position)
{
mPosition = position;
}
public void onClick(View arg0)
{
MenuListActivity sct = (MenuListActivity)activity;
sct.onItemClick(mPosition);
}
}
// Filter Class
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0)
{
data.addAll(arrayList);
}
else
{
for (ListModel lm : arrayList)
{
if (lm.getMenu().toLowerCase(Locale.getDefault()).contains(charText))
{
data.add(lm);
}
}
}
notifyDataSetChanged();
}
}
In design mode, when I clicks on Graphical Layout It is showing me proper/expected view (i.e. Search box to the Top and ListView Below to the search Box) but when I run my application then it is showing only ListView and SearchBox (EditText) is invisible. Please Help.
Change listview layout height to android:layout_height="0dp" instead of android:layout_height="fill_parent"
<LinearLayout 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:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginTop="20dp"
android:layout_weight="1" />
</LinearLayout>
Edit Use RelativeLayout instead of LinearLayout as
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:completionThreshold="1"
android:singleLine="true"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:layout_weight="1"
android:layout_below="#+id/txtInputSearch"
android:drawSelectorOnTop="false"/>
</RelativeLayout>
Edit
Use EditText in your code instead of TextView ,So change
TextView txtInputSearch;
to
EditText txtInputSearch;
And
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
to
txtInputSearch=(EditText )findViewById(R.id.txtInputSearch);
The problem is that you are adding a weight into you ListView which would take all the space of your layout, instead dont put any weight on it just simply wrap its height and remove the android:layout_weight="1"
sample:
<?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_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />
</LinearLayout>
problem:
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
You are casting it to a TextView not an EditText.
change it to this:
EditText txtInputSearch;
txtInputSearch=(EditText)findViewById(R.id.txtInputSearch);
I've got a ListView with a customer ArrayAdapter and a custom ListItem-XML. At the bottom of this ListView I've added a FooterView with a Button. Now I want to get all the values of the three EditTexts in each of my ListItems when I click this Button.
Here below is my code:
activity_checklistresult.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">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
result_inner_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/tv_result_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/default_margin" />
<EditText
android:id="#+id/et_result_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/default_margin"
android:inputType="number" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/tv_result_product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="end"
android:layout_margin="#dimen/default_margin" />
<AutoCompleteTextView
android:id="#+id/actv_search_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:singleLine="true"
android:ellipsize="end"
android:layout_margin="#dimen/default_margin"
android:inputType="textAutoComplete" />
</LinearLayout>
<TextView
android:id="#+id/tv_result_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/default_margin" />
<EditText
android:id="#+id/et_result_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/default_margin"
android:inputType="numberDecimal" />
</LinearLayout>
ResultListActivity.java:
public class ChecklistResultActivity extends ListActivity
{
private MyResultAdapter adapt;
private Button confirmButton;
private ChecklistResultActivity rActivity;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklistresult);
// Set my Custom ArrayAdapter for this ListActivity
setAdapter();
rActivity = this;
}
private void setAdapter(){
adapt = new MyResultAdapter(this, R.layout.result_inner_view, Controller.getInstance().getOrderedProducts());
setListAdapter(adapt);
// Add the confirm button at the end of the list
addFooterConfirmButton();
}
private void addFooterConfirmButton(){
ListView lv = (ListView)findViewById(android.R.id.list);
FrameLayout footerLayout = (FrameLayout) getLayoutInflater().inflate(R.layout.result_footer_view, null);
confirmButton = (Button)footerLayout.findViewById(R.id.confirm_result_button);
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// Get all EditText values (and compare them with the Default Value)
}
});
lv.addFooterView(footerLayout);
}
...
MyResultAdapter.java:
public class MyResultAdapter extends ArrayAdapter<OrderedProduct>
{
private Context context;
private int layoutResourceId;
private LayoutInflater inflater;
public MyResultAdapter(Context c, int layoutResourceId, List<OrderedProduct> objects){
super(c, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.context = c;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
if(view == null)
view = inflater.inflate(layoutResourceId, parent, false);
...
return view;
}
}
In the ResultListActivity at // Get all EditText values (and compare them with the Default Value) I want to loop through all the OrderedProducts and compare the default values of those, with the new filled-in values of the two EditTexts and the AutoCompleteTextView. So how can I get those values from within the onClick of the Footer-Button?
Thanks in advance for the responses.
Your adapter has to save text on change for each created EditText :
create a map to save values
Define and set a generic TextWatcher for every EditText
set a Tag on the editText (using its position or any
id you want) we'll use this tag as the key in the hashMap
create a method to retrieve the value for a given EditText
Adapter :
public class MyResultAdapter extends ArrayAdapter<OrderedProduct>
{
...
private HashMap<String, String> textValues = new HashMap<String, String>();
...
public ViewView getView(int position, View convertView, ViewGroup parent){
View view = convertView;
boolean convertViewWasNull = false;
if(view == null){
view = inflater.inflate(layoutResourceId, parent, false);
convertViewWasNull = true;
}
myEditText1 = findViewById...
myEditText2 = findViewById...
if(convertViewWasNull ){
//be aware that you shouldn't do this for each call on getView, just once by listItem when convertView is null
myEditText1.addTextChangedListener(new GenericTextWatcher(myEditText1));
myEditText2.addTextChangedListener(new GenericTextWatcher(myEditText2));
}
//whereas, this should be called on each getView call, to update view tags.
myEditText1.setTag("theFirstEditTextAtPos:"+position);
myEditText2.setTag("theSecondEditTextAtPos:"+position);
}
private class GenericTextWatcher implements TextWatcher{
private View view;
private GenericTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
String text = editable.toString();
//save the value for the given tag :
MyResultAdapter.this.textValues.put(view.getTag(), editable.toString());
}
}
//you can implement a method like this one for each EditText with the list position as parameter :
public String getValueFromFirstEditText(int position){
//here you need to recreate the id for the first editText
String result = textValues.get("theFirstEditTextAtPos:"+position);
if(result ==null)
result = "default value";
return result;
}
public String getValueFromSecondEditText(int position){
//here you need to recreate the id for the second editText
String result = textValues.get("theSecondEditTextAtPos:"+position);
if(result ==null)
result = "default value";
return result;
}
}
You can store all edittext values and get them when needed, you can store it in afterTextChange or onTextChange, it's up to you.
public class MyResultAdapter extends ArrayAdapter<OrderedProduct>{
...
private final String[] valueList;
public MyResultAdapter(Context c, int layoutResourceId, List<OrderedProduct> objects){
super(c, layoutResourceId, objects);
...
valueList = new String[objects.size()];
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
if(view == null)
view = inflater.inflate(layoutResourceId, parent, false);
...
//for edittext add text watcher listener
final pos = position;
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
valueList[pos] = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
public String[] getValueList(){
return valueList;
}
}
I have button, which on clicked displays a listview and on clicking the listview item it must print something on logcat. I implemented this one in such a way that the list view and its listener are present inside the button onclick listener.
All is working well except the listview listener is not getting called(i.e. nothing is printing on logcat when clicked on listview item)
Here is my listener.
public class MyClickListener implements View.OnClickListener {
LinearLayout parent;
LayoutInflater layoutInflater;
Context context;
Home home;
#Override
public void onClick(View view) {
parent = (LinearLayout) home.findViewById(R.id.main_view);
View childLayout = layoutInflater.inflate(R.layout.mylayout, (ViewGroup) view.findViewById(R.id.list_layout));
parent.addView(childLayout, 0);
LinearLayout layout = (LinearLayout) home.findViewById(R.id.main_view);
ListView list = (ListView) layout.findViewById(R.id.list);
list.setAdapter(new MyListAdapter(context));
lsit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("hello Android");
}
});
}
}
mylayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list"
android:padding="15dp"
android:divider="#android:color/transparent"
android:dividerHeight="5dp"
android:listSelector="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"/>
</LinearLayout>
Home.java
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button button= (Button) findViewById(R.id.but);
button.setOnClickListener(new MyClickListener(this,this,layoutInflater));
}
}
home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/background">
...
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:id="#+id/main_view">
</LinearLayout>
.....
Can anyone help
Edit 1
MyListAdapter.java
private class MyListAdapter extends BaseAdapter {
String[] items;
LayoutInflater inflater;
Context context;
public MyListAdapter(Context context) {
this.context = context;
Resources resources = context.getResources();
items = new String[]{resources.getString(R.string.q1), resources.getString(R.string.q2), resources.getString(R.string.q3)};
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View view1 = view;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view1 = inflater.inflate(R.layout.list_layout_item, null);
TextView question = (TextView) view1.findViewById(R.id.itemtext);
question.setText(items[i]);
return view1;
}
}
list_layout_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/itemStyle">
<TextView
android:id="#+id/itemtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:drawableRight="#drawable/disclosure_indicator"/>
</LinearLayout>
Remove this code from your onClick() method and implement outside of that onClick() method. Just set Adapter there, but implementation is wrong og onItemClickListener().
lsit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("hello Android");
}
});
Make sure that in your list_item_layout doesn't have any element is stealing event, like button or TextView with setClickable(true).
I've got a custom BaseAdapter and an add button in the main activity. The button opens a dialog with a textbox and you can add new elements to the list that way. The problem is that the list is not refreshing. In the onActivityResult() function I print the number of elements in the list and each time I hit OK in the dialog box the number increases, so I know it's just the refreshing that doesn't work. My BaseAdapter and my activity:
class ListaOrase extends BaseAdapter{
private Activity context;
ArrayList<String> orase;
public ListaOrase(Activity context){
this.context=context;
orase=new ArrayList<String>();
}
public void add(String string){
orase.add(string);
this.notifyDataSetChanged();
}
public View getView (int position, View convertView, ViewGroup list) {
View element;
if (convertView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
element = inflater.inflate(R.layout.lista, null);
}
else element = convertView;
TextView elementLista=(TextView)element.findViewById(R.id.elementLista);
elementLista.setText(orase.get(position));
return element;
}
}
public class WeatherAppActivity extends ListActivity {
Button buton;
ListaOrase lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lista=new ListaOrase(this);
buton=(Button)findViewById(R.id.buton);
lista.add("Bucuresti");
lista.add("Sibiu");
setListAdapter(lista);
}
public void add(View view){
Intent intent=new Intent();
intent.setClass(this, Adauga.class);
startActivityForResult(intent, 0);
}
public void onActivityResult (int requestCode, int responseCode, Intent data){
System.out.println("Apelata");
if(responseCode==1){
lista.add(data.getStringExtra("oras")); // e chiar getText()
System.out.println(lista.getCount());
lista.notifyDataSetChanged();
}
}
}
As you can see, I'm trying to refresh (notifyDataSetChanged();) both when adding a new element (in the BaseAdapter extending class) and in method onActivityResult, after the dialog passes the new element to the main Activity. I repeat, the element IS added to the list because the count increases, it just doesn't refresh.
Thanks for your answers!
It's normal that it doesn't refresh, you are adding an item to "lista" but the adapter keeps its own copy of that list, so or you set again the list in the adapter and then you call notifyDataChanged or you add the new item to the adapter.
Anyway I see couple of weird things, I thing you could semplify everything using an array adapter, you don't need to implement add,etc. I wrote some code simplyfing yours:
public class WeatherAppActivity extends ListActivity {
Button buton;
ItemsAdapter lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> initialList = new ArrayList<String>();
initialList.add("Bucuresti");
initialList.add("Sibiu");
lista=new ItemsAdapter(this, initialList);
buton=(Button)findViewById(R.id.button1);
buton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista.add(""+System.currentTimeMillis()); // e chiar getText()
lista.notifyDataSetChanged();
}
});
setListAdapter(lista);
}
class ItemsAdapter extends ArrayAdapter<String> {
public ItemsAdapter(Context context, List<String> list) {
super(context, R.layout.lista, list);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
}
}
These are the xml that I have used:
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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Button" />
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
lista.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/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
This is the version of the adapter using a baseadapter:
class ItemsBaseAdapter extends BaseAdapter {
private List<String> items;
private Context mContext;
public ItemsBaseAdapter(Context context, List<String> list) {
items = list;
mContext = context;
}
public void addItem(String str) {
items.add(str);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = (String) getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
And this is the version of the list item wich also include an imageview on the left:
<?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="horizontal" >
<ImageView
android:layout_height="wrap_content"
android:src="#android:drawable/btn_star_big_on"
android:scaleType="fitCenter"
android:layout_width="wrap_content"
/>
<TextView
android:id="#+id/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>