【问题标题】:How to use onclick button in baseAdapter如何在 baseAdapter 中使用 onclick 按钮
【发布时间】:2012-09-22 06:04:22
【问题描述】:

如何在扩展 baseadapter 中使用单击事件按钮。我尝试了很多但没有用。在我的项目中有自定义列表视图,它包含文本、按钮(btnlist)、快速滚动索引。当我点击按钮(btnlist)时,它不是其他活动,也没有显示错误,没有吐司..
请帮我举个例子。提前谢谢你。

快速参考: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" />

【问题讨论】:

  • 按下按钮时会被选中吗?
  • @carnel no boss onclick 事件不起作用..
  • 我知道点击事件不会被触发,但如果按钮根本没有被选中,请尝试在您的 xml 文件中将其设置为可聚焦。
  • @Carnal 按钮将被选中,但 onclick 不起作用..
  • 嗯,奇怪,你确定你没有在你的 xml 中为那个按钮设置 onClick = "someMethod()" 吗?

标签: android android-layout android-intent android-emulator onclick


【解决方案1】:

您应该使用您的适配器来填充列表中的项目。然后在您的 Activity 或 Fragment 中,您应该实现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

我认为这是一个非常好的示例(尽管在 this stackoverflow answer 中使用了扩展 ArrayAdapter 而不是 BaseAdapter

有一点要记住:

  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 并确保按钮为 @ 之后立即设置 call listview.setItemsCanFocus(true) XML 中的 987654338@。监听onClick 事件应该可以工作了。

这在 GoogleIO World of ListView 演示文稿的幻灯片 25 中进行了描述(您可以获取它herevideo is here

希望对你有帮助

【讨论】:

  • 当然..请更新...不要忘记..我会尝试添加此代码..感谢您的回复。
  • 顺便说一句,如果您为按钮设置了android:focusable="false"(就像您拥有的那样),那么触摸列表项应该会触发onListItemClick 事件。这应该没问题,除非您在列表行上有多个按钮。
  • 更新(更正事件) 请注意,onItemSelected 在 ListView 上(不在按钮上),它会在回调中包含点击的位置。然后使用getItemAtPosition 访问特定项目。
【解决方案2】:

为您的按钮尝试以下操作:

android:focusable="false"

【讨论】:

    【解决方案3】:

    if (rowView == null) 条件中写入holder.btnList.setOnClickListener,然后重试。

    【讨论】:

      【解决方案4】:

      在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
                  }
              });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 2019-01-11
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多