如果我想在onClick
方法中执行此方法,我将如何声明此方法:
public void addBook(Context context) {
是addBook(context);
吗?
我在实施它时遇到了麻烦。我认为这会导致我的活动被迫关闭,因为我输错了:
public class book_edit extends Activity {
public String book_name;
public String isbn;
public String author;
public float ratings;
public EditText title;
public EditText book_author;
public EditText isbn_number;
public EditText name;
public RatingBar ratingbar;
public Button save;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_book_list);
title = (EditText)findViewById(R.id.title);
book_author = (EditText)findViewById(R.id.author);
isbn_number = (EditText)findViewById(R.id.isbn);
save = (Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
}
});
final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar1);
ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
ratingbar.setRating(rating);
}
});
}
public void addBook(Context context) {
String tag = "Excersising BookProvider";
Log.d(tag, "adding a book");
ContentValues cv = new ContentValues();
cv.put(BookProviderMetaData.BookTableMetaData.BOOK_NAME, book_name);
cv.put(BookProviderMetaData.BookTableMetaData.BOOK_ISBN, isbn);
cv.put(BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR, author);
ContentResolver cr = context.getContentResolver();
Uri uri = BookProviderMetaData.BookTableMetaData.CONTENT_URI;
Log.d(tag, "book insert uri: " +uri);
Uri insertedUri = cr.insert(uri, cv);
Log.d(tag, "inserted uri:" + insertedUri);
}
}
答案 0 :(得分:1)
onClick方法与View参数
一起使用onClick(View view);
你总是可以调用view.getContext()来获取addBook的上下文实例
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addBook(view.getContext());
}
});
答案 1 :(得分:0)
您应该将book_edit.this
设置为方法的参数,这应该有用。