在RecyclerAdapter中单击按钮时增加徽章值

时间:2017-11-03 09:49:21

标签: android mysql notifications counter badge

我正在开发一个应用程序,允许用户通过单击AlertDialog的“确定”按钮来增加通知徽章的值。该值将存储在MySQL数据库中。

AlertDialog在RecyclerAdapter中设置,通知Badge在Main活动中设置,我使用Utils类作为徽章计数。

请问实施该方法的最佳方式是什么?

更新

专柜课

public interface Counter {
public void setCounter(int count);}

适配器类

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {

Context c;
ArrayList<criteria> critere;
private Counter counter;

public RecyclerAdapter(Context c, ArrayList<criteria> critere, Counter counter) {
    this.c = c;
    this.critere = critere;
    this.counter = counter;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    Integer count;
    TextView criteria, update;
    ImageButton btn1, btn2, btn3, btn4;
    Boolean click1, click2, click3, click4;
    ImageView image;
    RelativeLayout layout;
    LinearLayout ranked;
    ImageView check;
    private ItemClickListener itemClickListener;
    public ClipData.Item currentItem;
    public View view;

    public MyViewHolder(View itemView) {
        super(itemView);
        view = itemView;

        btn1 = itemView.findViewById(R.id.btn1);
        btn2 = itemView.findViewById(R.id.btn2);
        btn3 = itemView.findViewById(R.id.btn3);
        btn4 = itemView.findViewById(R.id.btn4);

        layout = itemView.findViewById(R.id.check_view);
        ranked = itemView.findViewById(R.id.rank_layout);
        check = itemView.findViewById(R.id.check_image);

        criteria = itemView.findViewById(R.id.criteria_text);
        image = itemView.findViewById(R.id.criteria_pic);

    }

}

@Override
public RecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(c).inflate(R.layout.recycler_model,parent,false);
    return new MyViewHolder(v);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

    final criteria crit = critere.get(position);

    final String name = crit.getName();

    //BIND
    holder.criteria.setText(name);
    holder.layout.setVisibility(View.GONE);

    PicassoClient.downloadImage(c,crit.getImageurl(),holder.image);

    holder.btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

                LayoutInflater li = LayoutInflater.from(c);
                View dialogView = li.inflate(R.layout.custom_dialog_rank, null);

                AlertDialog.Builder dialog = new AlertDialog.Builder(c);

                dialog.setView(dialogView);
                dialog.setIcon(R.drawable.btn_press_rank1);
                dialog.setCancelable(false);
                dialog.setTitle(R.string.crit1);
                dialog.setMessage("The " + name + " was very unsatisfiying");
                final EditText userInput = (EditText) dialogView
                        .findViewById(R.id.comment_field);

                dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        //checked.setVisibility(View.VISIBLE);
                        holder.layout.setVisibility(View.VISIBLE);
                        holder.check.setVisibility(View.VISIBLE);
                        holder.check.bringToFront();
                        holder.ranked.setVisibility(View.INVISIBLE);
                        counter.setCounter(1);

                    }
                })
                        .setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //checked.setVisibility(View.GONE);
                                holder.layout.setVisibility(View.GONE);
                                holder.ranked.setVisibility(View.VISIBLE);
                            }
                        });

                final AlertDialog alert = dialog.create();
                alert.show();

        }
    });

}

@Override
public int getItemCount() {
    return critere.size();
}}

MainActivity类

public class RankActivity extends AppCompatActivity {
String jsonURL="xx/criteria.php";
RecyclerView rv;
private int mNotificationsCount = 0;
private Counter counter;
TextView notif;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rank);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    notif = (TextView) findViewById(R.id.badge_notification_1);

    new RankActivity.FetchCountTask().execute();

    counter = new Counter() {
        @Override
        public void setCounter(int count) {
            Log.e("Ser_Counter", "" + count);
            notif.setText(count + "");
            Toast.makeText(RankActivity.this, "Called", Toast.LENGTH_SHORT).show();
        }
    };

    rv = (RecyclerView) findViewById(R.id.rv);
    rv.setLayoutManager(new GridLayoutManager(RankActivity.this, 2));

    new Downloader_recycler(RankActivity.this,jsonURL, rv, counter).execute();
}

public void OnSave(MenuItem item){
    Toast.makeText(this, "Saved !", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_user, menu);
    MenuItem item = menu.findItem(R.id.action_notifications);
    MenuItemCompat.setActionView(item, R.layout.notification_update);
    //notificationCount = (RelativeLayout) MenuItemCompat.getActionView(item);
    //LayerDrawable icon = (LayerDrawable) item.getIcon();
    //Utils.setBadgeCount(this, icon, mNotificationsCount);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_notifications) {
        // TODO: display unread notifications.
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void updateNotificationsBadge(int count) {
    mNotificationsCount = count;
    invalidateOptionsMenu();
}

class FetchCountTask extends AsyncTask<Void, Void, Integer> {

    @Override
    protected Integer doInBackground(Void... params) {
        return 5;
    }

    @Override
    public void onPostExecute(Integer count) {
        updateNotificationsBadge(count);
    }
}}

2 个答案:

答案 0 :(得分:1)

按照以下步骤操作

1.像这样创建一个 interface

public interface Counter
{
    public void setCounter(int count);
}

2.然后在您的活动中添加此代码

private Counter counter;
counter = new Counter() {
            @Override
            public void setCounter(int count) {
                Log.e("Ser_Counter", "" + count);
                tvCountFav.setText(count + "");
                Toast.makeText(SearchResultClass.this, "Called", Toast.LENGTH_SHORT).show();
            }
        };

3.将此 interface 作为您的适配器类的参数

YourAdapteradapter = new YourAdapter(SearchResultClass.this, ArrayList, counter);

4.在适配器类构造函数中添加 counter 代码

 private Counter counter;
 public SearchResultAdapter(Context context, ArrayList<FilterDataModel> filterDataModelArrayList, Counter counter) {
        this.context = context;
        this.filterDataModelArrayList = filterDataModelArrayList;
        this.counter = counter;
    }

5.单击点击监听器中的5.fire counter inteface方法

holder.addLikeImagevView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                counter.setCounter(1);
            }
        });

答案 1 :(得分:-1)

这是我修复此(没有界面)

的方法

在主要活动中,我改变了实施徽章的方式,并添加了两种方法:

 public void update() {
    if (count>=5)
    {count = count +1;}
    display(count);
}

private void display(int count) {
    notif = (TextView) findViewById(R.id.badge_notification_1);
    notif.setText(""+ count);
}

这是新的主要活动类:

public class RankActivity extends AppCompatActivity {
String jsonURL="http://xx/load_criteria.php";
RecyclerView rv;
TextView notif;
int count = 5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rank);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    rv = (RecyclerView) findViewById(R.id.rv);
    rv.setLayoutManager(new GridLayoutManager(RankActivity.this, 2));

    new Downloader_recycler(RankActivity.this,jsonURL, rv).execute();
}

public void OnSave(MenuItem item){
    Toast.makeText(this, "Saved !", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_user, menu);
    MenuItem item = menu.findItem(R.id.action_notifications);
    MenuItemCompat.setActionView(item, R.layout.notification_update);
    //notificationCount = (RelativeLayout) MenuItemCompat.getActionView(item);
    //LayerDrawable icon = (LayerDrawable) item.getIcon();
    //Utils.setBadgeCount(this, icon, mNotificationsCount);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_notifications) {
        // TODO: display unread notifications.
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void update() {
    if (count>=5)
    {count = count +1;}
    display(count);
}

private void display(int count) {
    notif = (TextView) findViewById(R.id.badge_notification_1);
    notif.setText(""+ count);
}}

在Adapter类中,我在Onclick方法中添加了这些行:

if(c instanceof RankActivity){
  ((RankActivity)c).update();
                    }

我从其他帖子中了解到,在这里投放一个类是为了避免,因为它可能导致运行时异常,但它对我有用。

这是新的适配器类:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {

Context c;
ArrayList<criteria> critere;

public RecyclerAdapter(Context c, ArrayList<criteria> critere) {
    this.c = c;
    this.critere = critere;

}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView criteria, plus, update;
    ImageButton btn1, btn2, btn3, btn4;
    Boolean click1, click2, click3, click4;
    ImageView image, crown;
    RelativeLayout layout;
    LinearLayout ranked;
    ImageView check;
    private ItemClickListener itemClickListener;
    public ClipData.Item currentItem;
    public View view;

    public MyViewHolder(View itemView) {
        super(itemView);
        view = itemView;

        btn1 = itemView.findViewById(R.id.btn1);
        btn2 = itemView.findViewById(R.id.btn2);
        btn3 = itemView.findViewById(R.id.btn3);
        btn4 = itemView.findViewById(R.id.btn4);

        layout = itemView.findViewById(R.id.check_view);
        ranked = itemView.findViewById(R.id.rank_layout);
        check = itemView.findViewById(R.id.check_image);

        criteria = itemView.findViewById(R.id.criteria_text);
        image = itemView.findViewById(R.id.criteria_pic);

        crown = itemView.findViewById(R.id.crown_rank);
        plus = itemView.findViewById(R.id.plus);

    }

}

@Override
public RecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(c).inflate(R.layout.recycler_model,parent,false);

    return new MyViewHolder(v);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

    final criteria crit = critere.get(position);

    final String name = crit.getName();
    holder.criteria.setText(name);
    holder.layout.setVisibility(View.GONE);
    holder.crown.setVisibility(View.GONE);
    holder.plus.setVisibility(View.GONE);

    PicassoClient.downloadImage(c,crit.getImageurl(),holder.image);

    holder.btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

                LayoutInflater li = LayoutInflater.from(c);
                View dialogView = li.inflate(R.layout.custom_dialog_rank, null);

                AlertDialog.Builder dialog = new AlertDialog.Builder(c);

                dialog.setView(dialogView);
                dialog.setIcon(R.drawable.btn_press_rank1);
                dialog.setCancelable(false);
                dialog.setTitle(R.string.crit1);
                dialog.setMessage("The " + name + " was very unsatisfiying");
                final EditText userInput = (EditText) dialogView
                        .findViewById(R.id.comment_field);

                dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        //checked.setVisibility(View.VISIBLE);
                        holder.layout.setVisibility(View.VISIBLE);
                        holder.check.setVisibility(View.VISIBLE);
                        holder.check.bringToFront();
                        holder.ranked.setVisibility(View.INVISIBLE);
                        holder.crown.setVisibility(View.VISIBLE);
                        holder.plus.setVisibility(View.VISIBLE);
                        if(c instanceof RankActivity){
                            ((RankActivity)c).update();
                        }
                    }
                })
                        .setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //checked.setVisibility(View.GONE);
                                holder.layout.setVisibility(View.GONE);
                                holder.ranked.setVisibility(View.VISIBLE);
                                holder.crown.setVisibility(View.GONE);
                                holder.plus.setVisibility(View.GONE);
                            }
                        });

                final AlertDialog alert = dialog.create();
                alert.show();

        }
    });

}

@Override
public int getItemCount() {
    return critere.size();
}}

对于徽章:

Menu_user布局 在菜单文件夹中:

<menu 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"
tools:context="com.journaldev.collapsingtoolbarlayout.ScrollingActivity">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="Rank"
    android:onClick="OnSave"
    app:showAsAction="always" />
    <!--android:icon="@drawable/ic_ok"-->

<item
    android:id="@+id/action_notifications"
    android:orderInCategory="200"
    android:icon="@drawable/main_menu_notification"
    android:title="Notifications"
    app:showAsAction="always" />
</menu>

Notification_update布局 在布局文件夹中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@android:style/Widget.ActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:gravity="center"
android:orientation="vertical"
>

<RelativeLayout
    android:id="@+id/badge_layout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/relative_layout_item_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/button1"
            android:layout_width="30dip"
            android:layout_height="30dip"
            android:background="@drawable/crown1" />
    </RelativeLayout>

    <TextView
        android:id="@+id/badge_notification_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/relative_layout_item_count"
        android:background="@android:drawable/ic_notification_overlay"
        android:text="5"
        android:textColor="#FFF"
        android:textSize="12sp"
        android:textStyle="bold" />
</RelativeLayout>

希望它会帮助别人。