【发布时间】:2016-11-17 11:27:00
【问题描述】:
我创建了自己的类来模仿 Snackbar,我们称之为 CustomSnackbar。我想要实现的是自定义snackbar,并能够从我的主要活动中调用CustomSnackbar,并且其用法与调用标准Snackbar 非常相似。为了演示我的示例没有所有批量代码,这里是我的 CustomSnackbar 类:
package com.wizzkidd.myapp.helpers;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class CustomSnackbar {
Context _context;
Snackbar snackbar;
public CustomSnackbar(Context context) {
this._context = context;
}
public void make(View view, CharSequence text, int duration) {
snackbar = Snackbar.make(view, "", duration);
Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackbar.getView();
TextView textView = (TextView) snackbarLayout.findViewById(android.support.design.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE); //hide the default snackbar textview
//Create my own textview instead
TextView myTextView = new TextView(_context);
myTextView.setText(text);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); //Create layout params for some text
myTextView.setLayoutParams(params); //Apply the text layout params
snackbarLayout.addView(myTextView); //Add my text to the main snackbar layout. (Other widgets will also be added)
}
public void setAction(CharSequence text) {
snackbar.setAction(text, new View.OnClickListener() {
@Override
public void onClick(View view) {
//do something
Log.v("TAG", "You clicked the action");
}
});
}
public void show() {
snackbar.show();
}
}
在我的 MainActivity 中,我正在使用这样的类:
CustomSnackbar customSnackbar = new CustomSnackbar(activity);
customSnackbar.make(view, "This is my snackbar", Snackbar.LENGTH_INDEFINITE);
customSnackbar.setAction("HIDE");
customSnackbar.show();
您可以看到我正在使用我的 .setAction 方法来传递字符串/字符序列,但我不确定如何在同一个调用中处理 onClickListener 而不是在类中处理 onClickListener
请忽略该类可能看起来毫无意义的事实(但这是因为我出于本问题的目的对其进行了简化)。我不确定我是否正确地创建了这个类,所以任何额外的建议或建议将不胜感激。谢谢。
【问题讨论】:
标签: java android class onclicklistener android-snackbar