【问题标题】:Recycler View Item onClick回收商查看项目 onClick
【发布时间】:2016-06-04 22:50:18
【问题描述】:

我已经在 Google 上搜索了许多关于如何获取在回收站视图中单击的项目的可能性,但它们似乎都不起作用。下面的代码应该可以工作,但我不明白为什么不能。在 android studio 中,getPosition() 方法被划掉了。我的想法已经用完了,有没有办法至少可以为点击回收站视图的名称敬酒?

ViewHolder

public class ShoppingListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public CardView cv;
    public TextView name;
    public TextView description;
    Context context;

    public ShoppingListViewHolder(View itemView) {
        super(itemView);
        cv = (CardView) itemView.findViewById(R.id.cardView);
        name = (TextView) itemView.findViewById(R.id.title);
        description = (TextView) itemView.findViewById(R.id.description);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("RecyclerView", "onClick:" + getPosition());
            }
        });
    }


    public void bindView(int position) {

    }

    @Override
    public void onClick(View v) {
        Log.d("TAG", "onClick " + getPosition() + " " + name);
    }

适配器

public class MainShoppingListViewActivity extends AppCompatActivity {

    List<Data> list = new ArrayList<>();
    RecyclerView recyclerView;
    ShoppingListViewAdapter adapter;
    Context context;
    EditText listName;
    Firebase ref;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_shoppinglist_view);

        Firebase.setAndroidContext(this);
        ref = new Firebase("https://shoppinglistshare.firebaseio.com/");

        // Getting the recycler view, using the Recycler View
        recyclerView = (RecyclerView) findViewById(R.id.shopping_list_recycler_view);
        // The setLayoutManager which contains the main container where the Recycler View is contained
        recyclerView.setLayoutManager(new LinearLayoutManager(MainShoppingListViewActivity.this));

        // Floating action bar initiated, background color is set and then onClickListener to act when the
        // button is pressed to which the createDialogBox(); method is called
        FloatingActionButton addFloat = (FloatingActionButton) findViewById(R.id.fab);
        addFloat.setBackgroundTintList(ColorStateList.valueOf(Color
                .parseColor("#3F51B5")));
        addFloat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Click action
                createDialogBox();
            }
        });
    }

    /*
    * This method is used to add a new item to the Recycler View
    */
    public void addNewShoppingListItem(String val) {
        ref = new Firebase("https://shoppinglistshare.firebaseio.com/");

        adapter = new ShoppingListViewAdapter(list, MainShoppingListViewActivity.this);
        recyclerView.setAdapter(adapter);

        adapter.addItem(new Data(val, "Created by: Me"));
        ref.child("List Name: ").setValue(val);
    }

    /*
     * This method is used to add a new item to the Recycler View
    */
    public void removeShoppingListItem(String val) {
        adapter = new ShoppingListViewAdapter(list, MainShoppingListViewActivity.this);
        recyclerView.setAdapter(adapter);

        adapter.addItem(new Data(val, "Created by: Me"));
    }

    /*
     * This method is called inside the float action bar to create a dialog box when the floating action button is pressed.
    */
    public void createDialogBox() {

        // Alert Dialog Builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        // Using Layout Inflater class and assigned to a variable and using getLayout
        LayoutInflater inflater = this.getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout.
        // Using the view class to inflate the layout.
        View rootView = inflater.inflate(R.layout.custom_alert_dialog, null);
        listName = (EditText) rootView.findViewById(R.id.ShoppinglistName);

        // Using the AlertDialog Builder created above as "builder" to set the view.
        builder.setView(rootView)
                .setPositiveButton("Create", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String val = listName.getText().toString();
                        if (!val.isEmpty()) {
                            addNewShoppingListItem(val);
                        } else {
                            Toast.makeText(MainShoppingListViewActivity.this, "Please enter a value", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                // Show the dialog
                .show();
    }
}

日志

FATAL EXCEPTION: main
Process: familyshopshare.com.familyshopshare, PID: 17889
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.widget.Toast.<init>(Toast.java:102)
    at android.widget.Toast.makeText(Toast.java:259)
    at familyshopshare.com.familyshopshare.ShoppingListViewHolder$1.onClick(ShoppingListViewHolder.java:33)
    at android.view.View.performClick(View.java:5198)
    at android.view.View$PerformClick.run(View.java:21147)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

【问题讨论】:

  • 仅供参考:构造函数中有 2 个 onClick 可以工作并记录项目位置,但是当我在那里敬酒时,它会使应用程序崩溃。但是,我更希望在 onClick 方法中处理点击
  • getPosition 被划掉,因为它已被弃用(按 Ctrl+Q 就可以了,文档会告诉你)。您可能应该改用getAdapterPosition()。至于您的问题 - 显示您的 ViewHolder 实现是不够的,似乎问题出在其他地方,也许在适配器中。如何创建视图持有者?
  • 它可能会崩溃,因为您的 Context 为空,我看不出您将其分配到何处。你可以从itemView.getContext()
  • 上下文空在哪里?
  • 所以根据日志,我在 ViewHolder 的第 33 行得到了一个空对象引用,目前它是一个基本的 Toast Toast.makeText(context, "onClick is this:" + getAdapterPosition() , Toast.LENGTH_SHORT).show();

标签: java android onclicklistener android-recyclerview


【解决方案1】:

做了一些小的改动,这是我得到的解决方案。我打算将 onClick 更改为另一种方法,而不是它所在的位置。如果有任何关于如何使代码更好的建议,请告诉我,任何建议都非常感谢:)

public class ShoppingListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

public CardView cv;
public TextView name;
public TextView description;
Context context;

public ShoppingListViewHolder(View itemView) {
    super(itemView);
    cv = (CardView) itemView.findViewById(R.id.cardView);
    name = (TextView) itemView.findViewById(R.id.title);
    description = (TextView) itemView.findViewById(R.id.description);
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Data test = new Data(name.getText().toString(), description.getText().toString());
            Toast.makeText(v.getContext(), "onClick " +  test.getName(), Toast.LENGTH_SHORT).show();
            Log.d("RecyclerView", "onClick is this:" + getAdapterPosition());
        }
    });
}

@Override
public void onClick(View v) {
    Toast.makeText(context, "onClick " + getAdapterPosition() + " " + name, Toast.LENGTH_SHORT).show();
}

}

【讨论】:

    【解决方案2】:

    有几种方法可以做到这一点。就个人而言,我喜欢在适配器类的 onBindViewHolder 中设置监听器(无论你有你的viewholder):

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
    
       holder.YourTargetObject.setOnClickListener(new View.onClickListener(){
          public void onClick(View view){
           //do something
          }
       });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多