ListView with EditText and SwipeDismissListViewTouchListener - android

I've created a ListView that has an EditText in each row. The ListView also allows the user to delete an item in the list by swiping horizontally using SwipeDismissListViewTouchListener.java from https://github.com/romannurik/Android-SwipeToDismiss.
Both functionality work well, except when the user tries to do the swiping gesture with the initial ACTION_DOWN event occurring over the EditText. It looks like the EditText is consuming the ACTION_DOWN event before it can be passed to the SwipeDismissListViewTouchListener, which needs the ACTION_DOWN event to initialize the gesture.
Question:
How can I get the SwipeDismissListViewTouchListener to work when the swipe gesture is initiated on the EditText?
SampleListFragment.java:
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class SampleListFragment extends ListFragment {
protected AddGroupAdapter adapter;
protected ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new AddGroupAdapter(getActivity());
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
lv = getListView();
SwipeDismissListViewTouchListener listener =
new SwipeDismissListViewTouchListener(
lv,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
adapter.removeRecord(position);
}
adapter.notifyDataSetChanged();
}
});
lv.setOnTouchListener(listener);
lv.setOnScrollListener(listener.makeScrollListener());
super.onActivityCreated(savedInstanceState);
}
public class AddGroupAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> data;
public AddGroupAdapter(Activity activity) {
mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
data = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
data.add("Sample Text " + String.valueOf(i));
}
notifyDataSetChanged();
}
public void removeRecord(int position) {
data.remove(position);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
holder.edit = (EditText) convertView.findViewById(R.id.edit_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.edit.setText(data.get(position));
holder.edit.setId(position);
holder.edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
final int position = view.getId();
final EditText edit = (EditText) view;
if (edit.getText() != null && !edit.getText().toString().isEmpty())
if (position < getCount())
data.set(position, edit.getText().toString());
}
}
});
return convertView;
}
}
static class ViewHolder {
EditText edit;
}
}
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">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/edit_text"
android:hint="Enter Text"
android:gravity="center_horizontal"
android:singleLine="true" />
</LinearLayout>
*fragment_sample.xml:*
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#android:id/list"
android:name="com.example.app.SampleListFragment"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1.0"
android:descendantFocusability="beforeDescendants"
tools:context=".SampleActivity"
tools:layout="#android:layout/list_content"/>
</LinearLayout>

Trying adding this to your LinearLayout in the row.xml:
android:descendantFocusability="blocksDescendants"
Edit:
So apparently a EditText is trickier than buttons to have inside a listview. Maybe this answer can put you in the right direction if you must have them in yours: https://stackoverflow.com/a/2680077/362298

Related

Not being able to place an onClickListener on the Grid Items provided by a custom BaseAdapter

I currently have a grid view using a base adapter inside a fragment and I am trying to transfer to a different fragment when one of the items is clicked but none of the solutions I found on stack overflow has worked. I might miss something.
Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.licenta.joberfrontend.R;
import com.licenta.joberfrontend.rest.backend_entieties.Category;
import java.util.ArrayList;
import java.util.List;
public class CategoriesAdapter extends BaseAdapter {
public class ViewHolder {
TextView textName;
ImageView imageView;
}
private ArrayList<Category> categoryList;
public Context context;
public CategoriesAdapter(List<Category> apps, Context context) {
this.context = context;
this.categoryList = (ArrayList<Category>) apps;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) // inflating the layout and initializing widgets
{
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.category_list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = view.findViewById(R.id.textName);
viewHolder.imageView = view.findViewById(R.id.iconView);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
// here we are setting up the names and images
viewHolder.textName.setText(categoryList.get(position).getName());
viewHolder.imageView.setImageResource(this.context.getResources().getIdentifier(categoryList.get(position).getCategoryIconId(), "mipmap", this.context.getPackageName()));
return view;
}
}
Fragment's OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LocalStorageSaver localStorageSaver = new LocalStorageSaver(Objects.requireNonNull(getContext()));
final ToastShower toastShower = new ToastShower();
//REST services creation
final RetrofitCreator retrofitCreator = new RetrofitCreator();
final Retrofit retrofit = retrofitCreator.getRetrofit();
final CategoryService categoryService = retrofit.create(CategoryService.class);
final Call<List<Category>> getCategoriesRequest = categoryService.getAllCategoriesAndTheirJobs(localStorageSaver.getValueFromStorage(Constants.TOKEN));
getCategoriesRequest.enqueue(
new Callback<List<Category>>() {
#Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
toastShower.showToast("Categories succesfully retrieved from backend.", getContext());
final GridView gridView = Objects.requireNonNull(getView()).findViewById(R.id.gridViewNewContract);
gridView.setAdapter(new CategoriesAdapter(response.body(), getActivity()));
}
#Override
public void onFailure(Call<List<Category>> call, Throwable t) {
toastShower.showToast("There has been a problem with retrieving the categories data!", getContext());
}
}
);
}
Items inside the grid view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="100dp"
android:layout_height="100dp"
app:cardCornerRadius="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="15dp"
android:orientation="vertical">
<ImageView
android:id="#+id/iconView"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:src="#mipmap/ic_list"
android:tint="#color/colorAccent" />
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif"
android:maxLength="12"
android:text="#string/appName"
android:textColor="#color/colorAccent"
android:textSize="13sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
If you need any more information I will gladly provided.
I can mention that I've tried placing listeners both in the adapter and in the fragment directly on the grid.
please try this
viewHolder.imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});

How to select item in the list view programmatically

I have an ArrayList<String> List which contains some items from the listview all_list. How can I select these items in the list view all_list programmatically by checking the ArrayList<String> List contents?
for e.g., listview all_list contains [0] apple
[1] orange
[2] banana
In ArrayList<String> List, I have orange so I want item on position 1 on the listview all_list to be selected (highlighted) automatically.
I have tried using all_list.setItemChecked(), but it does nothing and shuts down the application. I am performing the operation after listing the adapter.
set an onItemClickListener to the listview such that on click, you set a boolean flag that sets the checkbox in each row to selected. then call notifyDataSetChanged()
Try this
MainActivity.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView1;
ArrayList<ModelClass> modelClass = new ArrayList<ModelClass>();
FruitSelectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelClass.add(new ModelClass("Orange", true));
modelClass.add(new ModelClass("Apple", false));
modelClass.add(new ModelClass("Banana", false));
modelClass.add(new ModelClass("Grapes", false));
listView1 = (ListView) findViewById(R.id.listView1);
adapter = new FruitSelectAdapter(MainActivity.this, modelClass);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(modelClass.get(arg2).isSelected()){
modelClass.get(arg2).setSelected(false);
}else{
modelClass.get(arg2).setSelected(true);
}
adapter.notifyDataSetChanged();
}
});
}
}
activity_main.xml
<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="com.example.multiseekbar.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
</ListView>
</RelativeLayout>
FruitSelectAdapter.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FruitSelectAdapter extends BaseAdapter
{
private Activity activity;
private LayoutInflater inflater;
private ArrayList<ModelClass> modelClass=null;
public FruitSelectAdapter(Activity activity, ArrayList<ModelClass> modelClass) {
this.activity = activity;
this.modelClass = modelClass;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return modelClass.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return modelClass.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder =new ViewHolder();
convertView = inflater.inflate(R.layout.row1, null);
holder.txtFruitName = (TextView)convertView.findViewById(R.id.txtFruitName);
holder.cbFruitSelectStatus = (CheckBox)convertView.findViewById(R.id.cbFruitSelectStatus);
holder.linLayBackground = (LinearLayout) convertView.findViewById(R.id.linLayBackground);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtFruitName.setText(modelClass.get(position).getFruitName());
holder.cbFruitSelectStatus.setChecked(modelClass.get(position).isSelected());
if(modelClass.get(position).isSelected()){
holder.linLayBackground.setBackgroundColor(Color.parseColor("#80ccff"));
}else{
holder.linLayBackground.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
return convertView;
}
class ViewHolder{
TextView txtFruitName;
CheckBox cbFruitSelectStatus;
LinearLayout linLayBackground;
}
}
row1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/linLayBackground"
android:layout_height="70dp"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtFruitName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Fruit name"
android:layout_weight="1"
android:textSize="16sp"
android:textColor="#000000" />
<CheckBox
android:id="#+id/cbFruitSelectStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
</LinearLayout>
ModelClass.java
package com.example.multiseekbar;
public class ModelClass {
String fruitName;
boolean isSelected=false;
public ModelClass(String fruitName, boolean isSelected) {
this.fruitName = fruitName;
this.isSelected = isSelected;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}

Only expandable listview showing up in activity

I'm making an android app for an automatic salad machine. The app lets you choose your ingredients and such, and then sends it to the machine. I set up an activity with an expandable listview to hold the ingredients, but I also need a next button on the activity and a nutritional information box below it. I added them to the activity, but when I run it only the expandable listview shows up.
Here's the code for the activity:
<?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="fill_parent"
android:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button"
android:layout_gravity="right" />
<ExpandableListView
android:id="#+id/list"
android:layout_height="286dp"
android:layout_width="match_parent"
android:groupIndicator="#null"
android:divider="#A4C739"
android:dividerHeight="0.5dp"
android:layout_weight="1.15" />
<TextView
android:layout_width="match_parent"
android:layout_height="77dp"
android:text="Nutrition Facts:"
android:id="#+id/nutritionTV" />
</LinearLayout>
and here's the code for the class that goes with it:
package com.picknchew.companionapp;
import java.util.ArrayList;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ExpandableListView;
public class ChooseIngredientsActivity extends ExpandableListActivity{
private ArrayList<String> parentItems = new ArrayList<String>();
private ArrayList<Object> childItems = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is not really necessary as ExpandableListActivity contains an ExpandableList
//setContentView(R.layout.main);
ExpandableListView expandableList = getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
expandableList.setDividerHeight(2);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
setGroupParents();
setChildData();
MyExpandableAdapter adapter = new MyExpandableAdapter(parentItems, childItems);
adapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
expandableList.setAdapter(adapter);
expandableList.setOnChildClickListener(this);
}
public void setGroupParents() {
parentItems.add("Lettuce");
parentItems.add("Protein");
parentItems.add("Fruit");
parentItems.add("Dressings");
}
public void setChildData() {
// Android
ArrayList<String> child = new ArrayList<String>();
child.add("Romain");
child.add("Iceberg");
child.add("Arugula");
child.add("Green");
childItems.add(child);
// Core Java
child = new ArrayList<String>();
child.add("Tofu");
child.add("Shredded Cheddar");
child.add("Sliced Eggs");
child.add("Beans");
child.add("Avocado");
childItems.add(child);
// Desktop Java
child = new ArrayList<String>();
child.add("Melon");
child.add("Watermelon");
child.add("Pineapple");
child.add("Grapefruit");
childItems.add(child);
// Enterprise Java
child = new ArrayList<String>();
child.add("Honey Mustard");
child.add("Ranch");
child.add("Caesar");
child.add("Vinaigrette");
childItems.add(child);
}
}
and finally here's the code for the expandable list view adapter, in case that's relevant:
package com.picknchew.companionapp;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.TextView;
import android.widget.Toast;
public class MyExpandableAdapter extends BaseExpandableListAdapter {
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
public MyExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern) {
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity) {
this.inflater = inflater;
this.activity = activity;
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
child = (ArrayList<String>) childtems.get(groupPosition);
CheckBox checkbox = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group, null);
}
checkbox = (CheckBox) convertView.findViewById(R.id.checkBox2);
checkbox.setText(child.get(childPosition));
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.child, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public int getChildrenCount(int groupPosition) {
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return parentItems.size();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
Mixing fixed heights with weights won't work.
What you can do: set all elements' height to 0 and assign them weights.
What I would do: use a RelativeLayout, put the Button at the top, the TextView at the bottom (alignParentBottom="true") and the ListView inbetween like
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button" />
<TextView
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="77dp"
android:text="Nutrition Facts:"
android:id="#+id/nutritionTV" />
<ExpandableListView
android:layout_above="#+id/nutritionTV"
android:layout_below="#+id/button"
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:groupIndicator="#null"
android:divider="#A4C739"
android:dividerHeight="0.5dp" />
</RelativeLayout>
Result:
EDIT: You have to actually use this layout, which you at the moment don't do:
// this is not really necessary as ExpandableListActivity contains an ExpandableList
//setContentView(R.layout.main);
Uncomment the setContentView line. Don't forget to assign the views correctly, ie
ExpandableListView expandableList = getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
will become
ExpandableListView expandableList = (ExpandableListView) findViewById(R.id.list)

How to get values from grid view

I have a gridview with editTexts as the individual views in it. I want to save the values that are in each of the editTexts because they are dissapearing when I switch to another fragment or press the home button, so how do I do that?
Would I need an array or arraylist that holds all of the views? How would I get the views if I did that?
fragment_score_red.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".RedScorerFragment"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/gridLabel__red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:text="#string/grid_label__red"
android:background="#color/white"
android:paddingTop="5dp"
/>
<GridView
android:id="#+id/gridViewRed"
android:layout_width="wrap_content"
android:layout_height="350dp"
android:layout_alignParentLeft="true"
android:layout_below="#id/gridLabel__red"
android:columnWidth="40dp"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="7dp"
android:gravity="center"
android:background="#color/white"
>
</GridView>
</RelativeLayout>
</ScrollView>
RedScorerFragment.java
import com.actionbarsherlock.app.SherlockFragment;
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
public class RedScorerFragment extends SherlockFragment {
LayoutInflater infl;
GridView mGrid;
EditText mText;
int R1C1, R1C2, R1C3;
View tView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
infl = inflater;
//super.onCreate(savedInstanceState);
View mView = inflater.inflate(R.layout.fragment_score_red, container, false);
mGrid = (GridView) mView.findViewById(R.id.gridViewRed);
tView = container.getRootView();
final InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mView.getApplicationWindowToken(), 0);
/*mGrid.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_MOVE)
return true;
return false;
}
});*/
if(savedInstanceState != null)
{
R1C1 = savedInstanceState.getInt("R1C1");
R1C2 = savedInstanceState.getInt("R1C2");
R1C3 = savedInstanceState.getInt("R1C3");
Log.d("savedd R1C1 ", String.valueOf(R1C1));
Log.d("savedd R1C2 ", String.valueOf(R1C2));
Log.d("savedd R1C3 ", String.valueOf(R1C3));
}
mGrid.setAdapter(new ImageAdapter(getActivity()));
return mView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null)
{
R1C1 = savedInstanceState.getInt("R1C1", 0);
R1C2 = savedInstanceState.getInt("R1C2", 0);
R1C3 = savedInstanceState.getInt("R1C3", 0);
Log.v("saved R1C1 ", String.valueOf(R1C1));
Log.v("saved R1C2 ", String.valueOf(R1C2));
Log.v("saved R1C3 ", String.valueOf(R1C3));
}
//Log.v("saved R1C1 ", String.valueOf(R1C1));
//Log.v("saved R1C2 ", String.valueOf(R1C2));
//Log.v("saved R1C3 ", String.valueOf(R1C3));
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
//for(int i=0;i<mGrid.getChildCount(); i++)
Log.v("Saving", String.valueOf(mGrid.getAdapter().getItem(0)));
//Log.v("Saving", mGrid.getItemAtPosition(2).toString());
Integer temp = (Integer) mGrid.getAdapter().getItem(0);
int temp2;
if(temp != null)
{
temp2 = temp;
Log.v("temp2", String.valueOf(temp2));
savedInstanceState.putInt("R1C1", temp2);
}
else
Log.v("temp2", "Temp was null");
mText = (EditText)tView.findViewById(R.id.weightedRed__red);
Log.d("weighted Red", mText.getText().toString() );
EditText oText = (EditText)tView.findViewById(R.id.grid_item_edit_text_red);
Log.d("red edit text", oText.getText().toString() );
EditText lText = (EditText)tView.findViewById(R.id.grid_item_edit_text_blue);
Log.d("blue edit text", lText.getText().toString() );
//savedInstanceState.putInt("R1C2", (Integer) mGrid.getAdapter().getItem(4) );
//savedInstanceState.putInt("R1C3", (Integer) mGrid.getAdapter().getItem(2) );
}
public class ImageAdapter extends BaseAdapter{
Context context;
public ImageAdapter(Context context)
{
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = convertView;
//LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null)
{
LayoutInflater li = infl;
myView= li.inflate(R.layout.grid_items, null);
EditText editText = (EditText) myView.findViewById(R.id.grid_item_edit_text_red);
}
return myView;
}
#Override
public int getCount() {
return 9;//only 9
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
}
I tried changing the get Item method to
#Override
public Object getItem(int position) {
return mGrid.getItemAtPosition(position);
}
but now it crashes when I press the home button and i get a stack overflow error
I'm not shure if this is the absolute and eligant solution, but you can try to add to your adapter a value container (like a dataset) for all the TextView's (it could be an ordinary ArrayList or somthing similar).
Then set a TextWatcher on every EditText:
mEditText.addTextChangedListener(new TextWatcher() {...});
And change the value of the list item every time the EditText value is changed.
In you onSaveInstanceState() method all you need is to retrive the value from the adapter.
The rest I think is simple.
Edit (Just to be clear)
Your adapter should luck somthing similar:
public class MyAdapter extends BaseAdapter {
// All the fancy stuff
List<String> dataset;
#Override
public View getView(...) {
//... othe code
mEditText.addTextChangedListener(new MyTextWatcher(position));
}
private class MyTextWatcher implements TextWatcher {
int index;
public MyTextWatcher(int index) {
this.index = index;
}
#Override
public void afterTextChanged(Editable s) {
dataset.set(index, s.toString());
}
}
}
In addition to TextWatchers, you could simply add all your Editexts to an array, and then when you need your text from them, you could simply cycle through the array and call getText().toString(); on all of them.
public class ImageAdapter extends BaseAdapter{
Context context;
EditText[] etCollection = new EditText[getCount()];
public ImageAdapter(Context context)
{
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = convertView;
//LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null)
{
LayoutInflater li = infl;
myView= li.inflate(R.layout.grid_items, null);
}
EditText editText = (EditText) myView.findViewById(R.id.grid_item_edit_text_red);
//^ moved to outside the null block
etCollection[position] = editText;
return myView;
}

GridView and ImageButton Weird issue

Hi all I have custom grid view with imageButton and textView as follows
Here i have used imageButton.. The problem is the grid is not clickable.. But if i use here imageView it works fine but UI is not appropriate.
Here is my layout
<?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="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp"
>
<ImageButton
android:id="#+id/profilePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/newlocation"
android:background="#drawable/btnbackground"
/>
<TextView
android:id="#+id/SpeakerName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="15sp"
android:text="Some Speaker"
/>
Here is my adapter
package com.tt.cc;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SavedConferencesGridAdapter extends ArrayAdapter<String>{
Context mContext;
List<String> confernceList;
public SavedConferencesGridAdapter(Context context, int textViewResourceId, List<String> confernceList)
{
super(context,textViewResourceId,confernceList);
this.confernceList = confernceList;
this.mContext = context;
Log.e("TAG", confernceList.size()+"");
}
int[] picIds = new int[] { R.drawable.newschedule,R.drawable.newexhibitors,
R.drawable.newsponsers, R.drawable.newlocation,
R.drawable.newfavourites, R.drawable.newreminder,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info };
#Override
public int getCount() {
// TODO Auto-generated method stub
return confernceList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.entity, null);
TextView tv = (TextView)v.findViewById(R.id.SpeakerName);
tv.setText("tt");
/*ImageView iv = (ImageView) v.findViewById(R.id.profilePic);
iv.setImageResource(picIds[position]);*/
}
else
{
v = convertView;
}
return v;
}
}
and here is my activity
public class SavedConferencesActivity extends Activity{
GridView confereneceGridView;
ArrayAdapter<String> conferneceAdapter;
Button btnUpdate;
List<String> conferenceList;
TextView txtHeading;
Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void onStart() {
super.onStart();
setContentView(R.layout.homegridlayout);
initialize();
confereneceGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(SavedConferencesActivity.this, conferenceList.get(position)+"", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
conferneceAdapter = new SavedConferencesGridAdapter(this, android.R.layout.simple_list_item_1, conferenceList);
confereneceGridView.setAdapter(conferneceAdapter);
}
private void initialize() {
confereneceGridView = (GridView) findViewById(R.id.gridOfConference);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
txtHeading = (TextView) findViewById(R.id.txtTag);
conferenceList = new ArrayList<String>();
conferenceList.add("AA");
conferenceList.add("BB");
conferenceList.add("CC");
if (conferenceList.size() == 0)
txtHeading.setText("No conferences saved");
else
txtHeading.setText("Selected Conferences");
}
}
Please help me in solving this problem. Or if any alternative available..
Simple. Provide this attribute for the ImageButton ,
android:focusable="false"
This problem usually occurs when there is a focussable element in the Grid.(Eg:Buttons, ImageButton etc).
Reason of this ImageButton is by Default is clickable and focusable, so Focus and click event never goes to ItemView.
Set Properties
android:focusable-"false"
and
android:clickable="false"
Your item's Layout should be:
<LinearLayout ...
android:descendantFocusability="blocksDescendants">
<ImageButton ...
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
Don't forget setOnClickListener for ImageButton in Adapter.
in your adapter class,
before you return the view "v", add the "onClickListener" to "v"
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position, Toast.LENGTH_SHORT).show();
}
});

Categories

Resources