set imageview onclick of current page in viewpager - android

Hello guys I am using viewpager in my application,
On a page there is one imageview. on this image view i set onclick listener.
When i am going to click on this imageview and change image on it, image of next page is get changed and current page image is remain unchanged.
How to change only image of current Page not next.
Here is my code.
public class KahawateViewPager extends android.support.v4.view.PagerAdapter{
Context kahawateViewPagerContext;
ImageView kahawateLikeUnlike_ImageView;
TextView kahawateIdiom_TextView;
TextView kahawateIdiomCountry_TextView;
LayoutInflater kahawateViewPagerLayout_LayoutInflater;
public KahawateViewPager(Context context)
{
this.kahawateViewPagerContext = context;
}
#Override
public int getCount()
{
//set page count only for testing
return 10;
}
#Override
public Object instantiateItem(ViewGroup container, final int position)
{
kahawateViewPagerLayout_LayoutInflater = (LayoutInflater) kahawateViewPagerContext.getSystemService(kahawateViewPagerContext.LAYOUT_INFLATER_SERVICE);
final View itemView = kahawateViewPagerLayout_LayoutInflater.inflate(R.layout.kahawate_viewpager_layout, container, false);
kahawateIdiom_TextView = (TextView) itemView.findViewById(R.id.textview_idieom);
kahawateIdiomCountry_TextView = (TextView) itemView.findViewById(R.id.textview_ideiomCountry);
kahawateLikeUnlike_ImageView = (ImageView) itemView.findViewById(R.id.imageView_favourite);
setKahawateData(position);
kahawateLikeUnlike_ImageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(kahawateViewPagerContext,"Current Position"+position,Toast.LENGTH_LONG).show();
if(kahawateLikeUnlike_ImageView.getTag().equals("like"))
{
kahawateLikeUnlike_ImageView.setImageResource(R.drawable.unlike);
kahawateLikeUnlike_ImageView.setTag("unlike");
} else
{
kahawateLikeUnlike_ImageView.setImageResource(R.drawable.like);
kahawateLikeUnlike_ImageView.setTag("like");
}
}
//}
});
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == ((LinearLayout)object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
void setKahawateData(int ID)
{
//setdefault image only for testing
kahawateLikeUnlike_ImageView.setImageResource(R.drawable.like);
kahawateLikeUnlike_ImageView.setTag("like");
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#f4e9cd">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="1"
android:gravity="right"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView_favourite"
android:layout_gravity="right"
android:src="#drawable/unlike"
android:clickable="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="9"
android:orientation="vertical"
android:paddingLeft="5dp"
android:paddingRight="5dp">
<TextView
android:id="#+id/textview_idieom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_weight="8"
android:gravity="center"
android:text="Big Data"
/>
<TextView
android:id="#+id/textview_ideiomCountry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="2"
android:gravity="right"
android:text="Small Data"
android:paddingRight="5dp"/>
</LinearLayout>
here is screen the star image i want to set/reset
Here toast current position 0 is showing but when i click the position 1 page imageview get set. and if I click on page1 image page 2 imageview get set and so on.
How set/reset current pages imageview?

Try implementing getItemPosition method like this:
#Override
public int getItemPosition(Object object) {
return mDataSource.indexOf(object);
}
This way you'll get the position of each item correctly

I think you have to set viewpager.setOffsetLimit(totalnumberofpage);
where totalnumberofpage is the count of list
Second thing is make ViewHolder class
private class ViewHolder {
TextView textViewItem;}
and use it like this way:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
// The convertView argument is essentially a "ScrapView" as described is Lucas post
// http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
// It will have a non-null value when ListView is asking you recycle the row layout.
// So, when convertView is not null, you should simply update its contents instead of inflating a new row layout.
if(convertView==null){
// inflate the layout
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
// well set up the ViewHolder
viewHolder = new ViewHolderItem();
viewHolder.textViewItem = (TextView) convertView.findViewById(R.id.textViewItem);
// store the holder with the view.
convertView.setTag(viewHolder);
}else{
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
viewHolder = (ViewHolderItem) convertView.getTag();
}
// object item based on the position
ObjectItem objectItem = data[position];
// assign values if the object is not null
if(objectItem != null) {
// get the TextView from the ViewHolder and then set the text (item name) and tag (item ID) values
viewHolder.textViewItem.setText(objectItem.itemName);
viewHolder.textViewItem.setTag(objectItem.itemId);
}
return convertView;}

Related

In Android, how to update GridView cell element control when selected?

I am trying to implement a GridView in Android to display a list of Products as mentioned in below image:
With Custom Button and Grid List I am implemented this.
I want to know, how can I make this Product Button Red when I select it. Or in other words, I want to get the selected cell item object and change the background color to red, TextViews text color to white. Plus, at the same time, I want to make all remaining cell items to default white background and text color to purple.
I am new to android, any help would be great support. Thanks in advance. Here is my code:
GridView in Fragment
<GridView
android:id="#+id/grid_Products"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:horizontalSpacing="10dp"
android:gravity="center"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp />
In ProductFragment class in onCreateView() method, I am binding the productModels to gridView
List<ProductModel> productModels;
GridView gdGridView=(GridView)(view.findViewById(R.id.grid_Products));
adapter = new ProductButtonAdaptor(view.getContext(), productModels);
gdGridView.setAdapter(adapter);
product_button.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btn_product_red"
android:id="#+id/pnl_ProudctButton"
android:orientation="vertical">
<LinearLayout
android:paddingTop="10dp"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="5"
android:gravity="center"
android:layout_gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/lbl_ProductName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="bottom"
android:text="5"
android:layout_marginRight="2dp"
android:textColor="#color/purple"
android:textAlignment="center"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/lbl_ProductCurrency"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:gravity="bottom"
android:text="QAR"
android:textAlignment="center"
android:textColor="#color/purple"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>
<View
android:id="#+id/lbl_ProductSeparator"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:layout_margin="4dp"
android:background="#color/purple" />
<TextView
android:id="#+id/lbl_ProductCategory"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:gravity="top"
android:text="International"
android:textAlignment="center"
android:textColor="#color/purple"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="16dp" />
</LinearLayout>
ProductButtonAdpater class:
public class ProductButtonAdaptor extends ArrayAdapter<ProductModel> implements AdapterView.OnItemClickListener
{
private Context context;
private final List<ProductModel> productModels;
private int selected = -1;
public ProductButtonAdaptor(Context context, List<ProductModel> productValues)
{
super(context, R.layout.button_product, productValues);
this.context = context;
this.productModels = productValues;
}
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null)
{
gridView = new View(context);
// get layout from button_product.xml
gridView = inflater.inflate(R.layout.button_product, null);
// set value into textview
TextView lbl_ProductName = (TextView)gridView.findViewById(R.id.lbl_ProductName);
TextView lbl_ProductCurrency = (TextView)gridView.findViewById(R.id.lbl_ProductCurrency);
TextView lbl_ProductCategory = (TextView)gridView.findViewById(R.id.lbl_ProductCategory);
lbl_ProductName.setText(productModels.get(position).getCode());
lbl_ProductCurrency.setText(productModels.get(position).getCurrency());
lbl_ProductCategory.setText(productModels.get(position).getCategoryName());
}
else
{
gridView = (View)convertView;
}
if (selected == position)
{
TextView lbl_ProductName = (TextView)gridView.findViewById(R.id.lbl_ProductName);
TextView lbl_ProductCurrency = (TextView)gridView.findViewById(R.id.lbl_ProductCurrency);
TextView lbl_ProductCategory = (TextView)gridView.findViewById(R.id.lbl_ProductCategory);
View lbl_ProductSeperator = (View)gridView.findViewById(R.id.lbl_ProductSeparator);
LinearLayout pnl_ProductButton = (LinearLayout)gridView.findViewById(R.id.pnl_ProudctButton);
lbl_ProductName.setTextColor(ContextCompat.getColor(context, R.color.vodafone_white));
lbl_ProductCurrency.setTextColor(ContextCompat.getColor(context, R.color.vodafone_white));
lbl_ProductCategory.setTextColor(ContextCompat.getColor(context, R.color.vodafone_white));
lbl_ProductSeperator.setBackgroundColor(ContextCompat.getColor(context, R.color.vodafone_white));
pnl_ProductButton.setBackground(ResourcesCompat.getDrawable(context.getResources(), R.drawable.btn_product_red, null));
}
else
{
//setup the other cells
TextView lbl_ProductName = (TextView)gridView.findViewById(R.id.lbl_ProductName);
TextView lbl_ProductCurrency = (TextView)gridView.findViewById(R.id.lbl_ProductCurrency);
TextView lbl_ProductCategory = (TextView)gridView.findViewById(R.id.lbl_ProductCategory);
View lbl_ProductSeperator = (View)gridView.findViewById(R.id.lbl_ProductSeparator);
LinearLayout pnl_ProductButton = (LinearLayout)gridView.findViewById(R.id.pnl_ProudctButton);
lbl_ProductName.setTextColor(ContextCompat.getColor(context, R.color.vodafone_purple));
lbl_ProductCurrency.setTextColor(ContextCompat.getColor(context, R.color.vodafone_purple));
lbl_ProductCategory.setTextColor(ContextCompat.getColor(context, R.color.vodafone_purple));
lbl_ProductSeperator.setBackgroundColor(ContextCompat.getColor(context, R.color.vodafone_purple));
pnl_ProductButton.setBackground(ResourcesCompat.getDrawable(context.getResources(), R.drawable.btn_product_white, null));
}
return gridView;
}
#Override
public int getCount()
{
return productModels.size();
}
#Override
public ProductModel getItem(int position)
{
return productModels.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selected = position;
this.notifyDataSetChanged();
//adapter.notifyDataChanged();
//parent.invalidate();
//view.invalidate();
}
}
this is the updated code
I think you want to do it programatically (not styles).
So,
You have to declare a int selected; variable which stores index of a selected cell (or -1 if none is selected). Then, you have to implement onClickListener on each cell and change selected value when any element is tapped and redraw all data grid cells using notify... method.
After that, do not forget to change the setup block of colors and other parameters of each sell in the correspond method of the adapter.
inside onCreate() method:
gridview.setOnItemClickListener(adapter);
your class:
public class ProductButtonAdaptor extends BaseAdapter implemets onItemClickListener {
private Context context;
private final ProductModel[] productModels;
private int selected = -1;
public ProductButtonAdaptor(Context context, ProductModel[] productValues) {
this.context = context;
this.productModels = productValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from button_product.xml
gridView = inflater.inflate(R.layout.button_product, null);
// set value into textview
TextView lbl_ProductName = (TextView) gridView.findViewById(R.id.lbl_ProductName);
TextView lbl_ProductCurrency = (TextView) gridView.findViewById(R.id.lbl_ProductCurrency);
TextView lbl_ProductCategory = (TextView) gridView.findViewById(R.id.lbl_ProductCategory);
lbl_ProductName.setText(productModels[position].Name);
lbl_ProductCurrency.setText(productModels[position].Currency);
lbl_ProductCategory.setText(productModels[position].CategoryName);
} else {
gridView = (View) convertView;
}
if (selected == position) {
//setup selected cell
//for example
gridView.setBackgroundColor(Color.red);
} else {
//setup the other cells
gridView.setBackgroundColor(Color.white);
}
return gridView;
}
#Override
public int getCount() {
return productModels.length;
}
#Override
public Object getItem(int position) {
return productModels[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selected = position;
adapter.notifyDataChanged();
//you can pass the grid as a paramater of constructor if you need it
grid.invalidateViews();
}

Android how to inflate ListView with two different items

I am trying to inflate listView with two different layouts using ArrayAdapter.
I want to show some user posts. If it contains a picture use one layout if it does not use second.
I am doing so far
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
boolean noImg = post.mImgUrl1 == null && post.mImgUrl2 == null;
if (convertView == null){
if (noImg)
convertView = LayoutInflater.from(getContext()).inflate(R.layout.post_item_no_img, parent ,false);
else
convertView = LayoutInflater.from(getContext()).inflate(R.layout.post_item, parent, false);
}
if (noImg == false) {
mTitle = (TextView) convertView.findViewById(R.id.tv_titlePost);
mText = (TextView) convertView.findViewById(R.id.tv_textPost);
mImage = (ImageView) convertView.findViewById(R.id.iv_postimg);
}
else {
mNoImgTitle = (TextView) convertView.findViewById(R.id.tv_noImgTitle);
mNoImgText = (TextView) convertView.findViewById(R.id.tv_noImgText);
}
if (noImg) {
mNoImgTitle.setText(post.mTitle);
mNoImgText.setText(post.mText);
if (post.mImgUrl1 != null)
Glide.with(mImage.getContext()).load(post.mImgUrl1).into(mImage);
else Glide.with(mImage.getContext()).load(post.mImgUrl2).into(mImage);
}
else {
mNoImgTitle.setText(post.mTitle);
mNoImgText.setText(post.mText);
}
return convertView;
}
But i realized that textviews from second layout cannot be found by findViewById function. And it always returns a null-pointer.
What are my solutions ? Should i make only one Layout and somehow trick it using visibility ? Or there is a way ?
There are a few different scenarios that you will see when getView() is called:
convertView is null: In this case just create the layout that you need depending upon noImg;
convertView is defined but is of the wrong type. In this case, you will need to discard the old view and create the one you need;
convertView is defined but is of the correct type, in which case, we do nothing with it.
The following code is one approach to making sure that you are always working with the right layout and can find the ids that you expect. This code uses a tag in the inflated layout to identify the layout type that can be checked.
if (convertView == null || noImg != (boolean) convertView.getTag()) {
// Either there is no view defined or it is the wrong type. Create
// the type we need.
if (noImg) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.post_item_no_img, parent, false);
} else {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.post_item, parent, false);
}
convertView.setTag(noImg);
}
With BaseAdapter you can create more complex layouts. Try using it.
Here is the example of use for your situation:
Activity:
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] data={"false","false","true","true","false","true"};
ListView listViewTest=(ListView)findViewById(R.id.listViewTest);
TestAdapter testAdapter=new TestAdapter(data);
listViewTest.setAdapter(testAdapter);
}
}
Adapter:
public class TestAdapter extends BaseAdapter {
private String[] data;
TestAdapter(String data[]) {
this.data = data;
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int i) {
return data[i];
}
#Override
public long getItemId(int i) {
return i;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (data[position].equals("false")) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_no_img, parent, false);
} else if (data[position].equals("true")) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_img, parent, false);
}
return convertView;
}
}
Layouts:
activity_main
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listViewTest"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
list_item_no_img
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewTest"
android:gravity="center"
android:layout_centerInParent="true"
android:textSize="32sp"
android:text="Test"/>
</RelativeLayout>
list_item_img
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewTest"
android:gravity="center"
android:layout_centerInParent="true"
android:textSize="32sp"
android:text="Test"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/textViewTest"
android:layout_toEndOf="#+id/textViewTest" />
</RelativeLayout>
Result:

The TextViews populated in my GridView appear blank

I'm using a Gridview to show a list of skills. The code runs fine, even populates exact number of items according to my array. However, the TextView that should display the item names is blank.
This is the code for my gridview adapter
SkillsAdapter.java
public class SkillsAdapter extends BaseAdapter {
private Context context;
private final String[] skillValues;
public SkillsAdapter(Context context, String[] skillValues) {
this.context = context;
this.skillValues = skillValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.skills_single_item, null);
// set value into textview
textView = (TextView) gridView.findViewById(R.id.single_label);
textView.setText(skillValues[position]);
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return skillValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
This is the code for my layout file skills_single_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:background="#drawable/rounded_corners">
<TextView
android:id="#+id/single_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_gravity="center"/>
</RelativeLayout>
The array is not null. The error occurs somewhere around here
// set value into textview
textView = (TextView) gridView.findViewById(R.id.single_label);
textView.setText(skillValues[position]);
Change your layout Item XML with this your I used your Adapter class its work fine at my side
it may help you
<?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:background="#FFFFFF"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:id="#+id/single_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="8dp"
android:textColor="#000000" />
</RelativeLayout>
Set test in your text view out of if condition like:
if (convertView == null) {
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.skills_single_item, null);
// set value into textview
textView = (TextView) gridView.findViewById(R.id.single_label);
} else {
gridView = (View) convertView;
}
textView.setText(skillValues[position]);
Move following line out of if-else blocks
textView.setText(skillValues[position]);
Like
if (convertView == null) {
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.skills_single_item, null);
textView = (TextView) gridView.findViewById(R.id.single_label);
} else {
gridView = (View) convertView;
}
// set value into textview
textView.setText(skillValues[position]);
I recommend you to read android ViewHolder pattern.

Material Design Navigation Adapter footer / header (How add footer ?)

I have a problem, I want put a footer in my navigation left.
I have a header that depends of code, but I don't know how I can add a footer, I tried all stuff, but not work any :
I read this post : Android 5.0 - Add header/footer to a RecyclerView , but my code is so diferent.
Thanks.
I put my code XML and java :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private static final int TYPE_HEADER = 0; // Declaring Variable to Understand which View is being worked on
// IF the viaew under inflation and population is header or Item
private static final int TYPE_ITEM = 1;
private String mNavTitles[]; // String Array to store the passed titles Value from MainActivity.java
private int mIcons[]; // Int Array to store the passed icons resource value from MainActivity.java
private String name; //String Resource for header View Name
private int profile; //int Resource for header view profile picture
private String email; //String Resource for header view email
Context context;
// Creating a ViewHolder which extends the RecyclerView View Holder
// ViewHolder are used to to store the inflated views in order to recycle them
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
int Holderid;
TextView textView;
ImageView imageView;
ImageView profile;
TextView Name;
TextView email;
Context contxt;
public ViewHolder(View itemView,int ViewType,Context c) { // Creating ViewHolder Constructor with View and viewType As a parameter
super(itemView);
contxt = c;
itemView.setClickable(true);
itemView.setOnClickListener(this);
// Here we set the appropriate view in accordance with the the view type as passed when the holder object is created
if(ViewType == TYPE_ITEM) {
textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml
imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml
Holderid = 1; // setting holder id as 1 as the object being populated are of type item row
}
else{
Name = (TextView) itemView.findViewById(R.id.name); // Creating Text View object from header.xml for name
email = (TextView) itemView.findViewById(R.id.email); // Creating Text View object from header.xml for email
profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic
Holderid = 0; // Setting holder id = 0 as the object being populated are of type header view
}
}
#Override
public void onClick(View v) {
Toast.makeText(contxt,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
}
}
MyAdapter(String Titles[], int Icons[], String Name, String Email, int Profile, Context passedContext){ // MyAdapter Constructor with titles and icons parameter
// titles, icons, name, email, profile pic are passed from the main activity as we
mNavTitles = Titles; //have seen earlier
mIcons = Icons;
name = Name;
email = Email;
profile = Profile; //here we assign those passed values to the values we declared here
this.context = passedContext;
//in adapter
}
//Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is
//Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml
// if the viewType is TYPE_HEADER
// and pass it to the view holder
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false); //Inflating the layout
ViewHolder vhItem = new ViewHolder(v,viewType,context); //Creating ViewHolder and passing the object of type view
return vhItem; // Returning the created object
//inflate your layout and pass it to view holder
} else if (viewType == TYPE_HEADER) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false); //Inflating the layout
ViewHolder vhHeader = new ViewHolder(v,viewType,context); //Creating ViewHolder and passing the object of type view
return vhHeader; //returning the object created
}
return null;
}
//Next we override a method which is called when the item in a row is needed to be displayed, here the int position
// Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us
// which view type is being created 1 for item row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(holder.Holderid ==1) { // as the list view is going to be called after the header view so we decrement the
// position by 1 and pass it to the holder while setting the text and image
holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
}
else{
holder.profile.setImageResource(profile); // Similarly we set the resources for header view
holder.Name.setText(name);
holder.email.setText(email);
}
}
// This method returns the number of items present in the list
#Override
public int getItemCount() {
return mNavTitles.length+1; // the number of items in the list will be +1 the titles including the header view.
}
// Witht the following method we check what type of view is being passed
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
}
My header.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.onpocket.alcover.Fragment_0_6"
>
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="178dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/contenedor_img_2_1_6_3"
android:id="#+id/l1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.3" >
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/barra_lateral_img_0_1"
android:layout_marginLeft="16dp"
android:layout_marginTop="38dp"
android:id="#+id/circleView"
android:adjustViewBounds="false" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.9"
android:background="#af000000"
android:gravity="center_vertical"
android:focusableInTouchMode="false"
android:id="#+id/l3"
android:focusable="false">
<LinearLayout
android:orientation="horizontal"
android:layout_width="15dp"
android:layout_height="match_parent" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:text="text"
android:textSize="14sp"
android:textStyle="bold"
android:id="#+id/name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"
android:id="#+id/email"
android:textColor="#ffffffff" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
<!--
<?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="178dp"
android:orientation="vertical"
android:weightSum="1"
android:background="#drawable/contenedor_img_2_1_6_3" android:scaleType="centerCrop">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="true"
android:background="#color/opacity"
android:gravity="center_vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textColor="#ffffff"
android:text="Akash Bangad"
android:textSize="14sp"
android:textStyle="bold"
/>
<!– android:background="#7f000000"
android:singleLine="false"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="15dp"
android:paddingBottom="5dp"–>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="inicio_texto_empresa"
android:textColor="#ffffffff"
android:layout_marginLeft="16dp"
/>
</LinearLayout>
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/barra_lateral_img_0_1"
android:layout_marginLeft="16dp"
android:layout_marginTop="38dp"
android:id="#+id/circleView"
android:adjustViewBounds="false" />
</RelativeLayout>-->
Main Activity (How To call)
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES, ICONS, NAME, EMAIL, PROFILE, this); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
});
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
but I don't know how I can add a footer
you can do the same thing you did for the HeaderView. Treat the footer as one of the items of RecyclerView:
Your getItemCount will returns
#Override
public int getItemCount() {
return mNavTitles.length+2;
}
and you will have a method call isPositionFooter
private boolean isPositionHeader(int position) {
return position == getItemCount() - 1;
}
you would change getItemViewType accordingly to return the footer type:
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
} else if (isPositionFooter(position)) {
return TYPE_FOOTER;
}
return TYPE_ITEM;
}

listview item cannot be click in android

i have created Custom listview and i add a onclick listener to it but it was not working.the below is my code
This is my MainActivity Class:
public class MainActivity extends Activity {
public boolean[] status;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// Attach the adapter to a ListView
listView = (ListView) findViewById(R.id.lvUsers);
populateUsersList();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
Toast.makeText(getBaseContext(),"Hello", Toast.LENGTH_SHORT).show();
}
});
}
private void populateUsersList() {
// Construct the data source
ArrayList<User> arrayOfUsers = User.getUsers();
// Create the adapter to convert the array to views
CustomUsersAdapter adapter = new CustomUsersAdapter(this, arrayOfUsers);
listView.setAdapter(adapter);
}
}
this is my adapter class:
public class CustomUsersAdapter extends ArrayAdapter<User> {
public CustomUsersAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
// Return the completed view to render on screen
return convertView;
}
}
i want to get the value from listview when the appropriate toggle button is checked .and want to save the value of toggle button and the appropriate text in arraylist.
this my xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvUsers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This is my second xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
>
<TextView
android:id="#+id/tvName"
android:layout_alignBaseline="#+id/ivUserIcon"
android:layout_toRightOf="#+id/ivUserIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="6dp"
android:text="Sarah"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvHometown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvName"
android:layout_below="#+id/tvName"
android:text="San Marco"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/tvName"
android:layout_marginRight="15dp"
android:text="ToggleButton" />
</RelativeLayout>
Change your RelativeLayout to
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:descendantFocusability="blocksDescendants"
>
This view will block any of its descendants from getting focus, even if they are focusable.
You must set the button on clicklistener.
tgbtn.setOnClickListener(new OnClickListener(position));
Dont know it it works but try anything like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
tgbtn.setOnClickListener(new OnButtonClickListener(position));
// Return the completed view to render on screen
return convertView;
}
then a class for the ButtonClick:
private class OnButtonClickListener implements OnClickListener {
int _postion;
// constructor
public OnButtonClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
}
}
below of your code that there is a ListView and you wanna able clicked function to the list item, write this code.
public void onListItemClick(ListView parent, View v, int position, long id){
// do something here
// Example below make a toast message
Toast.makeText(getApplicationContext(), "I clicked item of list number " + position,Toast.LENGTH_SHORT).show();
}

Categories

Resources