I've got some problem with my RecyclerView. I want to add a bubble widget that creates a new circle with message (just like in messanger). Problem is that bubble must be placed in separate XML layout file so I cannot add it to the "item" layout that I have in my adapter. Inside bubble layout I have simply TextView, however I don't want to display normal text - it would be too easy ;) I want to display data I get from API. Another words - I need access to TextView that is inside Bubble layout in my adapter. Please, help! :)
Here's my Adapter class
package pl.krakowskascenamuzyczna.ksmcalendar.Adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.w3c.dom.Text;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.txusballesteros.bubbles.BubbleLayout;
import com.txusballesteros.bubbles.BubblesManager;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import pl.krakowskascenamuzyczna.ksmcalendar.Activities.CalendarActivity;
import pl.krakowskascenamuzyczna.ksmcalendar.Activities.DisplayConcertActivity;
import pl.krakowskascenamuzyczna.ksmcalendar.MySingleton;
import pl.krakowskascenamuzyczna.ksmcalendar.R;
import pl.krakowskascenamuzyczna.ksmcalendar.data.Concert;
import pl.krakowskascenamuzyczna.ksmcalendar.data.Thumbnail;
public class ConcertAdapter extends RecyclerView.Adapter<ConcertAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Context context;
NetworkImageView mNetworkImageView;
private MySingleton mySingleton;
private List<Concert> concertList = new ArrayList();
public ConcertAdapter(Context context, List<Concert> concerts) {
this.inflater = LayoutInflater.from(context);
this.concertList = concerts;
this.context = context;
}
public void setListConcert(ArrayList<Concert> concertList) {
this.concertList = concertList;
notifyItemRangeChanged(0, concertList.size());
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.concert_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final float screenWidthPx = holder.itemView.getResources().getDisplayMetrics().widthPixels;
Concert current = concertList.get(position);
Log.d("mLog", current.getUrl());
holder.image.setImageUrl(current.getUrl(), MySingleton.getInstance().getImageLoader());
holder.image.getLayoutParams().height = (int) (screenWidthPx * 0.75);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date concertDate = new Date();
try {
concertDate = format.parse(current.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
DateTime dt = new DateTime();
DateTime currentDate = dt.withZone(DateTimeZone.forID("Europe/Warsaw"));
int days = Days.daysBetween(new DateTime(currentDate), new DateTime(concertDate)).getDays();
holder.date_btn.setText(String.valueOf(days));
}
#Override
public int getItemCount () {
return concertList.size();
}
public void showDisplay(int position){
Intent intent = new Intent(context, DisplayConcertActivity.class);
intent.putExtra("position", position);
intent.putExtra("content", concertList.get(position).getContent());
intent.putExtra("date", concertList.get(position).getDate());
intent.putExtra("url", concertList.get(position).getUrl());
context.startActivity(intent);
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private NetworkImageView image;
private Button date_btn;
public MyViewHolder(View itemView) {
super(itemView);
image = (NetworkImageView) itemView.findViewById(R.id.concerts_niv);
date_btn = (Button) itemView.findViewById(R.id.date_btn);
image.setOnClickListener(this);
}
#Override
public void onClick(View v) {showDisplay(getAdapterPosition());
}
}
}
And here's my Bubble layout:
<com.txusballesteros.bubbles.BubbleLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/bubble_tv"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/profile_decorator"
android:scaleType="centerCrop"
android:src="#drawable/profile_decorator"
android:textColor="#fff"
/>
</com.txusballesteros.bubbles.BubbleLayout>
You can pass your bubble TextView as aprameter to the adapter constructor.
private TextView mBubbleTextView;
public ConcertAdapter(Context context, List<Concert> concerts, TextView bubbleTextView) {
this.inflater = LayoutInflater.from(context);
this.concertList = concerts;
this.context = context;
this.mBubbleTextView = bubbleTextView;
}
Now you have the bubble TextView in your adapter, so can update it from any method.
Related
'Here is my adapter class code and when i long pressed on an item it should show a alert dialog box to delete that item ..I want to call DialogFragmnent from recycled view. How to resolve this show method from Recyclerview adapter. How is it possible?
Adaptorclass
package com.example.recyclerview1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedList;
import androidx.appcompat.app.AppCompatActivity;
public class MyAdaptor extends RecyclerView.Adapter<MyAdaptor.MyViewHolder>{
ArrayList<Student> l;
Context c;
public MyAdaptor (Context ctx,ArrayList<Student> list)
{
l=list;
c =ctx;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent,false);
strong textMyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
final Student s = l.get(position);
holder.t1.setText(s.getName());
holder.t2.setText(s.getCnic());
int currentposition=position;
final Student infodata= l.get(position);
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view)
{
Dialogclass dialog = new Dialogclass();
dialog.show(((AppCompatActivity)c).getSupportFragmentManager(), "Fragment");
removieitem(infodata);
Toast.makeText(c," Removed item "+position,Toast.LENGTH_LONG).show();
return false;
}
});
holder.linearLayout.setOnClickListener(new View.OnClickListener () {
#Override
public void onClick(View view)
{
Toast.makeText(c,s.getName()+" "+s.getCnic(),Toast.LENGTH_LONG).show();
}
});
}
private void removieitem(Student infodata) {
int position=l.indexOf(infodata);
l.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return l.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView t1,t2;
LinearLayout linearLayout;
public MyViewHolder(#NonNull View itemView)
{
super(itemView);
t1 = itemView.findViewById(R.id.txtname);
t2 = itemView.findViewById(R.id.txtcnic);
linearLayout = itemView.findViewById(R.id.mylayout);
}
}
}
Dialogclass
package com.example.recyclerview1;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.DialogFragment;
public class Dialogclass extends AppCompatDialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
It show the Error as....java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
at com.example.recyclerview1.MyAdaptor$1.onLongClick(MyAdaptor.java:49)
MainActivity.java
package com.example.recyclerview1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Student> list= list = new ArrayList<>();
RecyclerView rc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rc = findViewById(R.id.myrec);
Student s1 = new Student("Ahmed","34198723482");
Student s2 = new Student("Ahmed","34198723482");
Student s3 = new Student("Ahmed","34198723482");
Student s4 = new Student("Ahmed","34198723482");
Student s5 = new Student("Ahmed","34198723482");
Student s6 = new Student("Ahmed","34198723482");
Student s7 = new Student("Ahmed","34198723482");
Student s8 = new Student("Ahmed","34198723482");
Student s9 = new Student("Ahmed","34198723482");
Student s0 = new Student("Ahmed","34198723482");
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);
list.add(s8);
list.add(s9);
list.add(s0);
MyAdaptor myAdaptor = new MyAdaptor(getApplicationContext(),list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rc.setLayoutManager(linearLayoutManager);
rc.setAdapter(myAdaptor);
}
}
You can create custom dialog.
Add RecyclerView in your XML file layout if don't have any layout create it.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fl_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="300dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
Then initialize your RecyclerView and any other view in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//TODO Change 'frag_mdialog' to your custom view XML layout
View v = inflater.inflate(R.layout.frag_mdialog, container, false);
view = v;
// Do all the stuff to initialize your custom view
RecyclerView recyclerView = view.findViewById(R.id.rv_dialog);
return v;
}
I hope this help you.
Problem at line below
dialog.show(((AppCompatActivity)c).getSupportFragmentManager()
c is Context so cannot be cast to AppCombatActivity
Try Sending Activity object in MyAdaptor class like below
public MyAdaptor (Activity ctx,ArrayList<Student> list)
and In MainActivity.java class you need to pass Activity object like this below -
MyAdaptor myAdaptor = new MyAdaptor(MainActivity.this,list);
When I click the chat tab the recycler view doesn't show the items inside the fragment. It was working before when I had it in a activity. Now it doesnt seem to show the items when running the app. I have tried debugging and the likes and still can't seem to find out the problem. Any help will be grateful, thanks!
ChatFragment.java
package com.swampass.nauticalapp;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.swampass.nauticalapp.model.ActiveChatConvo;
import com.swampass.nauticalapp.model.User;
import java.util.ArrayList;
public class ChatsFragment extends Fragment {
private RecyclerView recyclerView;
private DatabaseReference mRef;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<User> users;
private FirebaseAuth mAuth;
private ActiveChatConvo adapter;
public ChatsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View penis = inflater.inflate(R.layout.fragment_chats, container, false);
// Inflate the layout for this fragment
mRef = FirebaseDatabase.getInstance().getReference("Users");
mRef.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
users = new ArrayList<>();
adapter = new ActiveChatConvo(users,getContext());
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
String name = postSnapshot.child("Name").getValue(String.class);
String email = postSnapshot.child("Email").getValue(String.class);
String pic = postSnapshot.child("image").getValue(String.class);
users.add(new User(name,email,pic));
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Recycler View
recyclerView = (RecyclerView) penis.findViewById(R.id.active_chats);
//ActiveChatConvo adapter = new ActiveChatConvo(users,this);
Context c = getContext();
mLinearLayoutManager = new LinearLayoutManager(getActivity());
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
return inflater.inflate(R.layout.fragment_chats, container, false);
}
}
ActiveChatConvo.java
package com.swampass.nauticalapp.model;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.swampass.nauticalapp.ChatConversationActivity;
import com.swampass.nauticalapp.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Peter on 6/6/2017.
*/
public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder> {
private ArrayList<User> mUsers;
private Context mContext;
public ActiveChatConvo(ArrayList<User> users, Context dick) {
mUsers = users;
mContext = dick;
}
private Context getContext() {
return mContext;
}
#Override
public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
User user = mUsers.get(position);
// Set item views based on your views and data model
TextView name = holder.mItemName;
name.setText(user.getName());
TextView description = holder.mItemDescription;
description.setText(user.getEmail());
ImageView pic = holder.mItemImage;
Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mItemImage;
private TextView mItemName;
private TextView mItemDescription;
private LinearLayout layout;
final LinearLayout.LayoutParams params;
public ViewHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Context context = itemView.getContext();
Intent intent = new Intent(context, ChatConversationActivity.class);
// intent.putExtra("image_id", );
intent.putExtra("descripion", mItemDescription.getText().toString());
intent.putExtra("name", mItemName.getText().toString());
context.startActivity(intent);
}
}
}
fragment_chat.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.swampass.nauticalapp.ChatsFragment">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.RecyclerView
android:id="#+id/active_chats"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#color/colorAccent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
In the ChatFragment.java, you should be returning the view you have created - penis, and not inflater.inflate(R.layout.fragment_chats, container, false). In this case, an empty view is returned and not the one you are creating.
I did not add spinner on my layout
I did not use addView function
code
Spinner spinner = new Spinner(MainActivity.this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, myArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
//this place is never called
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
I called spinner like this:
spinner.performClick();
After this I click one of my item which in my array and then I expect to fire onItemSelected but it never fires.
the problem is
onitemselected is never called.
thanks in advance
Try this,
1.Create a custom adapter.
2.set click Listener to textview in adapter.(so you can get position in adapter)
3.according to positon do whatever u feel like.
CustomModel.
public class CustomModel {
private String id;
private String description;
public char[] name;
public CustomModel() {
}
public CustomModel(String id, String description) {
this.id = id;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return description;
}
public void setName(String description) {
this.description = description;
}
}
Activity.
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import adapter.CustomAdapter;
import models.CustomModel;
import utils.SessionManager;
import static android.R.attr.id;
import static android.R.id.text1;
public class spinner extends AppCompatActivity {
private SessionManager sessionManager;
private List<CustomModel> myArray=new ArrayList<CustomModel>();
CustomModel customModel;
LinearLayout container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnre);
container = (LinearLayout) findViewById(R.id.container);
customModel=new CustomModel();
customModel.setName("Select a number");
myArray.add(customModel);
for(int i=0;i<10;i++)
{
customModel=new CustomModel();
customModel.setName(String.valueOf(i));
myArray.add(customModel);
}
LinearLayout.LayoutParams spinnerParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams textParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
spinnerParamas.setMargins(0,50,0,0);
Spinner spinner = new Spinner(spinner.this);
spinner.setLayoutParams(spinnerParamas);
spinner.setId(0);
CustomAdapter customAdapter=new CustomAdapter(spinner.this,myArray,spinner);
spinner.setAdapter(customAdapter);
container.addView(spinner);
}
}
Adapter
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ciomp.global.R;
import models.CustomModel;
/**
* Created by ciomp on 11/23/2016.
*/
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List<CustomModel> mList=new ArrayList<CustomModel>();
private LayoutInflater mLayoutInflater;
private String mType=null;
private Spinner mSpinner;
int one=0;
public CustomAdapter(Context mContext, List<CustomModel> list, Spinner spin) {
this.mContext=mContext;
this.mList=list;
mSpinner=spin;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
CustomAdapter.ViewHolder holder=null;
LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView==null){
convertView = layoutInflater.inflate(R.layout.customlayout, null);
holder = new CustomAdapter.ViewHolder();
holder.textView2=(TextView)convertView.findViewById(R.id.txt_text1);
convertView.setTag(holder);
}
else {
holder = (CustomAdapter.ViewHolder) convertView.getTag();
}
CustomModel classModel=mList.get(position);
holder.textView2.setText(classModel.getName());
holder.textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(one==0)
{
mSpinner.performClick();
one=1;
}
else if(one==1)
{
Toast.makeText(mContext, mList.get(position).getName(), Toast.LENGTH_SHORT).show();
try {
Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
method.invoke(mSpinner);
} catch (Exception e) {
e.printStackTrace();
}
one=0;
}
}
});
return convertView;
}
static class ViewHolder{
TextView textView2;
}
}
spinnre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_marginRight="5dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
customlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/txt_text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginBottom="13dp"
android:gravity="center"
android:layout_marginTop="13dp"
android:layout_marginLeft="5dp"
android:paddingLeft="5dp"
android:textColor="#000"
/>
/>
</LinearLayout>
hope it may help you.
In order to programatically select item from spinner. you need to call
spinner.setSelection(1);
Whereas 1 in the index, you want to select
My app is to perform ListView. When it was running, the error message notified that "Unfortunately, App has stopped". Here is my code.
package com.example.admin.customadapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Nation>nationifo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.ListViewNation);
nationifo = new ArrayList<>();
nationifo.add(new Nation("VietNam",1945));
nationifo.add(new Nation("Malaysia",1975));
nationifo.add(new Nation("Laos",1943));
NationAdapter adp = new NationAdapter(
MainActivity.this,
R.layout.nation_list,
nationifo
);
listView.setAdapter(adp);
}
}
Nation.java
package com.example.admin.customadapter;
public class Nation {
public String name;
public Integer year;
public Nation(String Name, Integer Year){
Name = name;
Year = year;
}
}
NationAdapter.java
package com.example.admin.customadapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class NationAdapter extends BaseAdapter {
Context mycontext;
int mylayout;
List<Nation>arrayNation;
public NationAdapter (Context context, int layout, List<Nation>nationList){
mycontext = context;
mylayout = layout;
arrayNation = nationList;
}
public int getCount() {
return arrayNation.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(mylayout,null);
TextView txtv1 = (TextView) convertView.findViewById(R.id.textView);
txtv1.setText(arrayNation.get(position).name);
TextView txtv2 =(TextView) convertView.findViewById(R.id.textView2);
txtv2.setText(String.valueOf(arrayNation.get(position).year));
return convertView;
}
}
nation_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background = "#ffffff">
<TextView
android:textColor="#ff0400"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/textView" />
<TextView
android:textColor="#0022ff"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2" />
</LinearLayout>
My Android Studio is 2.2. But I don't think that this version is diferrent to another.
try to use the following
convertView = inflater.inflate(mylayout,parent,false);
instead of
convertView = inflater.inflate(mylayout,null);
I am having problem with changing color of Textview in custom Listview.
My xml file is column.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cid"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textSize="30dp"
android:visibility="gone"/>
<TextView
android:id="#+id/cname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25dp"
android:textColor="#f60505" />
<TextView
android:id="#+id/amt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textColor="#2ec31d"
android:textAlignment="center" />
</LinearLayout>
and ListViewAdapter.java goes like this
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by XYZ on 06-05-2016.
*/
public class ListViewAdapter extends BaseAdapter {
public ArrayList<HashMap<String,String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String,String>>list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.colunm_row,null);
holder = new ViewHolder();
holder.textFirst=(TextView)convertView.findViewById(R.id.cid);
holder.textSecond=(TextView)convertView.findViewById(R.id.cname);
holder.textThird=(TextView)convertView.findViewById(R.id.amt);
txtFirst = (TextView) convertView.findViewById(R.id.cid);
txtSecond = (TextView)convertView.findViewById(R.id.cname);
txtThird = (TextView) convertView.findViewById(R.id.amt);
convertView.setTag(holder);
}else {
holder =(ViewHolder)convertView.getTag();
holder.textFirst.setText("");
holder.textSecond.setText("");
holder.textThird.setText("");
}
HashMap<String,String> map= list.get(position);
/* txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));*/
holder.textFirst.setText(map.get(FIRST_COLUMN));
holder.textSecond.setText(map.get(SECOND_COLUMN));
holder.textThird.setText(map.get(THIRD_COLUMN));
return convertView;
}
static class ViewHolder{
TextView textFirst;
TextView textSecond;
TextView textThird;
}
}
DisplayActivity :
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AccDisplay extends AppCompatActivity {
private ArrayList<HashMap<String,String>> arrayList;
Cursor c;
SQLiteDatabase db;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acc_display);
ListView listView = (ListView)findViewById(R.id.AcclistView);
arrayList = new ArrayList<HashMap<String, String>>();
db = openOrCreateDatabase("AccountsDB", Context.MODE_PRIVATE,null);
c=db.rawQuery("select c.c_id ,c.c_name, ((select CASE WHEN (sum(cr.amount)) IS Null THEN 0 ELSE sum(cr.amount) END from credit_master cr where c.c_id=cr.c_id) ) - ((select CASE WHEN (sum(d.amount)) IS NULL THEN 0 ELSE sum(d.amount) END from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c ORDER BY c.c_name ASC",null);
//c=db.rawQuery("select c.c_id ,c.c_name, ((select sum(cr.amount) from credit_master cr where c.c_id=cr.c_id) ) - ((select sum(d.amount) from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c",null);
try {
if (c!=null){
if(c.moveToFirst()){
Map<String,String> tem = new HashMap<String ,String>();
tem.clear();
arrayList.clear();
listView.setAdapter(null);
int cnt = c.getCount();
Toast.makeText(getApplicationContext(),""+cnt,Toast.LENGTH_SHORT).show();
do {
tem = new HashMap<String,String>();
tem.clear();
tem.put(FIRST_COLUMN, c.getString(0));
tem.put(SECOND_COLUMN,c.getString(1));
tem.put(THIRD_COLUMN,c.getString(2));
arrayList.add((HashMap<String, String>) tem);
}while (c.moveToNext());
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),"Error"+e,Toast.LENGTH_LONG).show();
}
ListViewAdapter adapter = new ListViewAdapter(this,arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) (view.findViewById(R.id.cid));
int str = Integer.parseInt(tv.getText().toString());
Toast.makeText(AccDisplay.this,"Clicked"+str,Toast.LENGTH_LONG).show();
Intent intent = new Intent(AccDisplay.this,Details.class);
intent.putExtra("name",str);
startActivity(intent);
}
});
}
protected void onRestart(){
super.onRestart();
Intent inte = getIntent();
finish();
startActivity(inte);
}
}
I am using same layout file for three different activities.
I want to display different color of each TextView in Different Activity.
I have tried this but didn't work
LayoutInflator inflator = (LayoutInflator)getSystemService(Context.LAYOUT_INFLATOR_SERVICE);
View vi = inflator.inflate(R.layout.column,null);
TextView tv = (TextView) vi.findViewById(R.id.amt);
tv.setTextColor(Color.BLACK);
I can change color of TextView in OnItemClickListener but i want to display color while displaying data.
I am having Debit/Credit activity which uses same Adapter class and column.xml layout for displaying data in listview.
I want to display TextView1 in black color font and TextView2 in Green color with big font size in Activity 1. and different color in different activity.
You can pass different flags in adapter constructor to adapter for identifying activity if same adapter you are using for other activities, and can put conditions according to the flag set colors to the TextView in adapter programmatically. textView.setTextColor(put_your_color);