Android Custom ArrayAdapter Listview is not clickable with Async Task - android

I have been stuck on this problem for almost a day now and have tried numerous previous posts on Stack Overflow, online tutorials etc. but nothing seems to work in my case. I have tried setting focusable, focusable in touch and clickable to false for all textviews in each row list item, set android:descendantFocusability="blocksDescendants" in the Relative Layout for list_item_main.xml but nothing has worked. Any help will really be appreciated! Thanks The setup is as follows:
tab.xml (Layout for listview):
<?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">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:clickable="true"
android:id="#+id/android:list"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</LinearLayout>
list_item_main.xml (Each row item):
<?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="wrap_content"
android:id="#+id/rLayout">
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="XYZ"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#808080"
android:layout_above="#+id/weight"
android:layout_alignLeft="#+id/Qty"
android:layout_alignStart="#+id/Qty"/>
<TextView
android:id="#+id/Qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="4"
android:text="150"
android:textSize="18sp"
android:textColor="#808080"
android:layout_marginLeft="39dp"
android:layout_marginStart="39dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="87dp"/>
<TextView
android:id="#+id/dateTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="4"
android:text="Available from: "
android:textSize="18sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Date"
android:layout_alignLeft="#+id/Qty"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=" 0.000"
android:textStyle="bold"
android:textSize="24sp"
android:id="#+id/Rate"
android:textColor="#808080"
android:layout_alignTop="#+id/Name"
android:layout_toRightOf="#+id/Date"
android:layout_toEndOf="#+id/Date"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="14/08/2007"
android:textSize="18sp"
android:id="#+id/Date"
android:textColor="#808080"
android:layout_below="#+id/weight"
android:layout_toRightOf="#+id/dateTitle"
android:layout_toEndOf="#+id/dateTitle"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=" Kgs"
android:id="#+id/weight"
android:textSize="18sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Qty"
android:layout_alignRight="#+id/Name"
android:layout_alignEnd="#+id/Name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="INR"
android:id="#+id/currency"
android:textStyle="bold"
android:textSize="24sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Rate"
android:layout_toRightOf="#+id/Rate"
android:layout_toEndOf="#+id/Rate"/>
DealAdapter:
public class DealAdapter extends ArrayAdapter<Offer2SaleTransaction> {
private List<Offer2SaleTransaction> activeDeals;
private Context context;
private static final Logger logger = Logger.getLogger(DealAdapter.class.getName());
public DealAdapter(List<Offer2SaleTransaction> activeDeals, Context ctx) {
super(ctx, R.layout.list_item_main, activeDeals);
this.activeDeals = activeDeals;
this.context = ctx;
}
public int getCount() {
if (activeDeals != null)
return activeDeals.size();
return 0;
}
public Offer2SaleTransaction getItem(int position) {
if (activeDeals != null)
return activeDeals.get(position);
return null;
}
public long getItemId(int position) {
if (activeDeals != null)
return activeDeals.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item_main, null);
}
Offer2SaleTransaction deal = activeDeals.get(position);
TextView textName = (TextView) v.findViewById(R.id.Name);
textName.setText(deal.getName());
TextView textQty = (TextView) v.findViewById(R.id.Qty);
textQty.setText(Float.toString(deal.getQty()));
// Hardcoded date as of now
TextView textDate = (TextView) v.findViewById(R.id.Date);
textDate.setText("01-01-1994");
logger.info("This is something I want to know " + deal.getSaleDate());
TextView textPrice = (TextView) v.findViewById(R.id.Rate);
textPrice.setText(Float.toString(deal.getRate()));
return v;
}
public List<Offer2SaleTransaction> getActiveDeals() {
return activeDeals;
}
public void setActiveDeals(List<Offer2SaleTransaction> activeDeals) {
this.activeDeals = activeDeals;
}}
Finally, the fragment to display the listview:
public class StatusFragment extends ListFragment implements OnItemClickListener{
DealAdapter adpt;
ListView lView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tab, container, false);
adpt = new DealAdapter(new ArrayList<Offer2SaleTransaction>(), getActivity());
lView = (ListView) view.findViewById(android.R.id.list);
lView.setAdapter(adpt);
lView.setOnItemClickListener(this);
// Exec async load task
new EndpointsStatusAsyncTask().execute(new Pair<Context, String>(getActivity(), "XXXXXX"));
return view;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Toast.makeText(getActivity(), "PLEASE WORK",Toast.LENGTH_LONG).show();
}
private class EndpointsStatusAsyncTask extends AsyncTask<Pair<Context, String>, Void, List<Offer2SaleTransaction>> {
private Offer2SaleTransactionApi myApiService = null;
private final Logger logger = Logger.getLogger(EndpointsStatusAsyncTask.class.getName());
private Context context;
private String TAG = "Background";
#Override
protected List<Offer2SaleTransaction> doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
Offer2SaleTransactionApi.Builder builder = new Offer2SaleTransactionApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("https:xxxx");
myApiService = builder.build();
}
context = params[0].first;
String userID = params[0].second;
try {
return myApiService.getOffer2SaleTransaction(userID).execute().getItems();
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(List<Offer2SaleTransaction> result) {
if (result == null)
{
Toast.makeText(context, "It didn't work", Toast.LENGTH_LONG).show();
logger.info("Failure in connecting to execute onPostExecute");
}
else
{
super.onPostExecute(result);
adpt.setActiveDeals(result);
adpt.notifyDataSetChanged();
}
}
}}

since you are extending ListFragment, you have to override onListItemClick, and use it in place of onItemClick.
Remove implements OnItemClickListener
Remove lView.setOnItemClickListener(this);
Delete onItemClick
Then
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "PLEASE WORK",Toast.LENGTH_LONG).show();k(l, v, position, id);
}

Related

Unable to display fetch data from MYSQL database in custom gridview in android

In my app I use grid view to display data. grid view is in a fragment.I already retrieve data from mysql database in Log cat but that json data not display in custom grid.
activity_product_list.xml
<android.support.constraint.ConstraintLayout 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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".DrawerActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/header2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PRODUCTS : -"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"/>
<GridView
android:id="#+id/productlist"
android:layout_below="#+id/header2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="2dp"
android:layout_marginTop="#dimen/activity_horizontal_margin">
</GridView>
</RelativeLayout>
ProductListFragment.java
public class ProductListFragment extends Fragment {
List<Product> productList;
GridView gridView;
CustomProductList customProductList;
int categoryid;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_product_list, container,false);
gridView = (GridView) rootView.findViewById(R.id.productlist);
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
categoryid = ID.getCategoryid();
productList = new ArrayList<>();
loadProduct();
customProductList = new CustomProductList(getActivity(),productList);
gridView.setAdapter(customProductList);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void loadProduct() {
String PRODUCT_URL = "http://192.168.0.101/cart/product/get_all_product.php?vcategoryid="+categoryid;
StringRequest stringRequest= new StringRequest(Request.Method.GET, PRODUCT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("products");
for (int i = 0; i < array.length(); i++){
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
Product product = new Product();
product.setProductid(userJson.getInt("productid"));
product.setProductName(userJson.getString("productname"));
product.setProductDesc(userJson.getString("productdesc"));
product.setPrice(userJson.getString("productprice"));
productList.add(product);
Log.e("product",userJson+"");
}
customProductList.notifyDataSetChanged();
Log.e("product",customProductList+"");
//customCategoryList = new CustomCategoryList(getActivity(),categoryList);
//recyclerView.setAdapter(customCategoryList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}
custom_product_list.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/home_appliances"/>
<TextView
android:id="#+id/productName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Redmi"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="22sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RS."
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9999"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"
android:layout_marginLeft="10dp"/>
</LinearLayout>
CustomProductList.java
public class CustomProductList extends BaseAdapter {
private Context mCtx;
private List<Product> productList;
public CustomProductList(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mCtx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(mCtx);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.custom_product_list, null);
TextView productname = (TextView) gridView.findViewById(R.id.productName);
TextView price = (TextView) gridView.findViewById(R.id.price);
// getting data for the row
Product product = productList.get(position);
// set data
productname.setText(product.getProductName());
price.setText(product.getPrice());
} else {
gridView = (View) convertView;
}
return gridView;
}
}
This is my code.All data comes from database in logcat as json..But All not display in grid.Please help me.Tell me What is the problem.
Solution:
You forgot to get count the updated list, hence chenge the below code:
#Override
public int getCount() {
return 0;
}
to this:
#Override
public int getCount() {
return this.productList.size();
}
That's it. Hope it helps.

Android Custom Spinner unable to select an option and show it

I have a problem with spinner it do not let me select one item. I tried a lot of things and that still not working.
The picture shows that the spinner is in blank when the activity load
When I clicked the arrow it shows the items
but when I choose one, nothing happends.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.Inspeccion.DatosGeneralesActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
>
<TextView
android:id="#+id/tvSubestacionTitulo"
android:layout_below="#+id/imgLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/strSubestacion"
android:textSize="18sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
/>
<TextView
android:id="#+id/tvSubestacionDato"
android:layout_below="#+id/tvSubestacionTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Prueba"
/>
<Spinner
android:id="#+id/spinnerSubEstacion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvSubestacionDato"
>
</Spinner>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
This is the Layout of the activity.
<?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="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tvNumeroOpcion"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="1"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDescriptionOption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="Guatemala"
android:textColor="#color/black"
android:textSize="14sp" />
</LinearLayout>
That is the custom layout for the spinner
Public class ComboAdapter extends BaseAdapter{
private List<Combo> combos;
private Activity activity;
private LayoutInflater inflater;
public ComboAdapter(List<Combo> combos, Activity activity) {
this.combos = combos;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return combos.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, null);
TextView tvId = (TextView) view.findViewById(R.id.tvNumeroOpcion);
TextView tvDescripcion = (TextView) view.findViewById(R.id.tvDescriptionOption);
tvId.setText(combos.get(position).getId());
tvDescripcion.setText(combos.get(position).getDescripcion());
}
return view;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getView(position, convertView,parent);
}
}
That is my Adapter
And below is my activity.
public class DatosGeneralesActivity extends AppCompatActivity {
private TextView tvSubestacionDato;
private List<Combo> listaCombo;
private Spinner spinnerSubestacion;
private ArrayAdapter<Combo> adapterSubestacion;
String seleccion;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_generales);
//Inicializando textos
tvSubestacionDato = (TextView) findViewById(R.id.tvSubestacionDato);
//Inicializanco listas
listaCombo = new ArrayList<>();
//Inivializando spinners
spinnerSubestacion = (Spinner) findViewById(R.id.spinnerSubEstacion);
AppService service = API.getCombos().create(AppService.class);
Call<List<Combo>> subestacionCall = service.getSubestacion();
subestacionCall.enqueue(new Callback<List<Combo>>() {
#Override
public void onResponse(Call<List<Combo>> call, Response<List<Combo>> response) {
listaCombo.clear();
listaCombo.addAll(response.body());
}
#Override
public void onFailure(Call<List<Combo>> call, Throwable t) {
}
});
//final ComboAdapter adapter = new ComboAdapter(listaCombo, DatosGeneralesActivity.this);
final ArrayAdapter<Combo> adapter = new ArrayAdapter<Combo>(this, R.layout.support_simple_spinner_dropdown_item, listaCombo);
spinnerSubestacion.setAdapter(adapter);
spinnerSubestacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
adapter.notifyDataSetChanged();
Toast.makeText(DatosGeneralesActivity.this, ""+position, Toast.LENGTH_SHORT).show();
tvSubestacionDato.setText(listaCombo.get(position).getDescripcion());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Try this changes:
Call adapter like:
ComboAdapter adapter = new ComboAdapter(DatosGeneralesActivity.this,
R.layout.combo_list_item, R.id.tvDescriptionOption, listaCombo);
now in adapter class:
public ComboAdapter(Activity context,int resouceId, int textviewId, List<Combo> list){
super(context,resouceId,textviewId, list);
this.combos = list;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Also inside your getView() method inflate layout like:
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, parent , false);

how to hide view appear on top of previous selected row on click of another row inside GridView in android

I have a Fragment with custom Adapter extending BaseAdapter that manages a GridView.
I want to show images on each row of the GridView and onClick of each cell, I want to open a translucent view on top of that particular image which will show image details.
Problem is that when I click on the image, a translucent view opened on top of the image but when I click on next image then a translucent view opened on previous images is not hiding,it still appears over the first images..
See the following code
My Fragment
public class ProductFragment extends Fragment {
String ss = null;
GridView gridView;
ArrayList<ProductParameterBO> productlist;
GridViewCustomAdapter gridViewCustomAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState!=null){
View rootView = inflater.inflate(R.layout.empty_catalog_item,null);
TextView configure = (TextView)rootView.findViewById(R.id.text_conf);
configure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),SplitViewActivity.class);
intent.putExtra("firstTab","1stTabs");
startActivity(intent);
}
});
TextView text_here = (TextView)rootView.findViewById(R.id.text_here);
text_here.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), EditUploadActivity.class);
startActivity(intent);
}
});
return rootView;
} else {
View rootView = inflater.inflate(R.layout.fragment_product,null);
gridView =(GridView)rootView.findViewById(R.id.gridView);
productlist = new ArrayList<ProductParameterBO>();
productlist.add(new ProductParameterBO("Type","Numeric","yes","yes"));
productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
gridViewCustomAdapter = new GridViewCustomAdapter(getActivity(),productlist);
gridView.setAdapter(gridViewCustomAdapter);
gridViewCustomAdapter.notifyDataSetChanged();
return rootView;
}
// return inflater.inflate(R.layout.fragment_product,null);
}
}
My Adater
public class GridViewCustomAdapter extends BaseAdapter {
private List<ProductParameterBO> availList;
private LayoutInflater inflater;
Context context;
public GridViewCustomAdapter(Context ctx,List<ProductParameterBO> list){
this.context = ctx;
this.availList = list;
}
#Override
public int getCount() {
return availList.size();
}
#Override
public Object getItem(int position) {
return availList.get(position);
}
#Override
public long getItemId(int position) {
ProductParameterBO c = availList.get(position);
// long id = c.getTimeId();
return 0;
}
#Override
public View getView(int position,View convertView,final ViewGroup parent) {
View row = convertView;
final TeeTimeHolder holder;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid_row,parent,false);
holder = new TeeTimeHolder();
holder.myImage =(ImageView)row.findViewById(R.id.imageView10);
holder.name =(TextView)row.findViewById(R.id.textView47);
holder.edit =(TextView)row.findViewById(R.id.textView49);
holder.rl =(RelativeLayout)row.findViewById(R.id.img_ovrly);
row.setTag(holder);
} else {
holder =(TeeTimeHolder)row.getTag();
}
holder.name.setText(availList.get(position).getParameterName());
holder.myImage.setImageResource(R.drawable.toi);
holder.rl.setVisibility(View.GONE);
holder.myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rows = null;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rows = inflater.inflate(R.layout.image_overlay,parent,false);
// holder.rl = (RelativeLayout)rows.findViewById(R.id.img_ovrly);
holder.rl.setVisibility(View.VISIBLE);
}
});
return row;
}
static class TeeTimeHolder {
ImageView myImage;
TextView name,edit;
RelativeLayout rl;
//TextView descriptions;
/* TextView coursefee;
TextView viewdetils;*/
}
}
My XML layout grid_row.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="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView10"
android:src="#drawable/toi"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image Name"
android:id="#+id/textView47"
android:layout_below="#+id/imageView10"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:id="#+id/textView49"
android:layout_below="#+id/textView47"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/img_ovrly"
android:background="#color/opacity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/mail"
android:layout_marginTop="10dp"
android:id="#+id/image_i"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title :"
android:id="#+id/text_ttle"
android:layout_below="#+id/image_i"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_ttle"
android:text="hmmmm"
android:layout_below="#+id/image_i"
android:layout_marginTop="20dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dimensions :"
android:id="#+id/text_dimen"
android:layout_below="#+id/text_ttle"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_dimen"
android:text="32*23"
android:layout_below="#+id/text_ttle"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price :"
android:id="#+id/text_prce"
android:layout_below="#+id/text_dimen"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_prce"
android:text="32*23"
android:layout_below="#+id/text_dimen"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color :"
android:id="#+id/text_clr"
android:layout_below="#+id/text_prce"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_clr"
android:text="red,white"
android:layout_below="#+id/text_prce"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Min. Quantity :"
android:id="#+id/text_minq"
android:layout_below="#+id/text_clr"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_minq"
android:text="1000"
android:layout_below="#+id/text_clr"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type :"
android:id="#+id/text_typ"
android:layout_below="#+id/text_minq"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_typ"
android:text="creamic"
android:layout_below="#+id/text_minq"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/img_flp"
android:background="#drawable/flip"
android:layout_below="#+id/text_typ"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"/>
</RelativeLayout>
</RelativeLayout>
Am I missing something? kindly help me to resolve this issue. I want a screen something like that. Am I doing right to open tranlucent screen on top of image and how to hide or make visivility gone on click of other images inside my Adater class.Any help would be appreciated in advanced
You can do one of two things.
1. Use a flag
NOTE this code is untested.
You can create an encapsulated flag in your ProductParameterBO object to determine the visibility of your overlay view. Something like the following
boolean mInformationViewVisible = false;
public void setInformationViewVisible(boolean visible) {
mInformationViewVisible = visible;
}
public boolean isInformationViewVisible() {
return mInformationViewVisible;
}
Then use that in your getView method to set the visibility of the view.
#Override
public View getView(int position,View convertView,final ViewGroup parent) {
...
holder.myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int itemPosition = 0; itemPosition < availList.size(); itemPosition++) {
if(itemPosition != position){
availList.get(itemPosition)
.setInformationViewVisible(false);
}
availList.get(itemPosition).setInformationViewVisible(true);
}
});
if (currentItem.isInformationViewVisible()) {
holder.rl.setVisibility(View.VISIBLE);
} else {
holder.rl.setVisibility(View.GONE);
}
...
}
2. Switch to RecyclerView
The second and better option is to switch to RecyclerView. This view is specifically built for individual interaction with items in your Adapter. It gives you more power over the View in terms of animations and removal/adittion of items to the adapter. You can read more on it here and here.
It is very likely that the app in the image you attached is using RecyclerView to manage their content. The code to manage the selected info view will be very similar in RecyclerView to what I posted for the ListView, the only difference would be that you would pass the OnClickListener to the RecyclerView.ViewHolder and set it to the info view in there in stead of in the getView() method. I highly recommend using this approach as it will benefit you in the future of your app.
In ProductParameterBO, you can keep a boolean member variable, and in getView() and if one image is clicked, you can set the boolean variables from that list as false, except the one you clicked. If the variable is true, it will display the image details, and if the variable is false, you can set the visibillty of the translucent view as Invisible of that particular position.
#Override
public View getView(int position,View convertView,final ViewGroup parent) {
View row = convertView;
final TeeTimeHolder holder;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid_row,parent,false);
holder = new TeeTimeHolder();
holder.myImage =(ImageView)row.findViewById(R.id.imageView10);
holder.name =(TextView)row.findViewById(R.id.textView47);
holder.edit =(TextView)row.findViewById(R.id.textView49);
holder.rl =(RelativeLayout)row.findViewById(R.id.img_ovrly);
row.setTag(holder);
}
else {
holder =(TeeTimeHolder)row.getTag();
}
holder.name.setText(availList.get(position).getParameterName());
holder.myImage.setImageResource(R.drawable.toi);
holder.rl.setVisibility(View.GONE);
holder.myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rows = null;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rows = inflater.inflate(R.layout.image_overlay,parent,false);
// holder.rl = (RelativeLayout)rows.findViewById(R.id.img_ovrly);
// holder.rl.setVisibility(View.VISIBLE);
for(int i=0;i<availList.size();i++){
if(i!=position){
availList.get(i).flag=false;
}
}
availList.get(position).flag=true;
}
});
if(availList.get(i).flag){
holder.rl.setVisibility(View.VISIBLE);
}else{
holder.rl.setVisibility(View.INVISIBLE);
}
return row;
}

ListView doesn't listen to onClick

I'm trying to do a ListView that it can refresh when i call the function actualizarDisplay().
I've seen in the log cat a message, and i have doubts abaout that message:
10-06 12:24:02.524: I/dalvikvm(6911): Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
10-06 12:24:02.524: W/dalvikvm(6911): VFY: unable to resolve virtual method 561: Landroid/content/res/TypedArray;.getType (I)I
10-06 12:24:02.524: D/dalvikvm(6911): VFY: replacing opcode 0x6e at 0x0002
10-06 12:24:02.688: D/AbsListView(6911): Get MotionRecognitionManager
10-06 12:24:02.712: D/AbsListView(6911): onVisibilityChanged() is called, visibility : 4
10-06 12:24:02.712: D/AbsListView(6911): unregisterIRListener() is called
10-06 12:24:02.712: D/AbsListView(6911): onVisibilityChanged() is called, visibility : 0
10-06 12:24:03.055: D/AbsListView(6911): unregisterIRListener() is called
my problem is when i push the screen the event onClickListener is not reviced.
This is my main activity:
public class Rescate extends ActionBarActivity {
ArrayList<Ficha> listaFichas = new ArrayList<Ficha>();
MyCustomAdapter dataAdapter = null;
Ficha fichaAux = new Ficha();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rescate);
Bundle b = this.getIntent().getExtras();
int tipo=b.getInt("lugar");
switch(tipo) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
fichaAux.setNumInv("1");
fichaAux.setIden("cuadro");
fichaAux.setUbi("sacrsitía");
fichaAux.setNumHom(2);
fichaAux.setMat("Plástico");
fichaAux.setEstado(0);
fichaAux.setPrioridad(1);
listaFichas.add(fichaAux);
fichaAux = new Ficha();
fichaAux.setNumInv("2");
fichaAux.setIden("cuadro");
fichaAux.setUbi("sacrsitía");
fichaAux.setNumHom(2);
fichaAux.setMat("Plástico");
fichaAux.setEstado(0);
fichaAux.setPrioridad(2);
listaFichas.add(fichaAux);
actualizarDisplay();
break;
default:
setContentView(R.layout.activity_rescate);
}
}
this is my function actualizarDisplay which implements the lsiteners:
public void actualizarDisplay()
{
dataAdapter = new MyCustomAdapter(this,R.layout.listadofichas, listaFichas);
ListView listView = (ListView) findViewById(R.id.listaObras);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Intent passIntent = new Intent();
passIntent.setClass(Rescate.this, VistaFicha.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("num",listaFichas.get(arg2).getNumInv() );
bundle.putCharSequence("ubicacion",listaFichas.get(arg2).getUbi() );
passIntent.putExtras(bundle);
startActivity(passIntent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3)
{
final String[] opciones = new String[] { "Si", "No"};
final AlertDialog.Builder dialogo = new AlertDialog.Builder(Rescate.this);
dialogo.setCancelable(true);
dialogo.setTitle("¿Desea establecer que la obra ha sido rescatada?");
dialogo.setItems(opciones, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0)
{
listaFichas.get(arg2).setEstado(1);
actualizarDisplay();
}
else
{
listaFichas.get(arg2).setEstado(0);
actualizarDisplay();
}
}
});
dialogo.setCancelable(false);
dialogo.create();
dialogo.show();
return false;
}
});
listView.setAdapter(dataAdapter);
}
and this are my functions to handle the ListView:
public class FichaAdapter extends BaseAdapter
{
private ArrayList<Ficha> fichas;
public FichaAdapter(ArrayList<Ficha> fichas)
{
this.fichas = fichas;
//Cada vez que cambiamos los elementos debemos noficarlo
notifyDataSetChanged();
}
public int getCount()
{
return fichas.size();
}
public Object getItem(int position)
{
return fichas.get(position);
}
public long getItemId(int position)
{
return 0;
}
public View getView(int position, View convertView, ViewGroup parent)
{
FichaView view;
if (convertView == null) //NO existe, creamos uno
view = new FichaView(parent.getContext());
else //Existe, reutilizamos
view = (FichaView) convertView;
view.setFicha(fichas.get(position));
return view;
}
}
private class MyCustomAdapter extends ArrayAdapter<Ficha>
{
private ArrayList<Ficha> fichaList;
public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<Ficha> fichaList)
{
super(context, textViewResourceId,fichaList);
this.fichaList = new ArrayList<Ficha>();
this.fichaList.addAll(fichaList);
}
private class ViewHolder
{
TextView num,iden,ubi,hombres,material;
ImageView foto;
RelativeLayout fondo;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listadofichas, null);
holder = new ViewHolder();
holder.num = (TextView) convertView.findViewById(R.id.numInvResCon);
holder.iden = (TextView) convertView.findViewById(R.id.idenRescCont);
holder.ubi = (TextView) convertView.findViewById(R.id.ubiResCon);
holder.hombres = (TextView) convertView.findViewById(R.id.numHomResCon);
holder.material = (TextView) convertView.findViewById(R.id.matRescCon);
holder.foto = (ImageView) convertView.findViewById(R.id.imaResc);
holder.fondo = (RelativeLayout) convertView.findViewById(R.id.fondoRes);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Ficha ficha = fichaList.get(position);
holder.num.setText(ficha.getNumInv());
holder.iden.setText(ficha.getIden());
holder.ubi.setText(ficha.getUbi());
holder.hombres.setText(String.valueOf(ficha.getNumHom()));
holder.material.setText(ficha.getMat());
if(ficha.getPrioridad()==1)
{
holder.num.setTextColor(Color.RED);
holder.iden.setTextColor(Color.RED);
holder.ubi.setTextColor(Color.RED);
holder.hombres.setTextColor(Color.RED);
holder.material.setTextColor(Color.RED);
}
if(ficha.getPrioridad()==2)
{
holder.num.setTextColor(Color.parseColor("#FF8000"));
holder.iden.setTextColor(Color.parseColor("#FF8000"));
holder.ubi.setTextColor(Color.parseColor("#FF8000"));
holder.hombres.setTextColor(Color.parseColor("#FF8000"));
holder.material.setTextColor(Color.parseColor("#FF8000"));
}
if(ficha.getPrioridad()==3)
{
holder.num.setTextColor(Color.GREEN);
holder.iden.setTextColor(Color.GREEN);
holder.ubi.setTextColor(Color.GREEN);
holder.hombres.setTextColor(Color.GREEN);
holder.material.setTextColor(Color.GREEN);
}
if(ficha.getEstado()== 1)
{
holder.fondo.setBackgroundColor(Color.GREEN);
holder.num.setTextColor(Color.WHITE);
holder.iden.setTextColor(Color.WHITE);
holder.ubi.setTextColor(Color.WHITE);
holder.hombres.setTextColor(Color.WHITE);
holder.material.setTextColor(Color.WHITE);
}
return convertView;
}
}
I think the prgoblem is when the log cat says visibility: 0
I have a warning in this line:
convertView = vi.inflate(R.layout.listadofichas, null);
i think that the problem is here.
i write the layouts:
listadofichas.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fondoRes"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:contentDescription="#string/par" >
<ImageView
android:id="#+id/imaResc"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="40dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="1dp"
android:contentDescription="#string/vacia"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/numInv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imaResc"
android:layout_marginLeft="100dp"
android:layout_toRightOf="#+id/imaResc"
android:text="#string/numInvResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/idenResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/numInv"
android:layout_below="#+id/numInv"
android:layout_marginTop="12dp"
android:text="#string/idenResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/ubiResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/idenResc"
android:layout_below="#+id/idenResc"
android:layout_marginTop="12dp"
android:text="#string/ubiResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/numHomResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ubiResc"
android:layout_below="#+id/ubiResc"
android:layout_marginTop="12dp"
android:text="#string/numHomResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/matResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/numHomResc"
android:layout_below="#+id/numHomResc"
android:layout_marginTop="12dp"
android:text="#string/matResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/numInvResCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/idenResc"
android:layout_marginLeft="84dp"
android:layout_toRightOf="#+id/numInv"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/idenRescCont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/idenResc"
android:layout_alignLeft="#+id/numInvResCon"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/ubiResCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/numHomResc"
android:layout_alignLeft="#+id/idenRescCont"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/numHomResCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/matResc"
android:layout_alignLeft="#+id/ubiResCon"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/matRescCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/matResc"
android:layout_alignBottom="#+id/matResc"
android:layout_alignLeft="#+id/numHomResCon"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imaResc"
android:layout_marginLeft="23dp"
android:layout_marginStart="23dp"
android:layout_toEndOf="#+id/imaResc"
android:layout_toRightOf="#+id/imaResc"
android:contentDescription="#string/guia"
android:src="#drawable/barralat" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/matResc"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:src="#drawable/barrahor" />
<Spinner
android:id="#+id/spinner2"
style="#style/mySpinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/spinner1"
android:layout_below="#+id/spinner1"
android:layout_marginTop="13dp"
android:entries="#array/equipos" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/numInvResCon"
android:layout_alignBottom="#+id/numInvResCon"
android:layout_marginLeft="203dp"
android:layout_toRightOf="#+id/numInvResCon"
android:text="#string/equiposAsig"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<Spinner
android:id="#+id/spinner1"
style="#style/mySpinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="13dp"
android:layout_marginLeft="13dp"
android:entries="#array/equipos" />
</RelativeLayout>
and the layout of the activity
<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:background="#FFFFFF"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="app.gepv.Rescate" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF" >
<ListView
android:id="#+id/listaObras"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="60dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="20dp"
tools:listitem="#layout/listadofichas" >
</ListView>
</RelativeLayout>
</LinearLayout>
The adpater works well because i can change the color,.. but the listener doesn't work
Can anyone help me?
In onCreate of your activity you have a switch in which you initiate the Adapters only if the value tipo is 4, so if it is not, the listview has no adapter and will do nothing. You could either debug to see which value it gets or at least put the line
Log.d("Rescate","tipo = "+tipo)
to see which value it has. To see if the onItemClick is called you could plug as the first line in onItemClick the line:
Log.d("Rescate","onItemClick")
And see if this appears in the Log when you click an item in the list.
I think the error might be related to the fact that ActionBarActivity is depreciated, you should use AppCompatActivity.
If it still doesnt work could you also post the layout files you use?
So here's my code with String list items instead of Ficha ones. I made 'Rescate.java' first extend AppCompatActivity and then ActionBarActivity, and it worked for both versions:
public class Rescate extends ActionBarActivity
{
ArrayList<String> listaFichas = new ArrayList<>();
MyCustomAdapter dataAdapter = null;
String fichaAux = "Hello";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setting this up with Strings to keep things simple
listaFichas.add("Hello");
listaFichas.add("Hi there");
actualizarDisplay();
}
public void actualizarDisplay()
{
dataAdapter = new MyCustomAdapter(this,R.layout.listadofichas, listaFichas);
ListView listView = (ListView) findViewById(R.id.listaObras);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Intent passIntent = new Intent();
passIntent.setClass(Rescate.this, VistaFicha.class);
startActivity(passIntent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3)
{
final String[] opciones = new String[]{"Si", "No"};
final AlertDialog.Builder dialogo = new AlertDialog.Builder(Rescate.this);
dialogo.setCancelable(true);
dialogo.setTitle("¿Desea establecer que la obra ha sido rescatada?");
dialogo.setItems(opciones, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
if (item == 0)
{
actualizarDisplay();
Toast.makeText(Rescate.this, "item = 0", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Rescate.this, "item != 0", Toast.LENGTH_SHORT).show();
}
}
});
dialogo.setCancelable(false);
dialogo.create();
dialogo.show();
return false;
}
});
listView.setAdapter(dataAdapter);
}
}
'VistaFicha.java' is just a blank activity showing "Hello World".
I put the adpater in a separate file 'MyCustomAdapter.java'
public class MyCustomAdapter extends ArrayAdapter
{
private ArrayList<String> fichaList;
private LayoutInflater vi;
public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<String> fichaList)
{
super(context, textViewResourceId,fichaList);
this.fichaList = new ArrayList<String>();
this.fichaList.addAll(fichaList);
// I had to change the original code because my adapter is not an inner class:
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder
{
TextView num;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
convertView = vi.inflate(R.layout.listadofichas, null);
holder = new ViewHolder();
holder.num = (TextView) convertView.findViewById(R.id.tvHallo);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
String ficha = fichaList.get(position);
holder.num.setText(ficha);
return convertView;
}
}
The xml for the list rows is simply a TextView (R.id.tvHallo) inside a LinearLayout and my Rescate activity contains only the usual "Hello World" and the ListView (R.id.listaObras)
Hope this helps, and let me know if there are any questions :)

Items of ListView in ListActivity remain unclickable

In my app there is a Main Acitvity (which extends List Activity) where I have one list view. I want to make items of this list view clickable and handle click events. Here's my code:
public class MainActivity extends ListActivity {
private ArrayList<Item> m_parts = new ArrayList<Item>();
private ItemAdapter m_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
(…)
m_adapter = new ItemAdapter(this, R.layout.item_layout, m_parts);
setListAdapter(m_adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
(…)
}
}
And here's my xml for Main Activity layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/main_background"
tools:context=".MainActivity">
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
</ListView>
</LinearLayout>
This is my Item class:
public class Item {
private Bitmap image;
private Uri uri;
private String title;
private String date;
private String latitude;
private String longitude;
public CheckBox checkBox = null;
public Item(){}
public Item(Bitmap bi, Uri ur, String ti, String da, String la, String lo){
this.image = bi;
this.uri = ur;
this.title = ti;
this.date = da;
this.latitude = la;
this.longitude = lo;
}
public Bitmap getImage() {return image;}
public String getTitle(){
return title;
}
public String getDate(){
return date;
}
public String getLatitude(){
return latitude;
}
public String getLongitude(){
return longitude;
}
public Boolean isChecked(){
return checkBox.isChecked();
};
public Uri getUri(){
return uri;
}
}
Item's layout:
<?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="?android:attr/listPreferredItemHeight">
<ImageView
android:id="#+id/photo"
android:layout_width="60dp"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/place"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/photo"
android:textColor="#color/white"
android:textColorHighlight="#color/white"
android:textColorHint="#color/white"
android:textColorLink="#color/white"
android:hint="#string/founding_place_text" />
<TextView
android:id="#+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/photo"
android:textColor="#color/white"
android:textColorHighlight="#color/white"
android:textColorHint="#color/white"
android:textColorLink="#color/white"
android:hint="#string/founding_date_text" />
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/photo"
android:maxLines="1"
android:textColor="#color/white"
android:textColorHighlight="#color/white"
android:textColorHint="#color/white"
android:textColorLink="#color/white"
android:hint="#string/founding_title_text_2" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
And eventually my Item Adapter:
public class ItemAdapter extends ArrayAdapter<Item>{
private ArrayList<Item> objects;
public ItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects){
super(context, textViewResourceId, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item_layout, null);
}
Item i = objects.get(position);
if(i != null){
ImageView im = (ImageView)v.findViewById(R.id.photo);
TextView ti = (TextView)v.findViewById(R.id.title);
TextView da = (TextView)v.findViewById(R.id.date);
TextView pl = (TextView)v.findViewById(R.id.place);
CheckBox ch = (CheckBox)v.findViewById(R.id.checkBox);
if(im != null){
im.setImageBitmap(i.getImage());
}
if(ti != null){
if(i.getTitle() != null && i.getTitle() != ""){
ti.setText(i.getTitle());
}else{
ti.setText("No title");
}
}
if(da != null){
da.setText(i.getDate());
}
if(pl != null){
if(i.getLatitude()!=null && i.getLongitude()!=null){
pl.setText(i.getLatitude() + ", " + i.getLongitude());
}else{
pl.setText("No coordinates");
}
}
if(ch != null){
i.checkBox = ch;
}
}
return v;
}
}
My problem is that onListItemClick(…) isn't called when I click on any item in list view. What's more, they aren't even highlighted. Do you have any idea what do I have to add to my code to handle click events? I am using Android 4.3.
Don't set your list view to be clickable and don't set an OnItemClickListener. (In other words, end your onCreate() method with the call to setlistAdapter.) You only need to override onListItemClicked; the ListActivity infrastructure takes care of the rest. By setting a listener yourself you are interfering with the framework's mechanism.
remove android:clickable="true" from layout and listView.setClickable(true) from code and set listView.setOnItemClickListener and put android:layout_height="wrap_content" android:layout_width="match_parent

Categories

Resources