当前位置: 首页 > 知识库问答 >
问题:

创建回收站视图项目的选项菜单

谭鹏云
2023-03-14

我一直在尝试按照以下教程将选项菜单集成到我的listview中:

[https://www.simplifiedcoding.net/create-options-menu-recyclerview-item-tutorial/]

我已经能够让菜单的图标出现在列表视图中的项目旁边,但是我无法点击它来访问弹出菜单。我试图在我的BindViewHolder(MyViewHolder持有者,int位置)方法中实现这一点。

我不明白为什么我不能执行onClick。我已经发布了适配器的代码

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

    private Context context;
    private List<League> leaguesList;
    public TextView buttonViewOption;

    public void notifyDatasetChanged(List<League> newleagueslist) {
        leaguesList.clear();
        leaguesList.addAll(newleagueslist);
        super.notifyDataSetChanged();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView basescore;
        public TextView basescorepercentage;
        private TextView leagueAverage;
        public TextView id;
        public TextView timestamp;
        public TextView buttonViewOption;


        public MyViewHolder(View view) {
            super(view);
            id = view.findViewById( R.id.tvLeagueId);
            name = view.findViewById(R.id.tvSeriesName );
            basescore = view.findViewById(R.id.tvBaseScore );
            basescorepercentage = view.findViewById(R.id.tvBaseScorePercentage );
            leagueAverage = view.findViewById(R.id.tvLeagueAverage);
            timestamp = view.findViewById(R.id.timestamp);
            buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
        }
    }


    public LeagueAdapter(Context context, List<League> leaguesList) {
        this.context = context;
        this.leaguesList = leaguesList;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.listview_league, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        League league = leaguesList.get(position);
        int id = league.getId();
        String leagueId = String.valueOf(id);
        holder.id.setText(leagueId);
        holder.name.setText(league.getName());
        holder.basescore.setText(league.getBaseScore());
        holder.basescorepercentage.setText(league.getBaseScorePercentage());
        if (league.getAverage() != "") {
            holder.leagueAverage.setText(String.format("League Avg: %s", league.getAverage()));
        } else {
            holder.leagueAverage.setText(String.format("League Avg: %s", "0"));
        }
        //Formatting And Displaying Timestamp
        holder.timestamp.setText(formatDate(league.getTimestamp()));

        holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //creating a popup menu
                PopupMenu popup = new PopupMenu(context, holder.buttonViewOption);
                //inflating menu from xml resource
                popup.inflate(R.menu.options_menu);
                //adding click listener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu1:
                                //handle menu1 click
                                break;
                            case R.id.menu2:
                                //handle menu2 click
                                break;
                            case R.id.menu3:
                                //handle menu3 click
                                break;
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();

            }
        });
    }

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

    //Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
    //Input  : 2018-05-23 9:59:01
    //Output : Wed May 23 2018 (9:59:01)
    private String formatDate(String dateStr) {
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = fmt.parse(dateStr);
            SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
            return fmtOut.format(date);
        } catch (ParseException e) {

        }

        return "";
    }
}

这是我的listview xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:autofit="http://schemas.android.com/apk/res-auto"
    android:clickable="true"
    android:foreground="?attr/selectableItemBackground"
    android:paddingBottom="@dimen/dimen_10"
    android:paddingLeft="@dimen/activity_margin"
    android:paddingRight="@dimen/activity_margin"
    android:paddingTop="@dimen/dimen_10"
    android:focusable="true">

    <me.grantland.widget.AutofitTextView
        android:id="@+id/tvSeriesName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:singleLine="true"
        android:text="@string/leagueValue"
        android:textColor="?attr/colorAccent"
        android:textSize="24sp"
        android:textStyle="bold"
        autofit:minTextSize="16sp" />

    <TextView
        android:id="@+id/tvLeagueAverage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tvSeriesName"
        android:layout_marginStart="0dp"
        android:text="League Average: 300"
        android:textColor="#000000"
        android:textSize="12sp" />


    <TextView
        android:id="@+id/timestamp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvSeriesName"
        android:layout_centerHorizontal="true"
        android:text="Fri May 18 2018"
        android:textColor="?attr/colorText1"
        android:textSize="10sp"
        android:visibility="gone" />

    <TextView
        android:id="@+id/tvLeagueId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/tvSeriesName"
        android:layout_below="@+id/timestamp"
        android:text="TextView"
        android:textColor="?attr/colorText1"
        android:visibility="gone" />

    <TextView
        android:id="@+id/tvBaseScore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="?attr/colorText1"
        android:visibility="gone" />
    <TextView
        android:id="@+id/tvBaseScorePercentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="?attr/colorText1"
        android:visibility="gone" />

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="66dp"
        android:background="?attr/colorAccent" />

    <TextView
        android:id="@+id/textViewOptions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:text="&#8942;"
        android:textAppearance="?android:textAppearanceLarge" />
    android:background="?android:attr/listDivider" />

</RelativeLayout>

任何帮助都将不胜感激

我做了一点调查,发现了一些与我正在经历的问题相似的东西:

创建回收站选项菜单

第二个答案看起来很接近我试图实现的内容,它是在onBindViewHolder()中完成的,但是当我将代码移动到onBindViewHolder时,结果与之前相同。点会出现,但它们不可单击。

我回到教程,注意到我错过了几行,我添加了。这些行在哪里处理mCtx。更新代码如下。

public LeagueAdapter(Context context, List<League> leaguesList) {
        this.mCtx=mCtx;
        this.context = context;
        this.leaguesList = leaguesList;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.listview_league, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        League league = leaguesList.get(position);
        int id = league.getId();
        String leagueId = String.valueOf(id);
        holder.id.setText(leagueId);
        holder.name.setText(league.getName());
        holder.basescore.setText(league.getBaseScore());
        holder.basescorepercentage.setText(league.getBaseScorePercentage());
        if (league.getAverage() != "") {
            holder.leagueAverage.setText(String.format("League Avg: %s", league.getAverage()));
        } else {
            holder.leagueAverage.setText(String.format("League Avg: %s", "0"));
        }
        //Formatting And Displaying Timestamp
        holder.timestamp.setText(formatDate(league.getTimestamp()));

        holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //creating a popup menu
                PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
                //inflating menu from xml resource
                popup.inflate(R.menu.options_menu);
                //adding click listener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu1:
                                //handle menu1 click
                                break;
                            case R.id.menu2:
                                //handle menu2 click
                                break;
                            case R.id.menu3:
                                //handle menu3 click
                                break;
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();

            }
        });
    }

我现在从Logcat得到以下错误

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
        at com.android.internal.view.menu.MenuBuilder.<init>(MenuBuilder.java:189)
        at android.widget.PopupMenu.<init>(PopupMenu.java:99)
        at android.widget.PopupMenu.<init>(PopupMenu.java:74)
        at android.widget.PopupMenu.<init>(PopupMenu.java:59)
        at ca.rvogl.tpbcui.views.LeagueAdapter$1.onClick(LeagueAdapter.java:92)

联盟适配器。java:92是下面的一行

//creating a popup menu
                PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);

我也张贴了我的主活动incase它是必需的

public class MainActivity extends AppCompatActivity {

    private LeagueAdapter mAdapter;
    private List<League> leaguesList = new ArrayList<>();
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private TextView noLeaguesView;

    private DatabaseHelper db;

    private TextView leagueAverage;
    private String savedLeagueAverage;

    private static final String PREFS_NAME = "prefs";
    private static final String PREF_BLUE_THEME = "blue_theme";
    private static final String PREF_GREEN_THEME = "green_theme";
    private static final String PREF_ORANGE_THEME = "purple_theme";
    private static final String PREF_RED_THEME = "red_theme";
    private static final String PREF_YELLOW_THEME = "yellow_theme";

    @Override
    protected void onResume() {
        super.onResume();
        db = new DatabaseHelper(this);
        mAdapter.notifyDatasetChanged(db.getAllLeagues());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //Use Chosen Theme
        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean useBlueTheme = preferences.getBoolean(PREF_BLUE_THEME, false);
        if (useBlueTheme) {
            setTheme(R.style.AppTheme_Blue_NoActionBar);
        }
        boolean useGreenTheme = preferences.getBoolean(PREF_GREEN_THEME, false);
        if (useGreenTheme) {
            setTheme(R.style.AppTheme_Green_NoActionBar);
        }
        boolean useOrangeTheme = preferences.getBoolean(PREF_ORANGE_THEME, false);
        if (useOrangeTheme) {
            setTheme(R.style.AppTheme_Orange_NoActionBar);
        }
        boolean useRedTheme = preferences.getBoolean(PREF_RED_THEME, false);
        if (useRedTheme) {
            setTheme(R.style.AppTheme_Red_NoActionBar);
        }
        boolean useYellowTheme = preferences.getBoolean(PREF_YELLOW_THEME, false);
        if (useYellowTheme) {
            setTheme(R.style.AppTheme_Yellow_NoActionBar);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        coordinatorLayout = findViewById(R.id.coordinator_layout);
        recyclerView = findViewById(R.id.recycler_view);
        noLeaguesView = findViewById(R.id.empty_leagues_view);

        db = new DatabaseHelper(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_league_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLeagueDialog(false, null, -1);
            }
        });

        mAdapter = new LeagueAdapter(this, leaguesList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        //recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
        recyclerView.setAdapter(mAdapter);

        toggleEmptyLeagues();


        //On Long Click On The RecyclerView Item An Alert Dialog Is Opened With The Option To Choose Edit/Delete
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {

                int leagueId = leaguesList.get(position).getId();
                Intent myIntent = new Intent(MainActivity.this, BowlerActivity.class);
                myIntent.putExtra("leagueId", leagueId);
                startActivity(myIntent);
                overridePendingTransition(0, 0);
            }

            @Override
            public void onLongClick(View view, int position) {
                showActionsDialog(position);
            }
        }));
    }

    //Inserting New League In The Database And Refreshing The List
    private void createLeague(String league, String baseScore, String baseScorePercentage) {

        String leagueAverage = "0";

        //Inserting League In Database And Getting Newly Inserted League Id
        long id = db.insertLeague(league, baseScore, baseScorePercentage, leagueAverage);

        //Get The Newly Inserted League From The Database
        League n = db.getLeague(id);

        if (n != null) {
            //Adding New League To The Array List At Position 0
            leaguesList.add(0, n);

            //Refreshing The List
            mAdapter.notifyDataSetChanged();

            toggleEmptyLeagues();
        }
    }

    //Updating League In The Database And Updating The Item In The List By Its Position
    private void updateLeague(String name, String baseScore, String baseScorePercentage, int position) {
        League n = leaguesList.get(position);

        //Updating League Text
        n.setName(name);
        n.setBaseScore(baseScore);
        n.setBaseScorePercentage(baseScorePercentage);

        //Updating The League In The Database
        db.updateLeague(n);

        //Refreshing The List
        leaguesList.set(position, n);
        mAdapter.notifyItemChanged(position);

        toggleEmptyLeagues();
    }

    //Deleting League From SQLite Database And Removing The League Item From The List By Its Position
    private void deleteLeague(int position) {

        //Deleting The League From The Database
        db.deleteLeague(leaguesList.get(position));

        //Removing League From The List
        leaguesList.remove(position);
        mAdapter.notifyItemRemoved(position);

        toggleEmptyLeagues();
    }


    private void showActionsDialog(final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = View.inflate(this, R.layout.dialog_options_1, null);

        final AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.AppTheme));
        alertDialogBuilderUserInput.setView(view);
        alertDialogBuilderUserInput.setCancelable(true);

        final AlertDialog alertDialog = alertDialogBuilderUserInput.create();

        //Cancel
        final ImageButton cancel_btn = (ImageButton) view.findViewById(R.id.cancel);
        cancel_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
            alertDialog.cancel();
            }
        });

        //Edit
        ImageButton edit_btn = (ImageButton) view.findViewById(R.id.edit);
        edit_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showLeagueDialog(true, leaguesList.get(position), position);
                alertDialog.dismiss();
            }
        });

        ImageButton delete_btn = (ImageButton) view.findViewById(R.id.delete);
        delete_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "League will be deleted.", Snackbar.LENGTH_LONG)
                        .setAction("OK", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                deleteLeague(position);
                            }
                        });

                snackbar.show();
                alertDialog.dismiss();
            }
        });

        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.TOP);
        alertDialog.show();
    }



        //Show Alert Dialog With EditText Options to Enter/Edit A League
    //When shouldUpdate = true, It Will Automatically Display Old League Name And Change The Button Text To UPDATE
    private void showLeagueDialog(final boolean shouldUpdate, final League league, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = View.inflate(this, R.layout.dialog_league, null);

        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.AppTheme));
        alertDialogBuilderUserInput.setView(view);

        final EditText inputLeague = view.findViewById(R.id.etLeagueNameInput);
        final EditText inputBaseScore = view.findViewById(R.id.etBaseScore);
        final EditText inputBaseScorePercentage = view.findViewById(R.id.etBaseScorePercentage);
        TextView dialogTitle = view.findViewById(R.id.dialog_title);
        dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_league_title) : getString(R.string.lbl_edit_league_title));

        if (shouldUpdate && league != null) {
            inputLeague.setText(league.getName());
            inputBaseScore.setText(league.getBaseScore());
            inputBaseScorePercentage.setText(league.getBaseScorePercentage());
        }
        alertDialogBuilderUserInput.setCancelable(true).setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogBox, int id) {

            }
        }).setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogBox, int id) {
                dialogBox.cancel();
            }
        });

        final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
        alertDialog.show();

        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Show Toast Message When No Text Is Entered
                if (TextUtils.isEmpty(inputLeague.getText().toString())) {
                    Toast.makeText(MainActivity.this, "Enter League!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    alertDialog.dismiss();
                }

                //Check If User Is Updating League
                if (shouldUpdate && league != null) {
                    // update note by it's id
                    updateLeague(inputLeague.getText().toString(), inputBaseScore.getText().toString(), inputBaseScorePercentage.getText().toString(), position);
                } else {
                    // create new note
                    createLeague(inputLeague.getText().toString(), inputBaseScore.getText().toString(), inputBaseScorePercentage.getText().toString());

                }
            }
        });
    }

    //Toggling List And Empty League View
    private void toggleEmptyLeagues() {
        // you can check notesList.size() > 0

        if (db.getLeaguesCount() > 0) {
            noLeaguesView.setVisibility(View.GONE);
        } else {
            noLeaguesView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            overridePendingTransition(0, 0);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

我想我已经找到了问题的根源,当我清除main活动中onClick()中的一段代码时,listview中的每一行都会出现选项菜单。我注释掉的代码如下:

//On Long Click On The RecyclerView Item An Alert Dialog Is Opened With The Option To Choose Edit/Delete
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {

               /* int leagueId = leaguesList.get(position).getId();
                Intent myIntent = new Intent(MainActivity.this, BowlerActivity.class);
                myIntent.putExtra("leagueId", leagueId);
                startActivity(myIntent);
                overridePendingTransition(0, 0);*/

            }


            @Override
            public void onLongClick(View view, int position) {
                showActionsDialog(position);
            }
        }));
    }

如何为该部分添加onClickListener?本节处理的是整行,单击它会将用户带到一个新活动。

共有2个答案

戚飞
2023-03-14

试试这个:

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

    private Context context;
    private List<League> leaguesList;
    public TextView buttonViewOption;

    public void notifyDatasetChanged(List<League> newleagueslist) {
        leaguesList.clear();
        leaguesList.addAll(newleagueslist);
        super.notifyDataSetChanged();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView basescore;
        public TextView basescorepercentage;
        private TextView leagueAverage;
        public TextView id;
        public TextView timestamp;
        public TextView buttonViewOption;


        public MyViewHolder(View view) {
            super(view);
            id = view.findViewById( R.id.tvLeagueId);
            name = view.findViewById(R.id.tvSeriesName );
            basescore = view.findViewById(R.id.tvBaseScore );
            basescorepercentage = view.findViewById(R.id.tvBaseScorePercentage );
            leagueAverage = view.findViewById(R.id.tvLeagueAverage);
            timestamp = view.findViewById(R.id.timestamp);
            buttonViewOption = (TextView) view.findViewById(R.id.textViewOptions);
           
           buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //creating a popup menu
                PopupMenu popup = new PopupMenu(context, holder.buttonViewOption);
                //inflating menu from xml resource
                popup.inflate(R.menu.options_menu);
                //adding click listener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu1:
                                //handle menu1 click
                                break;
                            case R.id.menu2:
                                //handle menu2 click
                                break;
                            case R.id.menu3:
                                //handle menu3 click
                                break;
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();

            }
        });
        }
    }


    public LeagueAdapter(Context context, List<League> leaguesList) {
        this.context = context;
        this.leaguesList = leaguesList;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.listview_league, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        League league = leaguesList.get(position);
        int id = league.getId();
        String leagueId = String.valueOf(id);
        holder.id.setText(leagueId);
        holder.name.setText(league.getName());
        holder.basescore.setText(league.getBaseScore());
        holder.basescorepercentage.setText(league.getBaseScorePercentage());
        if (league.getAverage() != "") {
            holder.leagueAverage.setText(String.format("League Avg: %s", league.getAverage()));
        } else {
            holder.leagueAverage.setText(String.format("League Avg: %s", "0"));
        }
        //Formatting And Displaying Timestamp
        holder.timestamp.setText(formatDate(league.getTimestamp()));

      
    }

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

    //Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
    //Input  : 2018-05-23 9:59:01
    //Output : Wed May 23 2018 (9:59:01)
    private String formatDate(String dateStr) {
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = fmt.parse(dateStr);
            SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
            return fmtOut.format(date);
        } catch (ParseException e) {

        }

        return "";
    }
}
阎建中
2023-03-14

您在public LeagueAdapter(上下文,列表)上初始化了错误的上下文

 类似资料:
  • 我有一个显示位图的水平循环视图。它的实现方式是在它下面有一个Imageview和一个recyclerview。当前选定的项目将显示在图像视图上。为选定的图像视图提供蓝色背景,以指示其已选定。我可以从“多媒体资料”中选择图像,每次选择新图像时,我都希望滚动到最后一个位置并选中该项目。 图像列表保存在数组列表中,每次添加新图像时,我都会将图像添加到列表并notifyDataChanged()。 当前,

  • 如何创建一个选项菜单,如以下屏幕截图: 点击RecyclerView项目的“更多”图标后,应打开选项菜单! 我的尝试是这样的: 但这会导致问题,因为如果我点击RecyclerView item More按钮,则会单击完整项目。。。 这是我的RecyclerViewOnTouchListener: 我没有发现任何类似的问题,所以我希望你能帮助我!

  • 我有一个从内部存储器加载图像的回收器视图。我想在单击时突出显示所选项。我试了很多方法,但都不起作用。实际上,我需要的是,当我在Recycler视图中单击任何项目时,该项目必须进入我的ArrayList,它也应该突出显示,当我单击或说unselect时,它必须再次变为正常。以下是我的代码: 这是我的适配器类:

  • 在SiteMonitor V5中,系统利用JavaScript监测脚本从网站收集数据,每个站点均有一个默认视图,默认视图是该站点所有数据的汇总处理结果。客户可以通过配置过滤器,生成其他的视图从而观测同一个站点数据的某一部分数据的处理结果。 2.2.1 概念介绍 一个项目下可包含多个站点,一个站点下可包含多个视图(默认为一个默认视图)。 项目 通常设定为一个客户或一个品牌,每个项目可包含多个站点。如

  • 我正面临一个奇怪的错误,其中recyclerview只显示了一个项目。下面是我的recyclerview适配器的代码: 我已经在其他应用程序中使用了这段代码,它的工作非常完美。我已经检查了聊天数据,这也是完美的。 这里是指向git repo布局文件的链接:布局文件

  • 然后,在每个@test方法中,我调用activitytestrule.launchactivity(Intent.action_main)),然后进行单击。我发现,只有第一次点击不起作用,但第二次和第三次点击起作用。那么,这种行为的原因又能是什么呢?