Ai đó có thể giúp tôi tạo giao diện người nghe do người dùng xác định với một số đoạn mã không?
Ai đó có thể giúp tôi tạo giao diện người nghe do người dùng xác định với một số đoạn mã không?
Câu trả lời:
Tạo một tệp mới:
MyListener.java:
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, String result);
}
Trong hoạt động của bạn, thực hiện giao diện:
MyActivity.java:
public class MyActivity extends Activity implements MyListener {
@override
public void onCreate(){
MyButton m = new MyButton(this);
}
// method is invoked when MyButton is clicked
@override
public void callback(View view, String result) {
// do your stuff here
}
}
Trong lớp tùy chỉnh của bạn, gọi giao diện khi cần:
MyButton.java:
public class MyButton {
MyListener ml;
// constructor
MyButton(MyListener ml) {
//Setting the listener
this.ml = ml;
}
public void MyLogicToIntimateOthers() {
//Invoke the interface
ml.callback(this, "success");
}
}
WeakReference<>trong trường hợp này, nhưng sau đó bạn không thể biến người nghe thành một lớp ẩn danh hoặc bất cứ điều gì mà người nghe không có tài liệu tham khảo nào khác ... vì vậy tốt nhất là không nên sử dụng nó
xin vui lòng đọc mẫu quan sát
giao diện người nghe
public interface OnEventListener {
void onEvent(EventResult er);
// or void onEvent(); as per your need
}
sau đó trong lớp của bạn nói Eventlớp
public class Event {
private OnEventListener mOnEventListener;
public void setOnEventListener(OnEventListener listener) {
mOnEventListener = listener;
}
public void doEvent() {
/*
* code code code
*/
// and in the end
if (mOnEventListener != null)
mOnEventListener.onEvent(eventResult); // event result object :)
}
}
trong lớp lái xe của bạn MyTestDriver
public class MyTestDriver {
public static void main(String[] args) {
Event e = new Event();
e.setOnEventListener(new OnEventListener() {
public void onEvent(EventResult er) {
// do your work.
}
});
e.doEvent();
}
}
Tôi đã tạo Trình nghe AsyncTask chung, kết quả nhận được từ lớp tách biệt AsycTask và cung cấp cho CallingActivity bằng Giao diện gọi lại.
new GenericAsyncTask(context,new AsyncTaskCompleteListener()
{
public void onTaskComplete(String response)
{
// do your work.
}
}).execute();
Giao diện
interface AsyncTaskCompleteListener<T> {
public void onTaskComplete(T result);
}
GenericAsyncTask
class GenericAsyncTask extends AsyncTask<String, Void, String>
{
private AsyncTaskCompleteListener<String> callback;
public A(Context context, AsyncTaskCompleteListener<String> cb) {
this.context = context;
this.callback = cb;
}
protected void onPostExecute(String result) {
finalResult = result;
callback.onTaskComplete(result);
}
}
Có một cái nhìn về điều này , câu hỏi này để biết thêm chi tiết.
Có 4 bước:
1. tạo lớp giao diện (người nghe)
Giao diện 2.use trong chế độ xem 1 (xác định biến)
Giao diện 3.implements để xem 2 (xem 1 được sử dụng trong chế độ xem 2)
Giao diện 4.pass trong chế độ xem 1 để xem 2
Thí dụ:
Bước 1: bạn cần tạo giao diện và chức năng definde
public interface onAddTextViewCustomListener {
void onAddText(String text);
}
Bước 2: sử dụng giao diện này trong chế độ xem
public class CTextView extends TextView {
onAddTextViewCustomListener onAddTextViewCustomListener; //listener custom
public CTextView(Context context, onAddTextViewCustomListener onAddTextViewCustomListener) {
super(context);
this.onAddTextViewCustomListener = onAddTextViewCustomListener;
init(context, null);
}
public CTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
public void init(Context context, @Nullable AttributeSet attrs) {
if (isInEditMode())
return;
//call listener
onAddTextViewCustomListener.onAddText("this TextView added");
}
}
Bước 3,4: thực hiện hoạt động
public class MainActivity extends AppCompatActivity implements onAddTextViewCustomListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get main view from layout
RelativeLayout mainView = (RelativeLayout)findViewById(R.id.mainView);
//create new CTextView and set listener
CTextView cTextView = new CTextView(getApplicationContext(), this);
//add cTextView to mainView
mainView.addView(cTextView);
}
@Override
public void onAddText(String text) {
Log.i("Message ", text);
}
}
Tạo giao diện người nghe.
public interface YourCustomListener
{
public void onCustomClick(View view);
// pass view as argument or whatever you want.
}
Và tạo phương thức setOnCustomClick trong một hoạt động khác (hoặc đoạn), nơi bạn muốn áp dụng trình nghe tùy chỉnh của mình ......
public void setCustomClickListener(YourCustomListener yourCustomListener)
{
this.yourCustomListener= yourCustomListener;
}
Gọi phương thức này từ hoạt động Đầu tiên của bạn và vượt qua giao diện người nghe ...
Trong năm 2018, không cần giao diện người nghe. Bạn đã có Android LiveData để đảm bảo chuyển kết quả mong muốn trở lại các thành phần UI.
Nếu tôi lấy câu trả lời của Rupesh và điều chỉnh nó để sử dụng LiveData, nó sẽ như vậy:
public class Event {
public LiveData<EventResult> doEvent() {
/*
* code code code
*/
// and in the end
LiveData<EventResult> result = new MutableLiveData<>();
result.setValue(eventResult);
return result;
}
}
và bây giờ trong lớp trình điều khiển của bạn MyTestDriver:
public class MyTestDriver {
public static void main(String[] args) {
Event e = new Event();
e.doEvent().observe(this, new Observer<EventResult>() {
@Override
public void onChanged(final EventResult er) {
// do your work.
}
});
}
}
Để biết thêm thông tin cùng với các mẫu mã, bạn có thể đọc bài viết của tôi về nó, cũng như các tài liệu chính thức:
Trong Android, bạn có thể tạo một giao diện như Listener và Activity của bạn thực hiện giao diện đó, nhưng tôi không nghĩ đó là một ý tưởng hay. nếu chúng ta có nhiều thành phần để lắng nghe những thay đổi về trạng thái của chúng, chúng ta có thể tạo BaseListener thực hiện Listener giao diện và sử dụng mã loại để xử lý chúng. chúng ta có thể liên kết phương thức khi tạo tệp XML, ví dụ:
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button4"
android:onClick="Btn4OnClick" />
và mã nguồn:
public void Btn4OnClick(View view) {
String strTmp = "点击Button04";
tv.setText(strTmp);
}
nhưng tôi không nghĩ rằng đó là một ý tưởng tốt ...
Tôi đã thực hiện một cái gì đó như dưới đây để gửi lớp mô hình của tôi từ Hoạt động thứ hai đến Hoạt động đầu tiên. Tôi đã sử dụng LiveData để đạt được điều này, với sự giúp đỡ của các câu trả lời từ Rupesh và TheCodeFather.
Hoạt động thứ hai
public static MutableLiveData<AudioListModel> getLiveSong() {
MutableLiveData<AudioListModel> result = new MutableLiveData<>();
result.setValue(liveSong);
return result;
}
"liveSong" là AudioListModel được khai báo trên toàn cầu
Gọi phương thức này trong Hoạt động đầu tiên
PlayerActivity.getLiveSong().observe(this, new Observer<AudioListModel>() {
@Override
public void onChanged(AudioListModel audioListModel) {
if (PlayerActivity.mediaPlayer != null && PlayerActivity.mediaPlayer.isPlaying()) {
Log.d("LiveSong--->Changes-->", audioListModel.getSongName());
}
}
});
Có thể điều này giúp cho những nhà thám hiểm mới như tôi.
Phương pháp đơn giản để làm phương pháp này. Đầu tiên thực hiệnOnClickListeners trong lớp Activity của bạn.
Mã số:
class MainActivity extends Activity implements OnClickListeners{
protected void OnCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.activity_main.xml);
Button b1=(Button)findViewById(R.id.sipsi);
Button b2=(Button)findViewById(R.id.pipsi);
b1.SetOnClickListener(this);
b2.SetOnClickListener(this);
}
public void OnClick(View V)
{
int i=v.getId();
switch(i)
{
case R.id.sipsi:
{
//you can do anything from this button
break;
}
case R.id.pipsi:
{
//you can do anything from this button
break;
}
}
}