7

如何在擴展baseadapter中點擊事件按鈕..我嘗試了很多但沒有用..在我的項目中有自定義listview,它包含文本,按鈕(btnlist),fastscroll索引。當我點擊按鈕(btnlist)它不是其他活動gng,沒有錯誤也顯示,不吐司..
Plz幫助我的例子。提前謝謝你。如何在baseAdapter中使用onclick按鈕

快速參考:getview ---> holder.btnList.setOnClickListener

EfficientAdapter.java

public class EfficientAdapter extends BaseAdapter implements SectionIndexer, OnClickListener { 
IndexableListView mListView; 
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
ArrayList<Patient> patientListArray; 

private Intent intent; 
private Patient patient; 
private LayoutInflater mInflater; 
private Context context; 
private int positions; 
ViewHolder holder; 


public EfficientAdapter(Context context) { 
    mInflater = LayoutInflater.from(context); 
    this.context = context; 

    String patientListJson = CountriesList.jsonData; 
    JSONObject jssson; 
    try { 
     jssson = new JSONObject(patientListJson); 
     patientListJson = jssson.getString("PostPatientDetailResult"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    Gson gson = new Gson(); 
    JsonParser parser = new JsonParser(); 
    JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray(); 
    patientListArray = new ArrayList<Patient>(); 
    for (JsonElement obj : Jarray) { 
     Patient patientList = gson.fromJson(obj, Patient.class); 
     patientListArray.add(patientList); 
    // Log.i("patientList", patientListJson); 

    } 
} 


public int getCount() { 

    return patientListArray.size(); 
} 

public Object getItem(int position) { 

    return position; 
} 

public long getItemId(int position) { 
    return position; 
} 

public View getView(final int position, View convertView, ViewGroup parent) { 

    this.positions = position;  
    View rowView = convertView; 

    if (rowView == null) {      
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     rowView = inflater.inflate(R.layout.homemplebrowview, parent, false); 

     holder = new ViewHolder(); 
     holder.text1 = (TextView) rowView.findViewById(R.id.name); 
     holder.text2 = (TextView) rowView.findViewById(R.id.mrn); 
     holder.text3 = (TextView) rowView.findViewById(R.id.date); 
     holder.text4 = (TextView) rowView.findViewById(R.id.age); 
     holder.text5 = (TextView) rowView.findViewById(R.id.gender); 
     holder.text6 = (TextView) rowView.findViewById(R.id.wardno); 
     holder.text7 = (TextView) rowView.findViewById(R.id.roomno); 
     holder.text8 = (TextView) rowView.findViewById(R.id.bedno); 
     holder.btnList = (Button) rowView.findViewById(R.id.listbutton); 
     /*Button editButton = (Button) rowView.findViewById(R.id.listbutton) ; 
     editButton.setTag(position); 
     editButton.setClickable(true); 
     editButton.setOnClickListener(EfficientAdapter.this); 
     rowView.setClickable(true);*/ 


     rowView.setTag(holder); 
    } else { 
     holder = (ViewHolder) rowView.getTag(); 
    } 

    holder.text1.setText(Util.formatN2H(patientListArray.get(position) 
      .getName())); 
    holder.text2.setText(patientListArray.get(position).getMrnNumber()); 
    holder.text3.setText(Util.formatN2H(patientListArray.get(position) 
      .getRoom())); 
    holder.text4.setText(Util.formatN2H(patientListArray.get(position) 
      .getAge())); 
    holder.text5.setText(Util.formatN2H(patientListArray.get(position) 
      .getGender())); 
    holder.text6.setText(Util.formatN2H(patientListArray.get(position) 
      .getWard())); 
    holder.text7.setText(Util.formatN2H(patientListArray.get(position) 
      .getRoom())); 
    holder.text8.setText(Util.formatN2H(patientListArray.get(position) 
      .getBed()));   
    holder.btnList.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();  
      Intent next = new Intent(context, SeviceDetails.class); 
      Log.i("patient", " next "+ position + " onclickposition " + patientListArray.get(position).getMrnNumber()); 
      patient = getPatientDetailsByMrn(patientListArray, position); 
      Log.i("DDDD ", patient.getMrnNumber());    
      next.putExtra("patient", patient); 
      next.putExtra("position", position); 
      System.out.println("patient"+ patient); 
      context.startActivity(next); 
     } 
    }); 
return rowView; 
}  

static class ViewHolder { 
    public Button btnList; 
    public TextView text8; 
    public TextView text7; 
    public TextView text6; 
    public TextView text5; 
    public TextView text4; 
    public TextView text1; 
    public TextView text2; 
    public TextView text3; 
} 

@Override 
public void notifyDataSetChanged() { 
    super.notifyDataSetChanged(); 
} 

public int getPositionForSection(int section) { 
    sortMyData(); 

    Log.i("getPositionForSection", "section" + section); 
    // If there is no item for current section, previous section will be 
    // selected 
    for (int i = section; i >= 0; i--) { 
     for (int j = 0; j < getCount(); j++) { 
      if (i == 0) { 

       Log.i("getPositionForSection- i", "section" + i); 
       // For numeric section 
       for (int k = 0; k <= 9; k++) { 

        if (StringMatcher.match(
          String.valueOf(patientListArray.get(j) 
            .getName().charAt(0)), 
          String.valueOf(k))) 
         Log.i("getPositionForSection- j", "section" + j); 

         return j; 
       } 
      } else { 
       if (StringMatcher.match(
         String.valueOf(patientListArray.get(j).getName() 
           .charAt(0)), 
         String.valueOf(mSections.charAt(i)))) 
        return j; 
      } 
     } 
    } 
    return 0; 
} 

public int getSectionForPosition(int position) { 
    return 0; 
} 

public Object[] getSections() { 
    String[] sections = new String[mSections.length()]; 
    for (int i = 0; i < mSections.length(); i++) 
     sections[i] = String.valueOf(mSections.charAt(i)); 
    return sections; 
} 

/** 
* sorting the patientListArray data 
*/ 
public void sortMyData() { 
    // sorting the patientListArray data 
    Collections.sort(patientListArray, new Comparator<Object>() { 
     @Override 
     public int compare(Object k1, Object k2) { 
      Patient p1 = (Patient) k1; 
      Patient p2 = (Patient) k2; 
      return p1.getName().compareToIgnoreCase(p2.getName()); 
     } 

    }); 
} 


    } 

的.xml

<Button 
     android:id="@+id/listbutton" 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:layout_alignTop="@+id/name" 
     android:layout_marginRight="43dp" 
     android:focusable="false"  
     android:text="Episode" 
     android:textColor="#666666" /> 

默認列表視圖

 <ListView 

     android:id="@+id/homelistView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:dividerHeight="0dip" /> 
+0

當你按下它時,你的按鈕是否被選中? – Carnal

+0

@carnel沒有老闆onclick事件沒有工作.. –

+0

我知道點擊事件沒有被解僱,但如果按鈕根本沒有被選中,請嘗試將其設置爲在您的xml文件中可調焦。 – Carnal

回答

6

您應該使用適配器來填充項目列表。然後在您的活動或片段中,您應該實施onListItemClick事件來處理列表項目上的點擊。

編輯:我張貼下面我用一個ListFragment其中一個例子 - 這是一段代碼,我有可用的,現在,我可以張貼一些具體的事情到ListView後:在

public class RecipiesActivity extends FragmentActivity { 

    private RecipiesSummaryListAdapter m_listAdapter; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     /* here you need to set the adapter of the listview 
      and do other things for your applicaiton (i.e. populate the 
      data in your adapter. In your case, since you are calling a 
      WS you want to do that in a different task */ 
     ListFragment lf = 
      (ListFragment) fm.findFragmentById(R.id.my_list_fragment); 
     lf.setListAdapter(m_listAdapter); 
} 

然後你ListFragment

/* imports and other things go here then... */ 
public class MyListFragment extends ListFragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 

     return (View) inflater.inflate(R.layout.myListViewXml, 
              container, false); 
    } 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
     // put your handler here 

    } 
} 

有關ListFragment詳見here

我認爲一個非常好的例子(儘管通過延長ArrayAdapter代替BaseAdapterthis stackoverflow answer是hown

有一點要記住:

  1. 按鈕不能成爲焦點(即XML使用android:focusable="false" - 就像您在XML中使用的一樣)
  2. 您需要捕獲提供的onItemClick事件,處理方式如下(摘自上面的鏈接):

代碼:

listview.setOnItemClickListener(new OnItemClickListener() { 
    //@Override 
    public void onItemClick(AdapterView arg0, View view, 
            int position, long id) { 
     // user clicked a list item, make it "selected" 
     selectedAdapter.setSelectedPosition(position); 
     //Do your stuff here 
} 

最後,需要注意的一點。此解決方案意味着您單擊列表行並且事件被觸發。

我認爲如果你想讓用戶點擊按鈕和事件來觸發按鈕,那麼你需要在膨脹ListView XML之後立即設置調用listview.setItemsCanFocus(true),並確保按鈕是focusable XML。然後收聽onClick事件。

這ListView中呈現的GoogleIO世界的滑動器25描述(你可以得到它herevideo is here

希望這有助於

+0

確定.. PLZ更新... DENT忘記..我會嘗試添加此代碼..謝謝爲你的答覆。 –

+1

btw,如果你爲該按鈕設置了'android:focusable =「false」'(像你那樣),那麼觸摸列表項應該觸發'onListItemClick'事件。這應該沒問題,除非列表中有多個按鈕。 – Lefteris

+0

**更新(更正了事件)**請注意'onItemSelected'在ListView上(不在按鈕上),它將在回調中包含點擊的位置。然後使用'getItemAtPosition'來訪問特定的項目。 – Lefteris

2

使用Ť他在getView()方法中使用以下代碼:方法:

Button status = (Button) rowView.findViewById(R.id.image1); 
     status.setBackgroundResource(R.drawable.add_account); 
     status.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
         // DO your stuff 
      } 
     }); 
+0

不需要holder.button –

3

嘗試爲您的按鈕如下:

android:focusable="false" 
2

if (rowView == null)的條件下寫holder.btnList.setOnClickListener,然後重試。

+0

試過這個東西..但是沒有用.. –