"I was trying to create Toast message when user clicks on Description TextView and Like ImageButton. But the list_item is not responding to touch Events "
"I went through many other people answering about changing focus.But none of them are working"
EventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final EventsObject mEventsObject = mEventsAdapter.getItem(position);
final String mEventUrl = mEventsObject.geteLink();
Log.e(TAG, "Inside ListVIew");
final boolean status = mEventsObject.hasLiked();
//LikeButton likeButton = view.findViewById(R.id.heart_button);
TextView description = view.findViewById(R.id.eventDesc);
//final TextView likesCountTextView = view.findViewById(R.id.likesCount);
Toast.makeText(MainActivity.this, "Liked", Toast.LENGTH_SHORT).show();
description.setFocusable(false);
description.setFocusableInTouchMode(false);
description.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(mEventUrl)) {
Intent openLinkInBrowser = new Intent(Intent.ACTION_VIEW);
openLinkInBrowser.setData(Uri.parse(mEventUrl));
startActivity(openLinkInBrowser);
} else {
Toast.makeText(MainActivity.this, "Links are not provided", Toast.LENGTH_SHORT).show();
}
}
});
Button loveBtn = view.findViewById(R.id.loveButton);
loveBtn.setFocusable(false);
loveBtn.setFocusableInTouchMode(false);
loveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status) {
Toast.makeText(MainActivity.this, "Liked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(true);
} else {
Toast.makeText(MainActivity.this, "Disliked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(false);
}
}
});
}
XML for list_item is
?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:layout_margin="8dp"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:orientation="horizontal">
<TextView
android:id="#+id/organiser"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:paddingLeft="16dp"
android:textAllCaps="true"
android:textColor="#ffffff"
android:textSize="16sp"
android:textStyle="bold"
tools:text="Organiser" />
<TextView
android:id="#+id/dateOfEvent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:textColor="#ffffff"
android:textStyle="bold"
tools:text="12/03/20" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/organiserImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/events_circle"
android:padding="16dp"
android:src="#mipmap/ic_launcher"
android:textColor="#ffffff" />
<TextView
android:id="#+id/eventDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:gravity="fill"
android:textColor="#ffffff"
android:textSize="16sp"
tools:text="#string/test_event_desc" />
</LinearLayout>
<ImageButton
android:id="#+id/loveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
android:background="#drawable/events_love"
android:scaleType="center"
android:src="#drawable/love" />
<!--
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="0dp">
<com.like.LikeButton
app:icon_type="heart"
app:icon_size="18dp"
android:id="#+id/heart_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:circle_start_color="#ff2134"
app:circle_end_color="#000000"
/>
-->
<!--<TextView
android:id="#+id/likesCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
tools:text="10"
android:textColor="#ffffff"/>
</LinearLayout>-->
</LinearLayout>
"I would like to have list_item's responding to click events and showing toast message..
Please Help..
THanks in Advance !!"
It may be because you are trying to perform click inside item click listener of ListView.
You can fix it by creating a custom adapter for listview. Customer ListView Adapter
After creating this custom adapter you can get the reference of description and loveBtn and perform click operation on this.
Your adapter's getView() code will be like this-
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView=layoutInflater.inflate(R.layout.list_row, null);
TextView description=convertView.findViewById(R.id.eventDesc);
Button loveBtn=convertView.findViewById(R.id.loveButton);
}
description.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(mEventUrl)) {
Intent openLinkInBrowser = new Intent(Intent.ACTION_VIEW);
openLinkInBrowser.setData(Uri.parse(mEventUrl));
startActivity(openLinkInBrowser);
} else {
Toast.makeText(MainActivity.this, "Links are not provided", Toast.LENGTH_SHORT).show();
}
}
});
loveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status) {
Toast.makeText(MainActivity.this, "Liked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(true);
} else {
Toast.makeText(MainActivity.this, "Disliked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(false);
}
}
});
return convertView;
}
Related
I have an app which has Dialogbox with 3 Radios and RadioGroup,
So if the Light Radio is checked, after clicking Okay, the theme of the app will be changed to light theme.
If Dark is checked, after clicking Okay, the theme will be changed to night themeand if system it will be changed to system.
Toolbar:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar 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="wrap_content"
android:background="#FFF"
style="#style/TextAppearance.AppCompat.Widget.Button.Borderless.Colored"
android:elevation="0dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>
Menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/chooseTheme"
android:onClick="chooseTheme"
android:title="Choose Theme"
app:showAsAction="never"
tools:ignore="HardcodedText" />
</menu>
DialogBox:
<?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:gravity="center"
android:orientation="vertical">
<RadioGroup
android:id="#+id/themeGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="5dp"
android:gravity="center"
android:paddingStart="20dp"
android:paddingTop="20dp"
android:paddingEnd="20dp"
android:paddingBottom="5dp"
tools:ignore="UselessParent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginBottom="20dp"
android:text="Choose Theme"
android:textColor="#color/black"
android:textColorHint="#FFFFFF"
android:textSize="20sp"
tools:ignore="HardcodedText" />
<RadioButton
android:id="#+id/radioLight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginBottom="10dp"
android:buttonTint="#color/colorPrimary"
android:checked="true"
android:text="Light"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<RadioButton
android:id="#+id/radioDark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginBottom="10dp"
android:buttonTint="#color/colorPrimary"
android:text="Dark"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<RadioButton
android:id="#+id/radioSystem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginBottom="10dp"
android:buttonTint="#color/colorPrimary"
android:text="System"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginStart="80dp"
android:orientation="horizontal"
tools:ignore="RtlHardcoded">
<Button
android:id="#+id/btn_cancel"
style="?android:attr/borderlessButtonStyle"
android:layout_width="100dp"
android:layout_height="60dp"
android:gravity="center|center_vertical|fill_vertical"
android:scaleY="0.9"
android:text="Cancel"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/colorPrimary"
android:textSize="14sp"
tools:ignore="ButtonStyle,HardcodedText" />
<Button
android:id="#+id/btn_okay"
style="?android:attr/borderlessButtonStyle"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_marginStart="10dp"
android:gravity="center|center_vertical|fill_vertical"
android:scaleY="0.9"
android:text="Okay"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/colorPrimary"
android:textSize="14sp"
tools:ignore="ButtonStyle,HardcodedText" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
MainActivity:
public void chooseTheme(MenuItem item) {
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_theme,null);
Button btn_cancel = mView.findViewById(R.id.btn_cancel);
Button btn_okay = mView.findViewById(R.id.btn_okay);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
RadioButton radioLight = findViewById(R.id.radioLight);
final RadioButton radioDark =findViewById(R.id.radioDark);
RadioButton radioSystem =findViewById(R.id.radioSystem);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
I tried everything I knew, not I have no idea how to do it.
Thank you for attention!
The following will check which radio button is checked inside RadioGroup:
RadioGroup radioGroup = mView.findViewById(R.id.themeGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch(i) {
case R.id.radioLight:
setLightTheme();
Toast.makeText(getApplicationContext(),"Light mode",Toast.LENGTH_LONG).show();
break;
case R.id.radioDark:
setDarkTheme();
Toast.makeText(getApplicationContext(),"Dark mode",Toast.LENGTH_LONG).show();
break;
}
}
});
I found some points in your code.
for first, I think you have to find your radio buttons from your view too.
like this:
RadioButton radioLight = mView.findViewById(R.id.radioLight);
final RadioButton radioDark = mView.findViewById(R.id.radioDark);
RadioButton radioSystem = mView.findViewById(R.id.radioSystem);
And for the second I think you can use SharedPreferences to find what the user has checked, before calling dialog.dimiss.
That's what was I trying to achieve
Boolean night = false;
public void chooseTheme(MenuItem item) {
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
final View mView = getLayoutInflater().inflate(R.layout.dialog_theme,null);
Button btn_okay = mView.findViewById(R.id.btn_okay);
Button btn_cancel = mView.findViewById(R.id.btn_cancel);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
final RadioGroup themeGroup = mView.findViewById(R.id.themeGroup);
themeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#SuppressLint("NonConstantResourceId")
#Override
public void onCheckedChanged(RadioGroup themeGroup, int i) {
switch(i) {
case R.id.radioLight:
night = false;
break;
case R.id.radioDark:
night = true;
break;
}
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if(night){
sharedpref.setNightModeState(true);
Toast.makeText(getApplicationContext(),"Dark mode", Toast.LENGTH_LONG).show();
}
else if (!night){
sharedpref.setNightModeState(false);
Toast.makeText(getApplicationContext(),"Light mode",Toast.LENGTH_LONG).show();
}
alertDialog.dismiss();
restartApp();
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
SharedPref:
public class SharedPref {
SharedPreferences mySharedPref ;
public SharedPref(Context context) {
mySharedPref = context.getSharedPreferences("filename",Context.MODE_PRIVATE);
}
// this method will save the nightMode State : True or False
public void setNightModeState(Boolean state) {
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putBoolean("NightMode",state);
editor.apply();
}
// this method will load the Night Mode State
public Boolean loadNightModeState (){
Boolean state = mySharedPref.getBoolean("NightMode",false);
return state;
}
}
I have a recycler view displaying all posts made by a user in my app. I want the users to be able to click on one of the posts and be brought to a new fragment where they can only see the post they have chosen.
When I run my code, and click on one of the posts, the OnCLickListener isn't even triggered.
I have tried adding break points on public void OnClick but it never gets triggered. I have tried adding the OnClick to the onBindViewHolder but I understand this isn't a good idea.
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
public List<Post> postList;
private Context context;
private static OnItemClickListener onItemClickListener;
public PostAdapter(){
}
public interface OnItemClickListener{
void onItemClick(View v, int position);
}
public void updateList(List<Post> list){
postList = list;
notifyDataSetChanged();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
TextView postName, postUsername, postDate, postTime, postContent, postId;
PostViewHolder(View v) {
super(v);
this.postName = (TextView) itemView.findViewById(R.id.name);
this.postUsername = (TextView) itemView.findViewById(R.id.username);
this.postDate = (TextView) itemView.findViewById(R.id.date);
this.postTime = (TextView) itemView.findViewById(R.id.time);
this.postContent = (TextView) itemView.findViewById(R.id.content);
this.postId = (TextView) itemView.findViewById(R.id.postId);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = PostViewHolder.super.getAdapterPosition();
onItemClickListener.onItemClick(v, position);
System.out.println("doesn't even make it here");
}
});
}
}
public PostAdapter(List<Post> postList, Context context){
this.postList = postList;
this.context = context;
}
#Override
public PostAdapter.PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(context).inflate(R.layout.all_posts_layout, parent, false);
return new PostAdapter.PostViewHolder(view);
}
#Override
public void onBindViewHolder(PostViewHolder holder, int position){
Post post = postList.get(position);
holder.postUsername.setText(String.valueOf(post.getUsername()));
holder.postName.setText(String.valueOf(post.getName()));
holder.postDate.setText(String.valueOf(post.getDate()));
holder.postTime.setText(String.valueOf(post.getTime()));
}
#Override
public int getItemCount(){
return this.postList.size();
}
Any help would be very much appreciated!
<---card layout for each individual post---->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="130dp"
android:orientation="vertical">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="130dp">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="2dp"
android:elevation="60dp">
<RelativeLayout
android:id="#+id/search_term_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="1dp">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:textStyle="bold"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20sp" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/name"
android:text="Username"
android:textSize="18sp" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="56dp"
android:text="Date"
android:textSize="10sp" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/username"
android:layout_toRightOf="#+id/username"
android:layout_alignParentEnd="true"
android:paddingLeft="8dp"
android:text="Time"
android:textSize="10sp" />
<TextView
android:id="#+id/content"
android:layout_width="315dp"
android:layout_height="48dp"
android:layout_below="#+id/name"
android:layout_alignStart="#+id/name"
android:text="Content"
android:textSize="18sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/postId"
android:text="ID"
android:layout_below="#id/content"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</ScrollView>
</LinearLayout>
<---recycler view to display all posts------>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/filterBtn"
android:text="Filter"
android:background="#drawable/button"
android:layout_margin="2dp"
android:textColor="#color/common_google_signin_btn_text_dark_default"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/update_post_view"
android:layout_width="match_parent"
android:layout_marginTop="50dp"
android:padding="10dp"
android:layout_height="match_parent" />
</RelativeLayout>
Seems like your ScrollView consumes click event. Try to remove it or replace with NestedScrollView
You need to set it in onCreateViewHolder on that view. Also init it in the constructor.
Update code according to this
public static class PostViewHolder extends RecyclerView.ViewHolder, View.OnClickListener {
TextView postName, postUsername, postDate, postTime, postContent, postId;
PostViewHolder(View v) {
super(v);
//init view
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(v, getAdapterPosition());
}
}
**=> You just need to change onBindViewHolder() method code
=> Add click listener on this method.
=> Your code should be like this.**
#Override
public void onBindViewHolder(PostViewHolder holder, int position){
Post post = postList.get(position);
holder.postUsername.setText(String.valueOf(post.getUsername()));
holder.postName.setText(String.valueOf(post.getName()));
holder.postDate.setText(String.valueOf(post.getDate()));
holder.postTime.setText(String.valueOf(post.getTime()));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = PostViewHolder.super.getAdapterPosition();
onItemClickListener.onItemClick(v, position);
System.out.println("doesn't even make it here");
}
});
}
Here is my discussion.java which contains the RecyclerView
public class Discussion extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discussion);
RecyclerView mRecycleview =(RecyclerView)findViewById(R.id.cycleview);
mRecycleview.setLayoutManager(new LinearLayoutManager(this));
String[] use ={"a","b"};
String[] lo={"be","ndls"};
String[] ti={"12:00","11:00"};
String[] staus={"Today","Tommmorow"};
int[] posimg={R.drawable.img_post1,R.drawable.img_post2};
mRecycleview.setAdapter(new FeedAdapter(use,lo,ti,staus,posimg));
#NonNull
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Open Activity for posting", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Functionality for poll
}
}
Here is my FeedAdapter for the RecyclerView which is taking from resource layout file content.xml.
public class FeedAdapter extends
RecyclerView.Adapter<FeedAdapter.FeedViewHolder> {
private String[] userdata;
private String[] locdata;
private String[] timedata;
private int[] postdata;
private String[] statusdata;
public FeedAdapter(String[] userdata,String[] locdata,String[] timedata,String[] statusdata,int[] postdata){
this.userdata=userdata;
this.locdata=locdata;
this.postdata=postdata;
this.statusdata=statusdata;
this.timedata=timedata;
}
#Override
public FeedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view =inflater.inflate(R.layout.backupofcontent,parent,false);
return new FeedViewHolder(view);
}
#Override
public void onBindViewHolder( FeedAdapter.FeedViewHolder holder, int position) {
String user=userdata[position];
String loc=locdata[position];
String time=timedata[position];
String status=statusdata[position];
int post=postdata[position];
holder.username.setText(user);
holder.locationa.setText(loc);
holder.timea.setText(time);
holder.statusa.setText(status);
if(post==0)
holder.postimg.setVisibility(View.GONE);
else
holder.postimg.setImageResource(post);
}
#Override
public int getItemCount() {
return userdata.length;
}
public class FeedViewHolder extends RecyclerView.ViewHolder{
ImageView postimg;
TextView username;
TextView locationa;
TextView timea;
TextView statusa;
public FeedViewHolder(View itemView) {
super(itemView);
postimg=itemView.findViewById(R.id.imgView_postPic);
username=itemView.findViewById(R.id.user_name);
locationa=itemView.findViewById(R.id.Location);
timea=itemView.findViewById(R.id.Time);
statusa=itemView.findViewById(R.id.post_text);
}
}
}
Here is my content.xml from which adapter is taking the feed. I want to set up the onClickListner on the view id:likelayout" or like so that when it is clicked, some actions are to be performed. For now, a toast would be enough.
Please help me out how to do it.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:orientation="vertical"
tools:showIn="#layout/app_bar_main"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:text="User"
android:textSize="20sp" />
<TextView
android:id="#+id/Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/user_name"
android:layout_gravity="center|center_vertical"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:text="Time"
android:textSize="10sp" />
<TextView
android:id="#+id/Location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Time"
android:layout_gravity="center|center_vertical"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:text="Location"
android:textSize="10sp" />
<LinearLayout
android:id="#+id/layout_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Location"
android:layout_marginTop="10dp"
android:orientation="vertical">
<ImageView
android:id="#+id/imgView_postPic"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="fitCenter"
android:src="#drawable/img_post1" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="55dp"
android:layout_weight="1">
<TextView
android:id="#+id/post_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Status " />
</ScrollView>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="10dp"
android:gravity="center_vertical"
android:layout_above="#id/bottomnav">
<TextView
android:id="#+id/likecount"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="0"
android:gravity="center" />
<TextView
android:id="#+id/likecounttext"
android:layout_toRightOf="#id/likecount"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Liked"/>
<TextView
android:layout_toRightOf="#id/likecounttext"
android:layout_marginLeft="15dp"
android:id="#+id/countsepartor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="|"/>
<TextView
android:id="#+id/commentcount"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#id/countsepartor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"/>
<TextView
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/commentcount"
android:text="Comments"/>
</RelativeLayout>
<LinearLayout
android:id="#+id/bottomnav"
android:layout_width="match_parent"
android:layout_height="30dp"
android:weightSum="3"
android:layout_marginBottom="5dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/likelayout"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="25dp"
android:layout_height="wrap_content"
android:src="#drawable/like"/>
<TextView
android:id="#+id/like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Like"
android:layout_marginLeft="10dp"
android:layout_gravity="center_vertical"
android:textSize="15sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/commentlayout"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="25dp"
android:layout_height="wrap_content"
android:src="#drawable/comment"/>
<TextView
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Comment"
android:layout_marginLeft="10dp"
android:layout_gravity="center_vertical"
android:textSize="15sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/polllayout"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="25dp"
android:layout_height="wrap_content"
android:src="#drawable/poll"/>
<TextView
android:id="#+id/poll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Poll"
android:layout_marginLeft="10dp"
android:layout_gravity="center_vertical"
android:textSize="15sp"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
In your onBindViewHolder function, just add a click listener like the following.
#Override
public void onBindViewHolder( FeedAdapter.FeedViewHolder holder, int position) {
String user=userdata[position];
String loc=locdata[position];
String time=timedata[position];
String status=statusdata[position];
int post=postdata[position];
holder.username.setText(user);
holder.locationa.setText(loc);
holder.timea.setText(time);
holder.statusa.setText(status);
if(post==0)
holder.postimg.setVisibility(View.GONE);
else
holder.postimg.setImageResource(post);
holder.username.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Do something.
}
});
}
If you want to set up the click listener to the other UI elements in your list item, then just declare them like the way you have declared username, timea, statusa etc. and then add the listener to it.
Please keep in mind that, in order to make an ImageView clickable you need to add the clickable attribute to true in your layout file. For example, if you need to make your like image clickable, you need to add the clickable attribute like the following.
<ImageView
android:id="#+id/like_image"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/like"/>
In order to show a Toast on clicking the item, you need to have the Context of the Discussion activity while you are creating the adapter. So I would like to suggest you modify the constructor of the adapter like the following.
public class FeedAdapter extends
RecyclerView.Adapter<FeedAdapter.FeedViewHolder> {
private String[] userdata;
private String[] locdata;
private String[] timedata;
private int[] postdata;
private String[] statusdata;
// Add another extra variable to store context
// The context is necessary for showing toast
private Context context;
public FeedAdapter(String[] userdata, String[] locdata,String[] timedata, String[] statusdata, int[] postdata, Context context){
this.userdata = userdata;
this.locdata = locdata;
this.postdata = postdata;
this.statusdata = statusdata;
this.timedata = timedata;
this.context = context; // Initialize it here
}
#Override
public FeedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view =inflater.inflate(R.layout.backupofcontent,parent,false);
return new FeedViewHolder(view);
}
#Override
public void onBindViewHolder( FeedAdapter.FeedViewHolder holder, int position) {
String user=userdata[position];
String loc=locdata[position];
String time=timedata[position];
String status=statusdata[position];
int post=postdata[position];
holder.username.setText(user);
holder.locationa.setText(loc);
holder.timea.setText(time);
holder.statusa.setText(status);
if(post==0)
holder.postimg.setVisibility(View.GONE);
else
holder.postimg.setImageResource(post);
// Use the context here to show the Toast
holder.username.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Something", Toast.LENGTH_LOGN).show();
}
});
}
#Override
public int getItemCount() {
return userdata.length;
}
public class FeedViewHolder extends RecyclerView.ViewHolder{
ImageView postimg;
TextView username;
TextView locationa;
TextView timea;
TextView statusa;
public FeedViewHolder(View itemView) {
super(itemView);
postimg=itemView.findViewById(R.id.imgView_postPic);
username=itemView.findViewById(R.id.user_name);
locationa=itemView.findViewById(R.id.Location);
timea=itemView.findViewById(R.id.Time);
statusa=itemView.findViewById(R.id.post_text);
}
}
}
And to adopt the changes of the modified constructor, the adapter needs to be initialized like the following from your Discussion class.
mRecycleview.setAdapter(new FeedAdapter(use, lo, ti, staus, posimg, this));
Hope that helps!
same as the other views, in the FeedViewHolder class add a LinearLayout variable:
LinearLayout like;
then
like = itemView.findViewById(R.id.likelayout);
then in onBindViewHolder use :
holder.like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Like Layout was clicked
}
});
I try to show a Listview to show my data
This is main_fragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
ListView contactListView;
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) view.findViewById(R.id.txtName);
emailTxt = (EditText) view.findViewById(R.id.txtEmail);
phoneTxt = (EditText) view.findViewById(R.id.txtPhone);
addressTxt = (EditText) view.findViewById(R.id.txtAddress);
contactListView = (ListView) view.findViewById(R.id.listView);
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
if (contactAdapter != null) contactAdapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
final Button addContact = (Button) view.findViewById(R.id.btnadd);
nametxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addContact.setEnabled(!nametxt.getText().toString().trim().equals(""));
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
ArrayAdapter<import_fragment.Contact> contactAdapter;
ListView contactListView;
DatabaseHandler dbHandler;
int longClickedItemIndex;
public void onActivityResult(int reqCode, int resCode, Intent data) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
ImageView contactImageImgView;
contactImageImgView = (ImageView) getActivity().findViewById(R.id.ivContactImage);
if (resCode == Activity.RESULT_OK) {
if (reqCode == 1) {
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
{
ImageView contactImageImgView;
contactImageImgView = (ImageView) view.findViewById(R.id.ivContactImage);
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
if (dbHandler.getContactsCount() != 0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Contact Options");
menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Contact");
menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Contact");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO: Implement editing a contact
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(import_fragment.Contact contact) {
String name = contact.getName();
int contactCount = Contacts.size();
for (int i = 0; i < contactCount; i++) {
if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
return true;
}
return false;
}
private void populateList() {
contactAdapter = new ContactListAdapter(getActivity());
contactListView.setAdapter(contactAdapter);
}
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
private class ContactListAdapter extends ArrayAdapter<import_fragment.Contact> {
public ContactListAdapter(Context cntx) {
super (cntx, R.layout.fragment_import, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.fragment_import, parent, false);
import_fragment.Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
return view;
}
}
This is import_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="#+id/ivContactImage" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="91dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Contact Name"
android:id="#+id/contactName"
android:layout_gravity="left|center_vertical"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:id="#+id/phoneNumber"
android:layout_gravity="left|center_vertical"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:id="#+id/emailAddress"
android:layout_gravity="left|center_vertical"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:id="#+id/cAddress"
android:layout_gravity="left|center_vertical"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="My Contacts"
android:id="#+id/textView"
android:layout_gravity="center"
android:layout_marginTop="10dp"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView"
android:layout_gravity="center"/>
</LinearLayout>
My listview in import_fragment.xml, when i open import_fragment.xml in app its appear only Contact Name and Phone and Email and Address which is added in import_fragment.xml and not the new contact information which in database added by user.
You have to setAdapter in onCreateView. Currently you are populating the list in onCreateContextMenu. Moreover, after setting the adapter, you have to call notifyDataSetChanged() as well
Try this way, i have tried this in my machine and it show me listview properly , i have done with weightSum so it will be applicable for all devices , just change your xml file with below one
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4">
<ImageView
android:id="#+id/ivContactImage"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="vertical">
<TextView
android:id="#+id/contactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Contact Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginTop="5dp"
android:text="Phone" />
<TextView
android:id="#+id/emailAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Email" />
<TextView
android:id="#+id/cAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Address" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="My Contacts"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</LinearLayout>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
Change both of your LinearLayout's height to
android:layout_height="fill_parent"
Your listView is actually "there", it's just that the container (layout) of the listView isn't big enough to fit it.
EDIT:
You are defining two different list of Contacts there! Both activity and adapter class are referring to two different Contacts. Remove the one inside the onCreateView function.
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
Following some tutorials, I managed to make a custom list.
But the whole screen is just a list
And now want to put the list below the form. And to make the whole screen make scroll along with the list (see the last item in the list, the form needs to rise)
The log (Toasty) says that the item was added, but nothing appears. I do not know if the problem is in how I add, or is the way I try to display
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:fillViewport="true"
android:padding="5dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/cliente" />
<EditText
android:id="#+id/venda_form_cliente"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_cliente" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/produto" />
<EditText
android:id="#+id/venda_form_prod"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_produto" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/quantidade" />
<EditText
android:id="#+id/venda_form_qtd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/um" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/valor" />
<EditText
android:id="#+id/venda_form_valor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/desconto" />
<EditText
android:id="#+id/venda_form_desc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/zero" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/subtotal" />
<EditText
android:id="#+id/venda_form_subtotal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/venda_form_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="#string/adicionar" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="none" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And my activity
public class VendaFormActivity extends Activity {
private Cliente cliente;
// private Spinner condicaoSelect;
private Produto produto;
private TextWatcher somar;
private ItemVenda itemVenda;
private ListaAdapter listaAdapter;
private EditText inputQuantidade;
private EditText inputDesconto;
private EditText inputSubTotal;
private EditText inputProduto;
private EditText inputValor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_venda_form);
inputProduto = ((EditText) findViewById(R.id.venda_form_prod));
inputValor = ((EditText) findViewById(R.id.venda_form_valor));
((EditText) findViewById(R.id.venda_form_cliente)).setOnClickListener(new ClickListener(this, ClienteActivity.class, MainActivity.REQUEST_CLIENTE));
inputProduto.setOnClickListener(new ClickListener(this, ProdutoActivity.class, MainActivity.REQUEST_PRODUTO));
//condicaoSelect = (Spinner) findViewById(R.id.venda_form_condicao);
//new CondicaoHelper(this).popular(condicaoSelect);
bindCamposValores();
fazerLista();
bindBtnAdd();
}
private void limparCamposValores() {
inputDesconto.setText("0.00");
inputQuantidade.setText("1");
inputSubTotal.getText().clear();
inputProduto.getText().clear();
}
private void bindBtnAdd() {
((Button) findViewById(R.id.venda_form_btn)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
Double quantidade = Double.parseDouble( inputQuantidade.getText().toString() );
Double desconto = Double.parseDouble( inputDesconto.getText().toString() );
itemVenda = new ItemVenda();
itemVenda.setDesconto(desconto);
itemVenda.setProduto(produto);
itemVenda.setQuantidade(quantidade);
listaAdapter.setNotifyOnChange(true);
listaAdapter.getItens().add(itemVenda);
listaAdapter.notifyDataSetChanged();
Toast.makeText(getApplication(), "Foi", Toast.LENGTH_SHORT).show();
limparCamposValores();
} catch (Exception e) {
Toast.makeText(getApplication(), "Invalido", Toast.LENGTH_SHORT).show();
// NPE no produto
// NumberFormat nos valores
}
}
});
}
private void fazerLista() {
listaAdapter = new ListaAdapter(getApplicationContext());
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
}
static class ViewHolder {
protected TextView descricao;
protected TextView codigo;
protected TextView ean;
protected TextView referencia;
protected TextView quantidade;
protected TextView valor_unit;
protected TextView valor_item;
}
private class ListaAdapter extends ArrayAdapter<ItemVenda>{
private final Context context;
private final List<ItemVenda> itens;
public ListaAdapter(Context context) {
super(context, R.layout.produto_list);
this.context = context;
this.itens = new LinkedList<ItemVenda>();
}
public ListaAdapter(Context context, List<ItemVenda> itens) {
super(context, R.layout.produto_list, itens);
this.context = context;
this.itens = itens;
}
public List<ItemVenda> getItens() {
return itens;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.produto_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.descricao = (TextView) view.findViewById(R.id.descricao);
viewHolder.codigo = (TextView) view.findViewById(R.id.codigo);
viewHolder.ean = (TextView) view.findViewById(R.id.ean);
viewHolder.referencia = (TextView) view.findViewById(R.id.referencia);
viewHolder.quantidade = (TextView) view.findViewById(R.id.quantidade);
viewHolder.valor_unit = (TextView) view.findViewById(R.id.valor_unit);
viewHolder.valor_item = (TextView) view.findViewById(R.id.valor_item);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
ItemVenda item = itens.get(position);
holder.descricao.setText(item.getProduto().getNome());
holder.codigo.setText(item.getProduto().getCodigo());
holder.ean.setText(item.getProduto().getEan());
holder.referencia.setText(item.getProduto().getReferencia());
holder.quantidade.setText(item.getQuantidade().toString());
holder.valor_unit.setText(item.getProduto().getPreco().toString());
holder.valor_item.setText(item.getSubTotal().toString());
return view;
}
}
private void bindCamposValores() {
inputQuantidade = ((EditText) findViewById(R.id.venda_form_qtd));
inputDesconto = ((EditText) findViewById(R.id.venda_form_desc));
inputSubTotal = ((EditText) findViewById(R.id.venda_form_subtotal));
somar = new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
Double sub = 0.0;
try{
itemVenda = new ItemVenda();
itemVenda.setQuantidade(Double.parseDouble(inputQuantidade.getText().toString()));
itemVenda.setDesconto(Double.parseDouble(inputDesconto.getText().toString()));
itemVenda.setProduto(produto);
sub = itemVenda.getSubTotal();
} catch (Exception e) {
// algum campo não é numero/está vazio
}
inputSubTotal.setText(""+sub);
}
};
// Se mudar o valor
inputQuantidade.addTextChangedListener(somar);
inputDesconto.addTextChangedListener(somar);
// quando sair do campo
inputQuantidade.setOnFocusChangeListener(new Focus("1"));
inputDesconto.setOnFocusChangeListener(new Focus("0.00"));
}
private class Focus implements OnFocusChangeListener {
private final String padrao;
public Focus(String padrao){
this.padrao = padrao;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
Editable text = ((EditText) v).getText();
if(null == text || "".equals(text.toString())){
text.append(padrao);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_venda_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_copiar:
copiar();
return true;
case R.id.menu_simulacao:
simulacao();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void copiar() {
Toast.makeText(getApplication(), "Nada ainda", Toast.LENGTH_SHORT).show();
}
private void simulacao() {
Intent intent = new Intent(getApplicationContext(), SimulacaoPagtoActivity.class);
startActivityForResult(intent, MainActivity.REQUEST_SIMULACAO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == MainActivity.REQUEST_CLIENTE) {
if (resultCode == RESULT_OK) {
cliente = (Cliente) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
((EditText) findViewById(R.id.venda_form_cliente)).setText(cliente.getNome());
}
} else if (requestCode == MainActivity.REQUEST_PRODUTO) {
if (resultCode == RESULT_OK) {
produto = (Produto) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
inputProduto.setText(produto.getNome());
inputValor.setText(""+produto.getPreco());
somar.afterTextChanged(null);
}
} else if(requestCode == MainActivity.REQUEST_SIMULACAO){
// o que fazer quando voltar da simulação ?
}
}
}
Finally, my item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/descricao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#333"
android:textSize="16sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/codigo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CODIGO" />
<TextView
android:id="#+id/ean"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="EAN" />
<TextView
android:id="#+id/referencia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="REFERENCIA" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantidade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="QUANT." />
<TextView
android:id="#+id/valor_unit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR UNIT" />
<TextView
android:id="#+id/valor_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR ITEM" />
</LinearLayout>
</LinearLayout>
UPDATE
When I add an item in the list, nothing is shown. But after I click a TextEdit, and the virtual keyboard up, after typing some value, I close the keyboard, then the adapter.getView () is called and the list appears
I think I found your problem. Shouldn't the following code:
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
Be:
((ListView) findViewById(R.id.list)).setAdapter(listaAdapter);
instead?
You are trying to find a default Android view, rather than the view that you have created, which means that you are not actually setting the adapter for your ListView.
I am not sure about that, but if you want the list to be scrollable with the activity, you should use ScrollView, and then check if you scroll the list or the view itself. Try it
You can also try to see with debugger if the item was actually added to the list. I hope you will find an error.
Found the solution
1) The adapter have 2 constructors, but just 1 with List<ItemVenda> itens, and it isn't called.
I fixed it.
2) To add an item on the list, I need to call adapter.add() and not adapter.getItens().add()`. I think this trigger others methods.
3) Finally, to take the scroll list, and apply the scroll across the screen, I need to increase the size of the list. Then I override the method adapter.add(), and calculate the new height of the list, and add android:scrollbars="none" on ListView
Thanks to all, especially to #Marek