比如我寫了個具有圖文的Toast,我想把它封裝成類,以後要用這種toast的時候直接調用。代碼如下
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ImageView mView = new ImageView(MainActivity.this);
TextView mTextView = new TextView(MainActivity.this);
LinearLayout layout = new LinearLayout(MainActivity.this);
mTextView.setText("SS");
Linkify.addLinks(mTextView, Linkify.WEB_URLS
| Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES);
Toast toast=Toast.makeText(MainActivity.this, mTextView.getText(), Toast.LENGTH_LONG);
View textView=toast.getView();
layout.setOrientation(LinearLayout.HORIZONTAL);
mView.setImageResource(R.drawable.ic_launcher);
layout.addView(mView);
layout.addView(textView);
toast.setView(layout);
toast.show();
}
});
}
如何封裝成類???
public class MyToast {
public static void ToastShow(Context ct){
ImageView mView = new ImageView(ct);
TextView mTextView = new TextView(ct);
LinearLayout layout = new LinearLayout(ct);
mTextView.setText("SS");
Linkify.addLinks(mTextView, Linkify.WEB_URLS
| Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES);
Toast toast=Toast.makeText(ct, mTextView.getText(), Toast.LENGTH_LONG);
View textView=toast.getView();
layout.setOrientation(LinearLayout.HORIZONTAL);
mView.setImageResource(R.drawable.ic_launcher);
layout.addView(mView);
layout.addView(textView);
toast.setView(layout);
toast.show();
}
}
使用
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyToast.ToastShow(MainActivity.this);
}
}