حدث Android onClick لطرق العرض
-
21-12-2019 - |
سؤال
لدي فكرة لوضعها android:onClick="myClickMethod"
للعديد من TextView.
<TextView
android:id="@+id/search_suggestion_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="myClickMethod"
android:clickable="true"/>
<TextView
android:id="@+id/search_suggestion_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="myClickMethod"
android:clickable="true"/>
<TextView
android:id="@+id/search_suggestion_3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="myClickMethod"
android:clickable="true"/>
كيف يمكنني أن أختلف عن اسم TextView myClickMethod()؟
المحلول
يمكنك القيام بذلك باستخدام معرفات كل عرض نصي.استخدم Switch-Case داخل myClickMethod الخاص بك بناءً على معرفات عرض النص.كما يمكنك التمييز بين طرق عرض النص حسب العلامات.
نصائح أخرى
يمكنك تعيين أ tag
لكل منهم.بهذه الطريقة، على سبيل المثال، لأول مرة View
يستخدم android:tag="1"
وما إلى ذلك وهلم جرا.
في الخاص بك onClick
الطريقة، ببساطة استخدم v.getTag()
وستتمكن من التمييز بينها.
يمكنك استخدام حالة التبديل البسيطة
public void myClickMethod(View v)
{
switch(v.getId()) /
// id is an int value. use getId to get the id of the view
{
case R.id.search_suggestion_1:
// search suggestion 1
break
case R.id.search_suggestion_2 :
// search suggestion 2
break;
case R.id.search_suggestion_3:
// search suggestion 3
break;
}
}
عندما تقوم بإنشاء وظيفة في النشاط مثل:
public void onClickMethod(View view){
//Input argument is the view on which click is fired.
//Get id of that view
int id = view.getId();
switch(id){
// your logic
}
}
public void myClickMethod(View v)
{
switch(v.getId())
{
case R.id.search_suggestion_1:
//code here
break;
case R.id.search_suggestion_2:
//code here
break;
case R.id.search_suggestion_3:
//code here
break;
default: break;
}
}
يمكنك استخدام switch-case
لاتخاذ القرار الذي Textview
يتم الضغط عليه من خلال المقارنة بينهما id
.
public void myClickMethod(View v) {
switch(v.getd()) {
case R.id.search_suggestion_1:
//code here
break;
case R.id.search_suggestion_2:
//code here
break;
case R.id.search_suggestion_3:
//code here
break;
}
}
لا تنتمي إلى StackOverflow