On home scree of application, how to display the menu which is similar to android menu but no items needs to be displayed in specific cells. Considering grid of 3 x 3, five items only needs to be displayed at (Row, Col): [0,1], [1,0], [1,1], [1,2], [2,1].
We have tried GridView and set visibility to GONE (convertView.setVisibility(View.GONE);) for items which need not be displayed. Following this, item is not displayed in grid but when user browses through blank item using up and down keys or click directly on blank item, that icon is hihglighted and selected as if it is blank item in grid. We want as it is blank it should not repond to user events neither highlighted not selected.
Code for Grid View:
package org.XXX;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class XXXActivity extends Activity {
GridView MyGrid;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.maingrid);
MyGrid = (GridView)findViewById(R.id.MyGrid);
MyGrid.setAdapter(new ImageAdapter(this));
MyGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Toast.makeText(arg0.getContext(), position + " selected", Toast.LENGTH_LONG).show();
switch(position) {
case 0:break;
case 1:
//Browse
Intent newIntent = new Intent(XXXActivity.this, YYYListItemIcons.class);
startActivity(newIntent);
break;
case 2:break;
case 3:
//Saved Searches
newIntent = new Intent(XXXActivity.this, ZZZListItemIcons.class);
startActivity(newIntent);
break;
case 4:
//Sign in
break;
case 5:
//Reminders
break;
case 6:break;
case 7:
//Sign up
break;
case 8:break;
}
}
});
//onSearchRequested(); //to open search by default
}
public class ImageAdapter extends BaseAdapter
{
Context MyContext;
public ImageAdapter(Context _MyContext)
{
MyContext = _MyContext;
}
#Override
public int getCount()
{
return 9;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater mInflater = LayoutInflater.from(MyContext);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_item, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.grid_item_text);
holder.icon = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(getTextId(position));
holder.icon.setImageBitmap(BitmapFactory.decodeResource(MyContext.getResources(), getIconId(position)));
if(getIconId(position) == R.drawable.nothing) {
convertView.setVisibility(View.GONE);
}
return convertView;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
private int getIconId(int position) {
int iconImages[] = {
R.drawable.nothing,
R.drawable.browse,
R.drawable.nothing,
R.drawable.saved_searches,
R.drawable.sign_in,
R.drawable.reminders,
R.drawable.nothing,
R.drawable.sign_up,
R.drawable.nothing
};
return iconImages[position];
}
private int getTextId(int position) {
int iconNames[] = {
R.string.nothing,
R.string.browse,
R.string.nothing,
R.string.saved_searches,
R.string.sign_in,
R.string.reminders,
R.string.nothing,
R.string.sign_up,
R.string.nothing
};
return iconNames[position];
}
}
static class ViewHolder {
TextView text;
ImageView icon;
}
}
GridLayout:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MyGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="5dp"
android:verticalSpacing="5dp"
android:horizontalSpacing="20dp"
android:numColumns="auto_fit"
android:columnWidth="60dp"
android:stretchMode="columnWidth"
android:gravity="center">
</GridView>
PerItemIconLayout in Grid:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/GridItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<ImageView android:id="#+id/grid_item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
<TextView android:id="#+id/grid_item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:gravity="center_horizontal"
android:textColor="#FFFFFF">
</TextView>
</LinearLayout>
if(getIconId(position) == R.drawable.nothing) {
convertView.setVisibility(View.GONE);
}
replace the above lines by below and try....
if(getIconId(position) == R.drawable.nothing) {
convertView.setVisibility(View.GONE);
convertView.setClickable(false);
convertView.setEnabled(false);
}
try this code in getview().
Now that you have posted your code, I am not sure if you can technically remove but you can disable the "highlighted" click that you are talking about, this way, when a user clicks on the one of the icons, it will no longer highlight.
This can be done via XML or in your code:
https://stackoverflow.com/questions/2865683/android-disable-highlighting-in-gridview
Code: GridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
XML: android:listSelector="#00000000"
However, this will affect all the icons in your gridview.
Also take a look at this:
https://stackoverflow.com/questions/5514629/how-to-disable-item-click-for-particular-positions-in-grid-view-in-android
Related
Hye... I'm new in android development and i'm facing a little bit problem on the android project that I'm in right now. The codes below successfully returning the list of items on the activity_ticket_info.xml layout. Since the number of items appeared based on the looping process, how to set an ID on every single items that appeared so afterwards it could be set as clickable items to intent to another activity layout? Please help me to figure this out. Thanks a lot for the help..
TicketAdapter.java
package info.androidhive.navigationdrawer.activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import info.androidhive.navigationdrawer.R;
import info.androidhive.navigationdrawer.ticketfragments.ComboA_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboB_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboC_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboD_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboE_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboF_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.DuckTourTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.FOneSimulatorFragment;
import info.androidhive.navigationdrawer.ticketfragments.SixDCinemotionTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.SkyCabBasicTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.SkyCabExpressLaneTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.SkyCabPrivateVipGlassTicketFragment;
import static android.R.attr.x;
/**
* Created by user on 11/14/2016.
*/
public class TicketAdapter extends RecyclerView.Adapter<TicketViewHolder>
{
String [] name = {
"Combo A",
"Combo B",
"Combo C",
"Combo D",
"Combo E",
"Combo F",
"Combo G",
"Combo H",
"Combo I",
"Combo J",
"Combo K",
"Combo L"
};
Context context;
LayoutInflater inflater;
public TicketAdapter(Context context)
{
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public TicketViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = inflater.inflate(R.layout.item_list, parent, false);
TicketViewHolder viewHolder = new TicketViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(TicketViewHolder holder, final int position)
{
holder.textTitle.setText(name[position]);
/* holder.textDesc.setText(desc[position]);*/
holder.imageView.setOnClickListener(clickListener);
holder.imageView.setTag(holder);
// holder.imageView.setId(positionId[position]);
holder.cardview.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
switch (position)
{
case 0:
Intent intent0 = new Intent(v.getContext(),SkyCabBasicTicketFragment.class);
v.getContext().startActivity(intent0);
break;
case 1:
Intent intent1 = new Intent(v.getContext(),SkyCabExpressLaneTicketFragment.class);
v.getContext().startActivity(intent1);
break;
case 2:
Intent intent2 = new Intent(v.getContext(),SkyCabPrivateVipGlassTicketFragment.class);
v.getContext().startActivity(intent2);
break;
case 3:
Intent intent3 = new Intent(v.getContext(),SixDCinemotionTicketFragment.class);
v.getContext().startActivity(intent3);
break;
case 4:
Intent intent4 = new Intent(v.getContext(),DuckTourTicketFragment.class);
v.getContext().startActivity(intent4);
break;
case 5:
Intent intent5 = new Intent(v.getContext(),FOneSimulatorFragment.class);
v.getContext().startActivity(intent5);
break;
case 6:
Intent intent6 = new Intent(v.getContext(),ComboA_TicketFragment.class);
v.getContext().startActivity(intent6);
break;
case 7:
Intent intent7 = new Intent(v.getContext(),ComboB_TicketFragment.class);
v.getContext().startActivity(intent7);
break;
case 8:
Intent intent8 = new Intent(v.getContext(),ComboC_TicketFragment.class);
v.getContext().startActivity(intent8);
break;
case 9:
Intent intent9 = new Intent(v.getContext(),ComboD_TicketFragment.class);
v.getContext().startActivity(intent9);
break;
case 10:
Intent intent10 = new Intent(v.getContext(),ComboE_TicketFragment.class);
v.getContext().startActivity(intent10);
break;
case 11:
Intent intent11 = new Intent(v.getContext(),ComboF_TicketFragment.class);
v.getContext().startActivity(intent11);
break;
}
}
});
}
View.OnClickListener clickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
TicketViewHolder vholder = (TicketViewHolder) v.getTag();
int position = vholder.getPosition();
/* Toast.makeText(context,"You have choose " + position,Toast.LENGTH_LONG ).show();*/
//Display toast message with each tickets caption details
Toast.makeText(context,"You have choose " + (name[position]),Toast.LENGTH_LONG ).show();
}
};
#Override
public int getItemCount()
{
return name.length;
}
}
**UPDATED : I'm trying to implement a switch case statement as above for every single items that need to be navigated to each fragment layout and there is no errors found at all but it doesn't work. Could the above switch case statement be the proper way to navigate each items or there is another better way to implement? **
TicketInfoActivity.java
package info.androidhive.navigationdrawer.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import info.androidhive.navigationdrawer.R;
import static info.androidhive.navigationdrawer.R.id.name;
public class TicketInfoActivity extends AppCompatActivity
{
RecyclerView ticketView;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_info);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ticketView = (RecyclerView) findViewById(R.id.my_recycler_view);
TicketAdapter adapter = new TicketAdapter(this);
ticketView.setAdapter(adapter);
ticketView.setHasFixedSize(true);
ticketView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home)
{
// finish the activity
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
TicketViewHolder.java
package info.androidhive.navigationdrawer.activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import info.androidhive.navigationdrawer.R;
public class TicketViewHolder extends RecyclerView.ViewHolder
{
TextView textTitle,textDesc;
ImageView imageView;
CardView cardview;
public TicketViewHolder(View itemView)
{
super(itemView);
textTitle = (TextView) itemView.findViewById(R.id.list_title);
/* textDesc = (TextView) itemView.findViewById(R.id.list_desc);*/
imageView = (ImageView) itemView.findViewById(R.id.list_avatar);
cardview = (CardView) itemView.findViewById(R.id.ticket_view);
}
}
item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ticket_view"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_marginBottom="16dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#C5CAE9"
android:foreground="?attr/selectableItemBackground"
android:theme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="match_parent"
android:gravity="center"
android:paddingTop="16dp"
android:layout_height="match_parent">
<!-- Icon -->
<ImageView
android:id="#+id/list_avatar"
android:layout_width="match_parent"
android:layout_height="85dp"
android:scaleType="fitCenter"
android:src="#drawable/ic_tickets_info_color_48dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<!-- Title -->
<TextView
android:id="#+id/list_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Product Description Goes Here... "
android:textColor="#000000"
android:textStyle="bold"
android:textAppearance="?attr/textAppearanceListItem"
android:textSize="18sp"
android:gravity="center_horizontal"
android:layout_below="#+id/list_avatar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp"/>
<!-- Description -->
</RelativeLayout>
</android.support.v7.widget.CardView>
activity_ticket_info.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_ticket_info"
android:layout_width="match_parent"
android:layout_height="match_parent"
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="info.androidhive.navigationdrawer.activity.TicketInfoActivity">
<!--<include layout="#layout/actionbar_layout" />-->
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:scrollbars="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
If you want to use it later as clickable, instead of assigning the id, you can set the listener for each item when they are returned and call the intent.
However if you still want to assign id, you can use method setId(int) which is available for all types of widgets.. and views
if you want to just make clickable your every cardview item you can make interface
public interface ItemClickListener {
void onItemClick(View v, int pos);
}
and implement this on you adapter class like this
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
private List<Model> list;
Context mContext;
public MyAdapter(Context context,List<Model> list) {
mContext=context;
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Model model = list.get(position);
holder.name.setText("name :"+model.getName());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int position) {
Snackbar.make(v,list.get(position).getName(),Snackbar.LENGTH_SHORT).show();
Intent i=new Intent(mContext, Showname.class);
mContext.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView name,branch,sem;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.s_name);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(v,getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
}
}
I think there is no such method to provide ID for each item dynamically.According to the program above you can select only a single item in the recyclerView at a time. Better create a method in main activity as below
public void setRVAdapterSelectedItem(String itemName){this.itemName = itemName;}
and set the clicked string to activity by calling from onClick of the adapter
context.setRVAdapterSelectedItem(selectedString);
So that you will get the list in Activity.
It is always better to use a model class for item list. Hence you can use a boolean to identify if the item is selected or not and using that you can highlight item in onBindViewHolder
Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
my code given below of adapter and mainclass and activity files
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#drawable/gradient11"
android:layout_width="match_parent" android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="option one is selected now so you can"
android:textColor="#00ff00"
android:id="#+id/op1"/>
<RadioButton
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op2"
android:textColor="#00ff00"
android:id="#+id/op2"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op3"
android:textColor="#00ff00"
android:id="#+id/op3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op4"
android:textColor="#00ff00"
android:id="#+id/op4"/>
</RadioGroup>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/quest"
android:textColor="#e2000000"/>
</LinearLayout>
The Adapter file
package com.patel.ravin.com.domparsing;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by lenovo on 08-08-2016.
*/
public class Adpt extends BaseAdapter
{
Context context;
ArrayList<MyBean> arrayList;
public Adpt(Context context,ArrayList<MyBean> arrayList)
{
this.context=context;
this.arrayList=arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.listview, null);
TextView txtFName = (TextView) view.findViewById(R.id.qid);
TextView txtLName = (TextView) view.findViewById(R.id.quest);
RadioButton op1=(RadioButton)view.findViewById(R.id.op1);
RadioButton op2=(RadioButton)view.findViewById(R.id.op2);
RadioButton op3=(RadioButton)view.findViewById(R.id.op3);
RadioButton op4=(RadioButton)view.findViewById(R.id.op4);
MyBean myBean = arrayList.get(i);
txtFName.setText("" + myBean.getQid());
txtLName.setText(" Answer= " + myBean.getQname());
op1.setText(myBean.getOp1());
op2.setText(myBean.getOp2());
op3.setText(myBean.getOp3());
op4.setText(myBean.getOp4());
return view;
}
}
The Activity file
package com.patel.ravin.com.domparsing;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.patel.ravin.com.domparsing.AsyncTask.AsyncTaskLoader;
import com.patel.ravin.com.domparsing.AsyncTask.OnAsyncResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
TextView textView;
ListView listView1;
Adpt adpt;
ArrayList<MyBean> arrayList=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView= (TextView) findViewById(R.id.tv1);
listView1=(ListView)findViewById(R.id.llv);
// Adpt adpt=new Adpt(getApplicationContext(),arrayList);
//listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList));
OnAsyncResult onAsyncResult=new OnAsyncResult() {
#Override
public void onAsyncResult(String result) {
Log.e("h", result.toString());
try {
// textView.setText(""+result.toString());
// String co=result.toString();
JSONArray jsonArray=new JSONArray(result);
MyBean myBean;
arrayList = new ArrayList<>();
for(int i=1;i<=jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
myBean = new MyBean();
myBean.setQid(jsonObject.getString("que"));
myBean.setQname(jsonObject.getString("ans"));
myBean.setOp1(jsonObject.getString("a"));
myBean.setOp2(jsonObject.getString("b"));
myBean.setOp3(jsonObject.getString("c"));
myBean.setOp4(jsonObject.getString("d"));
arrayList.add(myBean);
listView1.setAdapter(new Adpt(getApplicationContext(),arrayList));
}
//JSONObject object = new JSONObject(result);
//String contact = object.getString("que");
// textView.setText(co);
} catch (Exception e) {
e.printStackTrace();
}
}
};
AsyncTaskLoader asyncTaskLoader=new AsyncTaskLoader(MainActivity.this,onAsyncResult,null,"http://quiz/jsonapi.php");
asyncTaskLoader.execute();
}
}
Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
This is a very common problem in Android with Listviews and Radio buttons.
First, I would recommend you to check this post:
Using radio button in custom listview in Android
Now, I'm going to tell you which solution fits for me. In my case I use GridView, but it also works for ListView.
In your Adapter's class you have to have a variable for the selected item and his index, it could be something like:
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
Then, define a function to retrieve this information:
public int getItemSelected(){
return mSelectedPosition;
}
Now, In order to make it works properly, you have to user a ViewHolder (in my case every item in the GridView has a Image and a RadioButton), so you define your ViewHolder in the Adapter's class as well:
private class ViewHolder {
ImageView image;
RadioButton radio;
}
Then, in your getView function, you have to work with the ViewHolder. In the code I write comments to follow.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView; // assign the view
ViewHolder holder; // declare the ViewHolder
if(view == null){
// cutom layout for each row (item) of the ListView
view = mLayoutInflater.inflate(R.layout.item_list_company, parent, false);
holder = new ViewHolder();
// initialize the ViewHolder's field
holder.image = (ImageView) view.findViewById(R.id.c1);
holder.radio = (RadioButton)view.findViewById(R.id.cN1);
view.setTag(holder); // set the tag
}else{ // already initialized
holder = (ViewHolder)view.getTag(); // so we only set the tag
}
// on click triggered for each RadioButton in the ListView
holder.radio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false); // uncheck the last one
}
mSelectedPosition = position; // change the item selected index
mSelectedRB = (RadioButton)v; // assign the new item selected
}
});
// just to control the right item checked
if(mSelectedPosition != position){
holder.radio.setChecked(false);
}else{
holder.radio.setChecked(true);
if(mSelectedRB != null && holder.radio != mSelectedRB){
mSelectedRB = holder.radio;
}
}
return view;
}
Finally, in the custom layout (item_list_company.xml in my case) for each item in the ListView, I have the following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView android:id="#+id/c1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="centerInside" />
<RadioButton
android:id="#+id/cN1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:buttonTint="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:focusable="false"
android:layout_gravity="left"
android:clickable="false"
android:focusableInTouchMode="false"
android:textSize="20dp"/>
</LinearLayout>
Special attention for this three attributes of the RadioButton:
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
So, with all of this, you only have to set your adapter and ListView in your Activity and call to the right function to retrieve the selected item:
ArrayList<MyBean> arrayList = new ArrayList<>();
ListView listView1 = (ListView)findViewById(R.id.llv);
Adpt adpt = new Adpt(getApplicationContext(), arrayList);
// add data to the ArrayList
adpt.notifyDataSetChanged(); // notify for the new data in the ArrayList
// retrieve the item selected
int selected = adpt.getItemSelected();
Hope it helps!
I have an activity that has a AdapterView to display a gridview of ImageView
The Activity:
package com.xlck.mislistas
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.xlck.mislistas.adapters.ExpandableHeightGridView;
import com.xlck.mislistas.adapters.ImageGridAdapter;
import com.xlck.mislistas.adapters.ImageGridAdapter.ViewHolder;
import com.xlck.mislistas.adapters.ImageGridBean;
public class AmigosActivity extends SherlockActivity {
...
private ExpandableHeightGridView gridViewImagenes;
gridViewImagenes = (ExpandableHeightGridView) findViewById(R.id.grvImagenes);
// Adapter GridView
gridViewImagenes.setAdapter(imageGridAdapter);
gridViewImagenes.setExpanded(true);
.
.
.
// Listener
gridViewImagenes.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Do something ...;
}
});
}
The Adapter:
package com.xlck.mislistas.adapters;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.xlck.mislistas.R;
public class ImageGridAdapter extends BaseAdapter {
private Context mContext;
private List<ImageGridBean> items;
// Constructor
public ImageGridAdapter(Context context, ArrayList<ImageGridBean> items) {
this.mContext = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
ImageGridBean item = (ImageGridBean) items.get(position);
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_grid_imagen, null);
holder = new ViewHolder();
holder.txtId = (TextView) convertView.findViewById(R.id.uid);
holder.txtNombre = (TextView) convertView
.findViewById(R.id.txtNombre);
holder.imagen = (ImageView) convertView
.findViewById(R.id.imgImagen);
holder.check = (CheckBox) convertView.findViewById(R.id.chkItem);
holder.txtFondoNombre = (TextView) convertView.findViewById(R.id.txtFondoNombre);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtId.setText(item.getId());
holder.txtNombre.setText(item.getNombre());
holder.imagen.setImageBitmap(item.getImagen());
if (item.getId().equals("0"))
holder.check.setVisibility(View.INVISIBLE);
return convertView;
}
#Override
public ImageGridBean getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
// --------------------------------------------------------< ViewHolder >---
// -------------------------------------------------------------------------
/* private view holder class */
public class ViewHolder {
public TextView txtId;
public TextView txtNombre;
public TextView txtFondoNombre;
public ImageView imagen;
public CheckBox check;
}
}
I have this Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="92dp"
android:layout_height="92dp"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false" >
<TextView
.../>
<ImageView
.../>
<TextView
.../>
<TextView
... />
</RelativeLayout>
<LinearLayout
android:layout_width="38dp"
android:layout_height="32dp"
android:layout_alignRight="#+id/relativeLayout2"
android:layout_alignTop="#+id/relativeLayout2"
android:layout_marginRight="0dp"
android:layout_marginTop="4dp" >
<CheckBox
android:id="#+id/chkItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Well, if i click in ImageView, it fire the event click and the listener capture it, but if i click in CheckBox the event click don't fire.
What I doing wrong? What I need to do?
Thanks in advance.
android:focusableInTouchMode="false" android:focusable="false"
#Sam is right, checkboxes handle clicks on their own and the click event never reaches the AdapterView.
Now, technically speaking, you could set android:clickable="false" for your checkbox in the layout file, and then the click event would get delivered up the view hierarchy, but in this case you won't be able to do anything useful with the checkbox, it will just always stay unchecked.
Here's what would be a better approach. Move the "do something" into a different method and add another onClickListener for the checkbox, to do the same thing:
gridViewImagenes.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
doSomething();
}
});
myCheckbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doSomething();
}
});
}
private void doSomething() {
//Do Stuff
}
Think you will have to implement a OnCheckedChangelistener to the checkbox, in your case to chkItem.
See CompoundButton.OnCheckedChangeListener
The implementation would be something like...
CheckBox checkBox = (CheckBox) findViewById(R.id.chkItem);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
// checkbox is checked - doSomething()
} else {
// checkbox is unchecked
}
}
});
Hope this helps.
I finally decided to put the adapter into the Activity class. In Class Adapter put a listener both ImageView and CheckBox component, since these listener invoking a method of the Activity class.
Thanks to all for your time and response!!!
my app has custom ListView, each row contains checkbox ,edit text and 2 buttons. In the main xml layout file i have 1 submit button and listView. i want that, when i click on submit button, i should get all checked row position.I am new to android programming ,so plz help me my code is not working here is my code:
main.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">
<Button android:layout_height="wrap_content"
android:text="#string/button_submit"
android:layout_width="wrap_content"
android:id="#+id/main_submit_button" android:onClick="#string/button_submit"></Button>
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
items.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="wrap_content">
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:layout_weight="1"
android:id="#+id/items_name"
android:gravity="left"
android:textStyle="bold" />
<CheckBox android:id="#+id/items_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button android:id="#+id/items_add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/text_switcher_plus" />
<EditText android:digits="10"
android:textStyle="bold" android:gravity="left"
android:id="#+id/items_plates" android:layout_height="wrap_content"
android:layout_width="90dp"></EditText>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/items_minus_button"
android:text="#string/text_switcher_minus"
android:gravity="right"
/>
</LinearLayout>
</LinearLayout>
VegmenuActivity
package com.sagar.resmenu;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
// reference:http://pareshnmayani.wordpress.com/tag/android-custom-listview-example
public class VegmenuActivity extends Activity implements OnItemClickListener{
//dynamic array that contains names of items
private ArrayList<String> items = new ArrayList<String>
(Arrays.asList("Veg pulav", "Pav bhaji", "Panir tikka", "veg kolhapuri",
"Coconut Rice", "Curd rice", "Mint Pulao",
"Banana Custard","Basundi", "Cheese potato Tikkis",
"Dum aloo"));
private ArrayList<Integer> counter = new ArrayList<Integer>
(Arrays.asList(0, 0,0, 0, 0,0, 0,0, 0,0,0));
private SparseBooleanArray a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView lv =(ListView)findViewById(R.id.list_view);
// lv.setOnClickListener(null);
MyAdapter adapter = new MyAdapter(getApplicationContext(),items,counter);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button submit1;
submit1 = (Button)findViewById(R.id.main_submit_button);
submit1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
a = new SparseBooleanArray();
a.clear();
a = lv.getCheckedItemPositions();
int len = items.size();
for (int i = 0; i < len; i++)
{
if(a.valueAt(i) == true)
Log.d("Returned ", String.valueOf(a.valueAt(i)));
}
}
});
}
//private OnItemClickListener selectCat = new OnItemClickListener();
public void onItemClick(AdapterView<?> a, View v, int positon, long id) {
// TODO Auto-generated method stub
}
}
MyAdapter.java
package com.sagar.resmenu;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextSwitcher;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter implements OnClickListener{
private LayoutInflater inflater;
private ArrayList<String> data;
VegmenuActivity m;
private ArrayList<Integer> counter;
public MyAdapter(Context context, ArrayList<String> data,ArrayList<Integer> counter) {
// TODO Auto-generated constructor stub
super();
// Caches the LayoutInflater for quicker use
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Sets the events data
this.data= data;
this.counter=counter;
}
public int getCount() {
return this.data.size();
//return this.counter.size();
}
public String getItem(int position) throws IndexOutOfBoundsException{
return null;
}
public long getItemId(int position) throws IndexOutOfBoundsException{
return 0;
}
public int getViewTypeCount(){
return 1;
}
public static class ViewHolder
{
TextView items_name;
CheckBox items_check ;
Button items_plus_button;
Button items_minus_button;
EditText plates;
}
public View getView(int position, View convertView, ViewGroup parent){
//String myText = getItem(position);
ViewHolder holder;
if(convertView == null){ // If the View is not cached
// Inflates the Common View from XML file
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.items,parent,false);
holder.items_name = (TextView) convertView.findViewById(R.id.items_name);
holder.plates = (EditText) convertView.findViewById(R.id.items_plates);
holder.items_check = (CheckBox) convertView.findViewById(R.id.items_check);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.items_name.setText(data.get(position));
holder.plates.setText(String.valueOf(counter.get(position)));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
when I need check boxes inside listview, I often code as following:
MyAdapter.java:
- Declare an boolean array to mark which item is checked/unchecked:
....
boolean[] checked;
...
inside constructor:
checked = new boolean[data.size()];
- Inside getView()
{
.....
holder.items_check.setChecked(checked[position]);
holder.items_check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked[position] = isChecked;
}
});
.....
- And method to get all checked items:
boolean[] getCheckedItems() {
return checked;
}
That's !
Could it be that your getItem and getItemId only return null and 1? These methods need to return the correct data for this to work I believe. getItem would need to be:
String getItem(int position)
{
return data.get(position);
}
and getItemId would simply return position instead of 0:
String getItemId(int position)
{
return position;
}
last days I was browsing one of the apps in Android
and I found out an amazing list.
I Found that Custom ListView Interesting.
When we click on the Text it shows me some Activity and when we click on the Arrow on Right it shows me a dialog.
I want to learn this. Can anybody go through some Tutorials where this Custom List is explained. Please Friends. guide me.. Thanks alot
Hi Below Is Custom ListView Example
First Create test.Java File below is code
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class test extends Activity {
/** Called when the activity is first created. */
ArrayList<String> arrayString = new ArrayList<String>();
test_adapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrayString.add("TextView1");
arrayString.add("TextView2");
arrayString.add("TextView3");
arrayString.add("TextView4");
arrayString.add("TextView5");
ListView list = (ListView) findViewById(R.id.LIST);
adapter = new test_adapter(this, arrayString);
list.setAdapter(adapter);
}
}
Also Used below Class file test_adapter.java
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class test_adapter extends BaseAdapter {
private Activity activity;
ArrayList<String> data = new ArrayList<String>();
private static LayoutInflater inflater = null;
public test_adapter(Activity a, ArrayList<String> d) {
activity = a;
data = d;
inflater = LayoutInflater.from(activity);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView txt1;
public Button btn1;
public RelativeLayout rel1;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.txt1 = (TextView) vi.findViewById(R.id.txt1);
holder.btn1 = (Button) vi.findViewById(R.id.btn1);
holder.rel1 = (RelativeLayout) vi.findViewById(R.id.rel1);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.txt1.setText(data.get(position));
holder.rel1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast
.makeText(activity, "Click On TextView",
Toast.LENGTH_LONG).show();
}
});
holder.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "Click On Button", Toast.LENGTH_LONG)
.show();
}
});
return vi;
}
}
Used below layout files main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ListView android:layout_width="fill_parent" android:id="#+id/LIST"
android:layout_height="fill_parent" />
</LinearLayout>
Used listview.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout android:id="#+id/rel1" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/txt1"
android:text="Test Description"></TextView>
</RelativeLayout>
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/btn1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="ClickHere"
android:layout_alignParentRight="true"></Button>
</RelativeLayout>
</LinearLayout>
Used Above Code and you will get display toast message and you can changed as per you requirement.