How to successfully create a dialog fragment with recyclerview? - android

'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);

Related

problem adding more than one recycle view

hello hope you doing well !
I have problem hope find the solution with you
I have myadpter2 java
package com.example.adopt_pet_app;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class myadapter2 extends FirebaseRecyclerAdapter<Adopters,myadapter2.myviewholder>
{
public myadapter2(#NonNull FirebaseRecyclerOptions<Adopters> options1) {
super(options1);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Adopters model)
{
holder.adopname.setText(model.getAdoname());
holder.adoptphone.setText(model.getAdophone());
holder.adopemail.setText(model.getAdoemail());
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow2,parent,false);
return new myviewholder(view);
}
class myviewholder extends RecyclerView.ViewHolder
{
TextView adopname,adoptphone,adopemail;
public myviewholder(#NonNull View itemView)
{
super(itemView);
adopname=(TextView)itemView.findViewById(R.id.nametext);
adoptphone=(TextView)itemView.findViewById(R.id.phonetext);
adopemail=(TextView)itemView.findViewById(R.id.emailtext);
}
}
}
and I want call it here ..
package com.example.adopt_pet_app;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
public class Adopters_u_d extends AppCompatActivity {
RecyclerView recview2;
myadapter myadapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adopters_u_d);
recview2=(RecyclerView)findViewById(R.id.recview2);
recview2.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Adopters> options1;
options1 = new FirebaseRecyclerOptions.Builder<Adopters>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Adopters"), Adopters.class)
.build();
myadapter2=new myadapter(options1);
recview2.setAdapter(myadapter2);
}
}
but it gave me error when i try call options1 it say this
its becouse i made one before for my pet page and now i want make another for my Adopter i dont want change petinfo becouse i need it its same code but with name options instated options1 please help thank you

Iam not getting the background color of recyclerview item by button clicks outside of the recyclerview.?

package com.android_examples.recyclerview_android_examplescom;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Context context;
RecyclerView recyclerView;
LinearLayout relativeLayout;
Button button;
RecyclerView.Adapter recyclerViewAdapter;
RecyclerView.LayoutManager recylerViewLayoutManager;
String[] subjects =
{
"ANDROID",
"PHP",
"BLOGGER",
"WORDPRESS",
"JOOMLA",
"ASP.NET",
"JAVA",
"C++",
"MATHS",
"HINDI",
"ENGLISH"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
context = getApplicationContext();
relativeLayout = (LinearLayout) findViewById(R.id.relativelayout1);
button = (Button) findViewById(R.id.button);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recylerViewLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(recylerViewLayoutManager);
recyclerViewAdapter = new RecyclerViewAdapter(context, subjects);
recyclerView.setAdapter(recyclerViewAdapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recylerViewLayoutManager.findViewByPosition(10).setBackgroundColor(Color.BLUE);
}
});
}
}
activity_main:--
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android_examples.recyclerview_android_examplescom.MainActivity"
android:id="#+id/relativelayout1">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Change"
android:id="#+id/button"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:scrollbars="vertical"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
RecyclerAdapter:--
package com.android_examples.recyclerview_android_examplescom;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
String[] SubjectValues;
Context context;
View view1;
ViewHolder viewHolder1;
TextView textView;
public RecyclerViewAdapter(Context context1,String[] SubjectValues1){
SubjectValues = SubjectValues1;
context = context1;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ViewHolder(View v){
super(v);
textView = (TextView)v.findViewById(R.id.subject_textview);
}
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
view1 = LayoutInflater.from(context).inflate(R.layout.recyclerview_items,parent,false);
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position){
package com.android_examples.recyclerview_android_examplescom;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
String[] SubjectValues;
Context context;
View view1;
ViewHolder viewHolder1;
TextView textView;
public RecyclerViewAdapter(Context context1,String[] SubjectValues1){
SubjectValues = SubjectValues1;
context = context1;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ViewHolder(View v){
super(v);
textView = (TextView)v.findViewById(R.id.subject_textview);
}
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
view1 = LayoutInflater.from(context).inflate(R.layout.recyclerview_items,parent,false);
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position){
holder.textView.setText(SubjectValues[position]);
}
#Override
public int getItemCount(){
return SubjectValues.length;
}
}
holder.textView.setText(SubjectValues[position]);
}
#Override
public int getItemCount(){
return SubjectValues.length;
}
}
If i want to change the background of perticular item in Recyclerview from button click it will effect to only visible items only not for invisible means (first item is visible to user it will effect, but for last item it will not change the color )
Please Help me...
Thanks In advance..
OnItemClickListener Will give you the position of the view and you can use this below code for changing background of selected positioned row
private View SelectedItem;
private void BackColor(View view) {
if (SelectedItem != null) {
SelectedItem.setBackgroundColor(Color.TRANSPARENT);
}
view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
SelectedItem = view;
}
yourListview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){
BackColor(view);
}
}
First get the click action of convertView (Object of View) under this set view as
if(!convertView.isSelected()){
convertView.setSelected(true);
//here change the background color as selected.
}else{
convertView.setSelected(false);
//here change the background color as unselected.
}
Handel isSelected status in selection.
How to get the convertView Object reference

RecyclerView not showing items inside view pager fragment

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.

spinner onitemselected is not working as expected?

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

How to add a second layout in RecyclerView?

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.

Categories

Resources