I am trying to alert multi selection dropdown check box in alert dialog like spinner but with check boxes in my android application ,can any one help here?
It may not work properly with respect to touch events. I guess that you will have to clone it and develop something like MultiSelectSpinner. You might wanna consult this answer for further detail.
Use customlayout in AlertDialog class using api, dialog.setconteView() method. You can add whatever widgets you wish in your custom layout
Use below code:-
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.setTitle("Title");
builder.setMultiChoiceItems(list, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked)
{
}
})
.setPositiveButton("OK",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog,
int id)
{
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id)
{
}
});
dialog = builder.create();
dialog.show();
As your view, Cant get the click events in AlertDialog.
Best solution for your Question. Just include the custom layout and get the Alertdialog Click events in your activity.
create a XML layout which you want to design
Include that XML layout in your activity through SetContentView()
Get the click events through your activity.
Please check this link for reference http://www.mkyong.com/android/android-custom-dialog-example/
Happy Coding :)
for Custom checkbox dropdown Dialogbox first we need to create MultiCheckAdaptar
public class MultiCheckAdaptar extends RecyclerView.Adapter<MultiCheckAdaptar.MyViewHolder> {
protected Context context;
private LayoutInflater inflater;
private ArrayList<ModelSpacialization> joblist ;
private String TYPE = "";
private int count = 0 ;
MultiCheckAdaptar.OnItemClickListener listener;
public interface OnItemClickListener {
void onClick(ModelSpacialization jobs, int pos , boolean type);
}
public MultiCheckAdaptar(Context context, ArrayList<ModelSpacialization> list, MultiCheckAdaptar.OnItemClickListener listener) {
this.context = context;
this.listener = listener;
if (context != null) {
inflater = LayoutInflater.from(context);
this.joblist= new ArrayList<>();
this.joblist.addAll(list);
}
}
public MultiCheckAdaptar.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_ckeck_item , parent, false);
MultiCheckAdaptar.MyViewHolder holder = new MultiCheckAdaptar.MyViewHolder(view);
return holder;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(#NonNull final MultiCheckAdaptar.MyViewHolder holder, final int position) {
ModelSpacialization item = joblist.get(position);
holder.txt_item.setText(item.getName());
if(item.isCheck())
holder.txt_item.setChecked(true) ;
else
holder.txt_item.setChecked(false) ;
holder.txt_item.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listener.onClick(item, position, false);
}
});
}
#Override
public int getItemCount() {
return joblist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
CheckBox txt_item ;
public MyViewHolder(View itemView) {
super(itemView);
txt_item = itemView.findViewById(R.id.txt_item);
}
}
}
layout_check_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/txt_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/size_10"
android:text="text"
android:textSize="#dimen/size_16" />
</RelativeLayout>
dialog_dropdwon_recyle.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:text="TItle"
android:id="#+id/tv_dialogTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#color/primary"
android:fontFamily="#font/poppins_medium"
android:textSize="#dimen/size_16"
tools:ignore="SpUsage" />
<ImageButton
android:id="#+id/btn_dialog_close"
android:layout_width="#dimen/size_25"
android:layout_height="#dimen/size_25"
android:layout_alignParentEnd="true"
android:layout_gravity="right"
android:background="#drawable/btn_grey_transparent"
android:elevation="1dp"
android:padding="#dimen/size_5"
android:src="#drawable/ic_close" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_dialog_close"
android:paddingHorizontal="#dimen/size_5"
android:orientation="vertical">
<EditText
android:id="#+id/edit_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search..."
android:visibility="gone" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/dialog_list"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/size_10"
android:scrollbars="none" />
<Button
android:id="#+id/btn_save"
android:layout_width="match_parent"
android:layout_height="#dimen/size_40"
android:layout_marginHorizontal="#dimen/size_10"
android:layout_marginTop="#dimen/size_10"
android:layout_marginBottom="#dimen/size_10"
android:background="#drawable/button_primary"
android:fontFamily="#font/poppins_medium"
android:text="Save"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="#dimen/size_15" />
</LinearLayout>
</RelativeLayout>
in Activity
Dialog dg_industries = new Dialog(context);
selected_spaci = new HashSet<>();
industresList.addAll(industries2);
selected_spaci = new HashSet<>();
dg_industries.setContentView(R.layout.dailogbox_dwondwon_recycle);
final RecyclerView indview = (RecyclerView) dg_industries.findViewById(R.id.dialog_list);
final TextView title = (TextView) dg_industries.findViewById(R.id.tv_dialogTitle);
title.setVisibility(View.VISIBLE);
title.setText("Select Specialization");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
indview.setLayoutManager(linearLayoutManager);
adaptor = new MultiCheckAdaptar(context, industresList, new MultiCheckAdaptar.OnItemClickListener() {
#Override
public void onClick(ModelSpacialization jobs, int pos, boolean type) {
jobs.setCheck(type);
selected_spaci.add(jobs);
Log.e("industries2", new Gson().toJson(industresList));
}
});
dg_industries.setCancelable(false);
dg_industries.show();
Related
I have a database, and I am trying to show the columns on cardview on my app.
Nothing wrong database side I guess. I have checked it, for example I can add items to the database. I can login-register. But when I add my items, I should be seeing them on the cardview after addition process.
When I add item on the database, it goes back to the recyclerview layout but shows nothing. Only an empty page.
No errors on the debug process until now.
Here is my cardview layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="15dp"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stock Name"
android:textColor="#color/colorPrimary" />
<TextView
android:id="#+id/barcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stock Code" />
<TextView
android:id="#+id/tvQuantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity" />
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price" />
<TextView
android:id="#+id/tvCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cost" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
recyclerlayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:orientation="horizontal"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
RECYCLER.JAVA
public class recycler extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private DatabaseHelper myDb;
private itemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler);
myDb = new DatabaseHelper(this);
Intent intent =getIntent();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.addMenu:
goToAddActivity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void goToAddActivity(){
Intent intent = new Intent(recycler.this, add.class);
startActivity(intent);
}
}
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ViewHolder> {
private List<list> mItemsList;
private Context mContext; //to inflate list layout
private RecyclerView mRecyclerV;
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView nameTxt;
public TextView quantityTxt;
public TextView priceTxt;
public TextView costTxt;
public TextView barcodeTxt;
public View layout;
public ViewHolder( View v) {
super(v);
layout = v;
nameTxt = (TextView) v.findViewById(R.id.itemName);
quantityTxt = (TextView) v.findViewById(R.id.tvQuantity);
priceTxt = (TextView) v.findViewById(R.id.tvPrice);
costTxt = (TextView) v.findViewById(R.id.tvCost);
barcodeTxt = (TextView) v.findViewById(R.id.barcode);
}
}
public void add(int position, list list) {
mItemsList.add(position, list);
notifyItemInserted(position);
}
public void remove(int position) {
mItemsList.remove(position);
notifyItemRemoved(position);
}
// Provide a suitable constructor (depends on the kind of dataset)
public itemAdapter(List<list> myDataset, Context context, RecyclerView recyclerView) {
mItemsList = myDataset;
mContext = context;
mRecyclerV = recyclerView;
}
// Create new views (invoked by the layout manager)
#Override
public itemAdapter.ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
//create a new view
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v =inflater.inflate(R.layout.activity_list, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final list list = mItemsList.get(position);
holder.nameTxt.setText("Stock Name: " + list.getName());
holder.barcodeTxt.setText("Barcode: " + list.getBarcode());
holder.quantityTxt.setText("Quantity: " + list.getQuantity());
holder.priceTxt.setText("Price: " + list.getPrice());
holder.costTxt.setText("Cost: " + list.getCost());
holder.layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Choose option");
builder.setMessage("Update or delete stock?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
goToUpdateActivity(list.getId());
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHelper dbHelper = new DatabaseHelper(mContext);
dbHelper.deleteRecord(list.getId(), mContext);
mItemsList.remove(position);
mRecyclerV.removeViewAt(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mItemsList.size());
notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
}
private void goToUpdateActivity(long listID){
Intent goToUpdate = new Intent(mContext, update.class);
goToUpdate.putExtra("listID", listID);
mContext.startActivity(goToUpdate);
}
#Override
public int getItemCount() {
return mItemsList.size();
}
}
I tried all the solution that i found here in the stackoverflow but it seems like none of them work.
Here is my main activity:
public class MerchantLocatorActivity extends AppCompatActivity implements OnMapReadyCallback {
public void init(){
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Spherical");
merchantLocatorResponseObject.setAddress("8007 Pioneer St, Kapitolyo, Mandaluyong, 1550 Metro Manila");
merchantLocatorResponseObject.setLatitude( 14.573249);
merchantLocatorResponseObject.setLongitude(121.057022);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Globe");
merchantLocatorResponseObject.setAddress("SCT, 584 Shaw Blvd, Mandaluyong, 1552 Metro Manila");
merchantLocatorResponseObject.setLatitude(14.585095);
merchantLocatorResponseObject.setLongitude(121.048893);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Sparndium");
merchantLocatorResponseObject.setAddress("Xavier, San Juan, 1502 Metro Manila");
merchantLocatorResponseObject.setLatitude(14.601918);
merchantLocatorResponseObject.setLongitude(121.042169);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
addMarker();
}
#OnClick(R.id.fab)
public void showAccToDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
View alertView = LayoutInflater.from(this).inflate(R.layout.dialog_biller, null);
alertDialogBuilder.setView(alertView);
final AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
final ListView listViewBillers = (ListView) dialog.findViewById(R.id.biller_institutions_listview);
if (listViewBillers != null) {
MerchantLocatorAdapter adapter = new MerchantLocatorAdapter(
this, R.layout.merchant_locator_adapter, merchantLocatorObjectArray);
listViewBillers.setAdapter(adapter);
listViewBillers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
geoLocate(merchantLocatorObjectArray,position);
DebugUtils.log("TESTTESTACTIVITYZXC");
DebugUtils.showToast(MerchantLocatorActivity.this,"HAHAHAH");
dialog.dismiss();
}
});
final EditText mSearchedittext = (EditText) dialog.findViewById(R.id.search_edittext);
mSearchedittext.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
final ArrayList<MerchantLocatorResponse> searchResultObject = new ArrayList<>();
searchResultObject.clear();
for (int hay = 0; hay <= merchantLocatorObjectArray.size() - 1; hay++) {
if ( merchantLocatorObjectArray.get(hay).getTitle().toLowerCase().contains(charSequence)) {
searchResultObject.add( merchantLocatorObjectArray.get(hay));
}
}
MerchantLocatorAdapter adapter = new MerchantLocatorAdapter(
MerchantLocatorActivity.this, R.layout.merchant_locator_adapter, searchResultObject);
listViewBillers.setAdapter(adapter);
listViewBillers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
geoLocate(searchResultObject,position);
dialog.dismiss();
}
});
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
}
i remove some part of the code because i think it's un necessary to include but let me know if there's some part that i need some clarification.
currently in my main activity, i'm calling a dialog that contains a listview and in my listview i have items.
My problem is i can't select any of my items even thought i have my setOnitemclick listener.
here is my adapter:
public class MerchantLocatorAdapter extends BaseAdapter {
private int resourceLayout;
private Context mContext;
ArrayList<MerchantLocatorResponse> merchantLocatorarray = new ArrayList<>();
public MerchantLocatorAdapter(Context context, int resource, ArrayList<MerchantLocatorResponse> merchantLocatorResponsesobjectArray) {
this.resourceLayout = resource;
this.mContext = context;
this.merchantLocatorarray = merchantLocatorResponsesobjectArray;
}
#Override
public int getCount() {
return merchantLocatorarray.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resourceLayout, parent, false);
}
TextView tt1 = (TextView) convertView.findViewById(R.id.field_name_textview);
TextView tt2 = (TextView) convertView.findViewById(R.id.field_value_textview);
ImageButton direction = (ImageButton) convertView.findViewById(R.id.direction);
tt1.setText(merchantLocatorarray.get(position).getTitle());
tt2.setText(merchantLocatorarray.get(position).getAddress());
return convertView;
}
}
here is my layout for my adapter:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="8dp"
android:elevation="3dp">
<LinearLayout
android:id="#+id/card_overflow"
android:focusable="true"
android:clickable="true"
android:background="#fff"
android:paddingLeft="16dp"
android:paddingRight="0dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:id="#+id/field_name_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_toLeftOf="#+id/branch_btns"
android:layout_alignParentLeft="true"
android:textSize="17sp"
android:textStyle="bold"
android:textColor="#color/edittext_text"
android:text="test"/>
<LinearLayout
android:id="#+id/branch_btns"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="horizontal"
>
<ImageButton
android:id="#+id/direction"
android:layout_width="50sp"
android:layout_height="wrap_content"
android:src="#drawable/ic_direction"
android:scaleType="fitCenter"
android:background="#color/translucent_clear_bg"
/>
<ImageButton
android:id="#+id/btn_branch_phone"
android:layout_width="50sp"
android:layout_height="wrap_content"
android:src="#drawable/ic_call_phone"
android:scaleType="fitCenter"
android:background="#color/translucent_clear_bg"
/>
</LinearLayout>
</RelativeLayout>
<View
android:id="#+id/seperator"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginBottom="5dp"
android:background="#android:color/darker_gray"
android:visibility="gone"
android:layout_marginTop="2dp"/>
<TextView
android:id="#+id/field_value_textview"
android:textSize="14sp"
android:textColor="#color/edittext_tint"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
i tried every solution that i found here in stackoverflow, and yet i can't still click my item. so please don't mark this as a duplicate.
if there's any part of the code that need clarification, please leave a comment and i'll answer as soon as possible. thanks.
Try to use Observable in you custom adapter:
// Define
private final PublishSubject<MerchantLocatorResponse> onItemClick = PublishSubject.create();
// Create the observable method
public Observable<ConversationMessage> getObservable(){
return onItemClick;
}
// Set the onClickListener into getView()
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick.onNext(merchantLocatorarray.get(position));
}
});
Then, in your main activity listen to it and handle the click:
#OnClick(R.id.fab)
public void showAccToDialog() {
// bla bla bla
listViewBillers.setAdapter(adapter);
listViewBillers.getObservable().subscribe(geoLocate);
// bla bla bla
}
Consumer<MerchantLocatorResponse> geoLocate = new Consumer<MerchantLocatorResponse>() {
#Override
public void accept(MerchantLocatorResponse mlr) {
// Code after click event
}
};
Add those library in your gradle:
implementation "io.reactivex.rxjava2:rxjava:2.1.5"
implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
Add convertView.setOnclickListener() in your code. Try below code in your adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resourceLayout, parent, false);
}
TextView tt1 = (TextView) convertView.findViewById(R.id.field_name_textview);
TextView tt2 = (TextView) convertView.findViewById(R.id.field_value_textview);
ImageButton direction = (ImageButton) convertView.findViewById(R.id.direction);
tt1.setText(merchantLocatorarray.get(position).getTitle());
tt2.setText(merchantLocatorarray.get(position).getAddress());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
return convertView;
} }
I'm trying to change the background color of the clicked item in RecyclerView from the adapter and it works, but the problem is when I click on position 1 it changes the color of position 1 and 7, and when I click on position 2 it changes the color of position 2 and 8 and so on ...
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.viewHolder> {
private ArrayList<String> name = new ArrayList<>();
private Context context;
boolean added = false;
public RecyclerViewAdapter(ArrayList<String> name, Context context) {
this.name = name;
this.context = context;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_horizontal_listview, parent, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(final viewHolder holder, final int position) {
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final Dialog dialog = new Dialog(view.getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.add_item_dialog_small);
Window window = dialog.getWindow();
window.setLayout(500, 450);
Button addToList = (Button) dialog.findViewById(R.id.addToList);
addToList.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ResourceAsColor")
#Override
public void onClick(View v) {
holder.cardView.setBackgroundColor(R.color.layer4);
dialog.dismiss();
}
});
dialog.show();
}
});
}
Edit:
here is the cardView :
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardView"
android:layout_width="300dp"
android:layout_height="320dp"
android:layout_margin="10dp"
android:background="#color/layer2"
card_view:cardCornerRadius="2dp">
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="2dp"
android:background="#color/layer3"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:id="#+id/textViewItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test Item"
android:textColor="#color/add_button"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/item_number"
android:textColor="#color/text_view_color"
android:textSize="20sp" />
<TextView
android:id="#+id/textViewItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:textColor="#color/second_color"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
In case of implementing options (such as favorite icon, checkbox, highlight or ...) to each row of a recyclerview, i think the best way is to create an object with your arbitrary parameter. for example for favorite a boolean parameter is best choice.
In your case you should create an object with a string and a boolean parameter with their setters and getters like below:
public class mObject {
private String name;
private boolean clicked;
// setters and getters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isClicked() {
return clicked;
}
public void setClicked(boolean clicked) {
this.clicked = clicked;
}
}
and then set your data in a list of this object then pass it to the adapter.
In onBindViewHolder, first check click value, if is true change the color. then in onClick method do both change the boolean value and background color and finally use notifyDataSetChanged(); for updating view.
Your adapter onBindViewHolder should looks like below:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder view,final int position) {
final MVH holder = (MVH) view;
holder.tv.setText(name.get(position).getName());
if (name.get(position).isClicked()){
holder.tv.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary));
} else {
holder.tv.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.add_item_dialog_small);
Window window = dialog.getWindow();
window.setLayout(500, 450);
Button addToList = (Button) dialog.findViewById(R.id.addToList);
addToList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (name.get(position).isClicked()){
name.get(position).setClicked(false);
holder.tv.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary));
} else {
name.get(position).setClicked(true);
holder.tv.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
}
dialog.dismiss();
notifyDataSetChanged();
}
});
dialog.show();
}
});
}
You can simplyfy your code using lambdas, that's for sure.
This:
addToList.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ResourceAsColor")
#Override
public void onClick(View v) {
holder.cardView.setBackgroundColor(R.color.layer4);
}
dialog.dismiss();
}
});
You can change to:
addToList.setOnClickListener((View v) -> {
holder.cardView.setBackgroundColor(R.color.layer4);
}
dialog.dismiss();
}
});
store var positionClicked in your adapter so it will be
onClick{positionClicked = position)
and then in your onBindViewHolder put
if(positionClicked==position){
//change color of element here//
}
I face this problem also. What you can do is set the background colour before click in onBindViewHolder method.
#Override
public void onBindViewHolder(final viewHolder holder, final int position) {
holder.cardView.setBackgroundColor(R.color.defaultBackgroundColour);
I have a ListView (shown below) that has a list of ingredients and how much of each ingredient each item has. How can I make it so there is some way to edit the number value when clicking on each ingredient?
Context menu and alert dialog so far, I also considered buttons to match the items but discovered it didn't work with the infinite listview. Thank you to anyone who helps me with this!
If you want to save the these values then you can create a child class and create list of this of child class.
you can use the onItemClickListner to update the value in the object and then do notifydatasetchange on the adapter this will do the trick.
or
Alternatively you can pass the two list in the adapter and update the list you want to update and do notifydatasetchange.
for e.g.:-
//MainActivity
public class MainActivity extends AppCompatActivity {
ListView recView;
ArrayList<Childclass> chobj=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recView= (ListView) findViewById(R.id.recView);
chobj.add(new Childclass("Tomato sauce","0.0"));
chobj.add(new Childclass("Chicken","0.0"));
chobj.add(new Childclass("Olives","0.0"));
ListAdapter lstadptr=new ListAdapter(MainActivity.this,chobj);
recView.setAdapter(lstadptr);
recView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//do something with edt.getText().toString();
chobj.get(position).setQuantity(edt.getText().toString());
((ListAdapter) recView.getAdapter()).notifyDataSetChanged();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
});
}}
Child Class
public class Childclass {
String name;
String quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public Childclass(String name, String quantity) {
this.name = name;
this.quantity = quantity;
}}
ListAdapter
public class ListAdapter extends ArrayAdapter {
ArrayList<Childclass> chobj;
Context context;
public ListAdapter(#NonNull Context context,ArrayList<Childclass> chobj) {
super(context, R.layout.recyclerow, chobj);
this.context = context;
this.chobj = chobj;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v;
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.recyclerow, parent, false);
TextView tv= (TextView) v.findViewById(R.id.txtrow);
TextView tv1= (TextView) v.findViewById(R.id.txtrow1);
tv.setText(chobj.get(position).getName());
tv1.setText(chobj.get(position).getQuantity());
return v;
}}
activity main
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.abhishek.kotlinprojecttest.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:paddingTop="10dp"
android:id="#+id/recView">
</ListView>
custom alert
<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:padding="10dp"
android:orientation="vertical">
<EditText
android:id="#+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
list row
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:id="#+id/rowcd">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="listTExt"
android:id="#+id/txtrow"
android:textColor="#000000"
android:textSize="16sp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="listTExt"
android:id="#+id/txtrow1"
android:textColor="#000000"
android:textSize="16sp"
android:gravity="center"/>
</android.support.v7.widget.CardView>
Hope this will help you
I know here we have a lot of questions like mine, but I don't know why none works for me.
My objective: I have an AlertDialog with a ListView with a check box in each row, I can select some of the items, and I wish to make an ArrayList with the elements selected.
For that reason, I'm calling the SetOnclickListener, I put a Log inside the method, but does nothing.
I tried with focusable and clickable almost everywhere, but my Log doesn't appear.
Here My alert Dialog
private void callAdditionalDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(ConfigProductActivity.this);
final View additionalView = layoutInflater.inflate(R.layout.dialog_additional, null);
additionalView.setFocusable(true);
// set the custom dialog components - text, buttons, accountants
TextView titleDialog = (TextView) additionalView.findViewById(R.id.title_additional);
titleDialog.setTypeface(boldFont);
Button buttonAccept = (Button) additionalView.findViewById(R.id.button_accept);
buttonAccept.setTypeface(boldFont);
Button buttonCancel = (Button) additionalView.findViewById(R.id.button_cancel);
buttonCancel.setTypeface(boldFont);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ConfigProductActivity.this);
alertDialogBuilder.setView(additionalView);
final AlertDialog alertD = alertDialogBuilder.create();
alertD.setCanceledOnTouchOutside(false);
//Fill object of additional
final ListView additionalListView = (ListView) additionalView.findViewById(R.id.list_additional);
TextView additionalNotFound = (TextView) additionalView.findViewById(R.id.additional_not_found);
if (!withoutModifiers){
additionalAdapter = new AdditionalAdapter(ConfigProductActivity.this, additionalList);
additionalListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
additionalListView.setAdapter(additionalAdapter);
final ArrayList<ModifierEntity> modifierList = new ArrayList<ModifierEntity>();
additionalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Object modifier = additionalListView.getAdapter().getItem(position).toString();
Log.d(TAG, "SOMETHIIIIING");
}
});
}
else{
additionalListView.setVisibility(View.GONE);
additionalNotFound.setVisibility(View.VISIBLE);
additionalNotFound.setTypeface(font);
buttonCancel.setVisibility(View.GONE);
}
//End of fill object of additional
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
buttonAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//additional.setText(additionalAdapter.getCount());
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
alertD.show();
}
Here my adapter:
public class AdditionalAdapter extends ArrayAdapter {
private static String TAG = AdditionalAdapter.class.getName();
private List<ModifierEntity> originalData = null;
private ConfigProductActivity activity;
private Typeface font;
private Typeface boldFont;
private static ModifierEntity modifier;
public AdditionalAdapter (ConfigProductActivity activity, List<ModifierEntity> listArray){
super(activity, R.layout.additional_item);
this.activity = activity;
this.originalData = listArray ;
font = Typeface.createFromAsset(activity.getAssets(),"HelveticaNeueThn.ttf");
boldFont = Typeface.createFromAsset(activity.getAssets(), "avgardm.ttf");
}
public static class Row
{
public TextView labelName;
public TextView labelPrice;
public CheckBox check;
}
#Override
public int getCount() {
return originalData.size();
}
#Override
public ModifierEntity getItem(int position) {
return originalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int colorFont = activity.getResources().getColor(R.color.brown_tataki);
final Row holder;
View rowView = convertView;
// reuse views
if (convertView == null) {
holder = new Row();
LayoutInflater inflater = LayoutInflater.from(activity);
rowView = inflater.inflate(R.layout.additional_item, null);
rowView.setClickable(true);
//rowView.setFocusable(false);
// configure view holder
holder.labelName = (TextView) rowView.findViewById(R.id.additional_name);
holder.labelPrice = (TextView) rowView.findViewById(R.id.additional_price);
holder.check = (CheckBox) rowView.findViewById(R.id.additional_check);
rowView.setTag(holder);
}
else {
holder = (Row) convertView.getTag();
// rowView.setClickable(true);
}
final ModifierEntity itm = originalData.get(position);
holder.labelName.setText(itm.getModifier_name());
holder.labelName.setTypeface(font);
holder.labelName.setTextColor(colorFont);
holder.labelPrice.setText(GlobalParameters.CURRENCY.concat(String.valueOf(itm.getModifier_cost())));
holder.labelPrice.setTypeface(boldFont);
holder.labelPrice.setTextColor(colorFont);
return rowView;
}
}
Here My Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange_tataki"
android:text="#string/additional_title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:id="#+id/title_additional"
android:padding="5dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title_additional"
android:gravity="center"
android:background="#color/white"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_additional"
android:divider="#color/brown_tataki"
android:dividerHeight="0.5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/list_additional"
android:gravity="center"
android:padding="10dp"
android:visibility="gone"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_not_found"
android:text="#string/additional_not_found"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttons"
android:layout_marginBottom="10dp"
android:layout_below="#+id/additional_not_found"
android:gravity="center"
android:layout_marginTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/button_cancel"
android:background="#color/green_tataki"
android:text="#string/button_cancel"
android:textSize="15sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_accept"
android:padding="10dp"
android:background="#color/green_tataki"
android:text="#string/button_accept"
android:textSize="15sp"
android:layout_marginLeft="15dp"
/>
</LinearLayout>
</RelativeLayout>
And Here my item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="QUESO"
android:singleLine="true"
android:padding="10dp"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/additional_price"
android:padding="10dp"
android:text="Bs. 500"
android:textColor="#color/brown_tataki"
android:layout_toRightOf="#id/additional_name"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="#+id/additional_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp" />
Using interfaces I can solve my problem, this link provided me the solution, and bassically consist in create an interface and implement in my activity.
Like this:
1.- Interface
public interface MyListener {
void folderClicked();
}
2.- Implements the interface in the activity
public class ActivityA extends Activity implements MyListener
3.- You will have to auto override the method folderClicked it will look like this:
#Override
protected void folderClicked() {
// Do your stuff here.
}
4.- Send the activity listener to the adapter with constructor like this:
MyAdpater adapter = new MyAdpater(ActivityA.this);
5.- Your adapter class your code should be like this:
public class TimeLineAdapter extends BaseAdapter {
private MyListener mListener;
public TimeLineAdapter(MyListener listener) {
super();
mListener = listener;
}
holder.iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onFolderClicked()
//code to do stuff when the image is clicked
}