【问题标题】:how to add onClickListener to buttons inside CardLayout如何将 onClickListener 添加到 CardLayout 内的按钮
【发布时间】:2014-10-07 17:59:51
【问题描述】:

我正在使用 Gabrielemariotti 的 Cardslib 库在我的 android 应用程序中实现卡片布局。我正在为我的卡片使用自定义布局。下面是创建自定义卡片的代码:

Card card = new Card(getActivity().getApplicationContext(), R.layout.status_card);
card.setTitle("sample title");

我的卡片底部有三个按钮(如 Facebook 安卓应用中的按钮)。我想为这些按钮设置 onClickListener。但我不知道该怎么做。

请帮帮我。

谢谢,

【问题讨论】:

    标签: android android-layout cardlayout cardslib


    【解决方案1】:

    你必须定义你的布局。 然后使用此布局创建Card,并覆盖setupInnerViewElements 方法。 在此方法中,您可以在按钮上定义 OnClickListener,并且可以访问所有卡片的值。

     public class CustomCard extends Card {
    
            /**
             * Constructor with a custom inner layout
             *
             * @param context
             */
            public CustomCard(Context context) {
                super(context, R.layout.carddemo_mycard_inner_content);
            }
    
    
            @Override
            public void setupInnerViewElements(ViewGroup parent, View view) {
    
                //Retrieve button 
                Button myButton = (Button) view.findViewById(R.id.myButton);
                if (myButton != null) {
                    myButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(getContext(), "Click Listener card=" + getId(), 
                                  Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }
    

    【讨论】:

      【解决方案2】:

      我有一个简单的解决方案。

      因此,另一种添加 onClick 侦听器的方法更简单,就是通过 XML。

      在按钮的 xml 中,添加以下行:

      android:onClick="methodName"
      

      其中 'methodName' 显然是方法的名称。每当单击按钮时,这将调用该方法。下一步很明显 - 只需进入您的 java 活动并创建您想要调用的方法,确保将 View 作为参数。所以你的活动类中会有这样的东西:

      public void methodName(View view) {
          Log.v("appTag","BUTTON WAS PRESSED");
          //whatever you want to do here
      }
      

      这是创建整个 onClickListener 的快捷方式。

      希望对您有所帮助。祝你好运:)

      编辑:

      请记住,您在这里传递了一个视图,因此您可以从该视图中获取您想要的任何内容。既然您评论说您需要从卡片上删除文本,我将向您展示如何做到这一点。

      这是你的方法:

      public void methodName(View view) {
          Log.v("appTag","BUTTON WAS PRESSED");
          TextView textFromCard = view.findViewById(R.id.THE_ID_YOU_GAVE_YOUR_TEXTVIEW_IN_THE_XML);
          String textFromTextView = textFromCard.getText().toString();
          //do whatever you want with the string here
      }
      

      【讨论】:

      • 嗨,Alex,感谢您的快速回复。但如果我这样做,那将是一种通用方法。点击按钮,我需要对卡片内容进行字符串操作。 \n 所以我需要在点击按钮时访问卡片内容(这里是文本)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多