如何从自定义视图中的按钮响应单击事件?

时间:2014-07-22 04:05:21

标签: android android-layout onclicklistener android-custom-view buttonclick

我尝试调整this tutorial以便与TextViewButton一起使用。我已创建了ArrayListListView

   private void displayListView() {

    //putting two Country objects into the ArrayList
    //these countries have email addresses for some reason, just go with it
    ArrayList<Country> countryList = new ArrayList<Country>();
    country = new Country("email@email.com","DummyName1",false);
    countryList.add(country);
    country = new Country("email@email.com","DummyName2",false);
    countryList.add(country);

    //create an ArrayAdaptar from the String Array
    dataAdapter = new MyCustomAdapter(this,
            R.layout.pending_invite, countryList);

    ListView listView = (ListView) findViewById(R.id.listViewPendingRequests);
    // Assign adapter to ListView
    listView.setAdapter(dataAdapter);

}

这是我的主要XML:

 <?xml version="1.0" encoding="utf-8"?>

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:orientation="vertical" android:layout_width="match_parent"
     android:layout_height="match_parent">  

         <ListView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:id="@+id/listViewPendingRequests" />

  </LinearLayout>

这是我的pending_invite.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Pending Invitation 1"
            android:id="@+id/textView7"
            android:layout_weight="1" />

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Cancel"
            android:id="@+id/button5"
            android:layout_weight="1"
            android:onClick="onClickCancel"/>
    </LinearLayout>
</LinearLayout>

我认为,由于我不再需要复选框和内容,因此无法制作MyCustomAdapter。无论如何,这是我到目前为止所得到的:

 private class MyCustomAdapter extends ArrayAdapter<Country> {

    private ArrayList<Country> countryList;

    public MyCustomAdapter(Context context, int textViewResourceId,
                           ArrayList<Country> countryList) {
        super(context, textViewResourceId, countryList);
        this.countryList = new ArrayList<Country>();
        this.countryList.addAll(countryList);
    }

    private class ViewHolder {
        TextView code;
        Button name;
    }

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

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.pending_invite, null);

            holder = new ViewHolder();
            holder.code = (TextView) convertView.findViewById(R.id.textView7);
            holder.name = (Button) convertView.findViewById(R.id.button5);
            convertView.setTag(holder);

        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        Country country = countryList.get(position);
        holder.name.setText(country.getName());
        holder.name.setTag(country);

        return convertView;

    }

}

这样(令人惊讶地)构建视图,但是如何判断onClick中哪个被按下了?:

 public void onClickCancel(View view){
    Log.i(LOG_TAG, "OnClickCancel view: " + view.getId()); //getId returns the same thing for all clicks. How do I get which button clicked?

}

view.getId为所有按钮返回相同的ID。如何将onClick侦听器附加到自定义视图中的膨胀按钮?

4 个答案:

答案 0 :(得分:1)

你可以做这样的事情

private class MyCustomAdapter extends ArrayAdapter<Country> {

    private ArrayList<Country> countryList;

    public MyCustomAdapter(Context context, int textViewResourceId,
                           ArrayList<Country> countryList) {
        super(context, textViewResourceId, countryList);
        this.countryList = new ArrayList<Country>();
        this.countryList.addAll(countryList);
    }

    private class ViewHolder {
        TextView code;
        Button name;
    }

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

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.pending_invite, null);

            holder = new ViewHolder();
            holder.code = (TextView) convertView.findViewById(R.id.textView7);
            holder.name = (Button) convertView.findViewById(R.id.button5);
            convertView.setTag(holder);

        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        Country country = countryList.get(position);
       // holder.code.setText(" (" +  country.getCode() + ")");
        holder.name.setText(country.getName());
        //holder.name.setChecked(country.isSelected());
        holder.name.setTag(countryList.get(position).getName());     // here you are setting the tag, it will be retrieved in handleClick method
        // here create your on click handler, like

       holder.name.setOnClickListener(handleClick(holder.name));


        return convertView;

    }

}

此处定义您的handleClick方法

private OnClickListener handleClick(final Button butn) {
        // TODO Auto-generated method stub
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String TAG = butn.getTag().toString();  // get the tag, now you can compare which button has been clicked with respect to its tag name 

             if (TAG.equals("somehting")
             {
                  // your logic here
             }
            }
        };
    }

我希望你从这个答案中得到一些想法。

答案 1 :(得分:0)

在国家/地区中创建归档的“ID”。然后在创建Country实例时为每个对象分配一个值。然后在类国家/地区内为按钮添加onclick侦听器,并传递位置。然后使用以下函数获取单击

public void onClickCancel(int position){

Country country = countryList.get(position);

String countryId = country.ID;
Log.i(LOG_TAG, "OnClickCancel view: " + countryId ); 
}

答案 2 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

private class MyCustomAdapter extends ArrayAdapter<Country> {

    private ArrayList<Country> countryList;
    private Context context;

    public MyCustomAdapter(Context context, int textViewResourceId,
                           ArrayList<Country> countryList) {
        super(context, textViewResourceId, countryList);
        this.countryList =countryList;
        this.context = context;
    }

    private class ViewHolder {
        TextView code;
        Button name;
    }

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

        ViewHolder holder;
        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.pending_invite, null);
            holder = new ViewHolder();
            holder.code = (TextView) convertView.findViewById(R.id.textView7);
            holder.name = (Button) convertView.findViewById(R.id.button5);
            convertView.setTag(holder);

        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.name.setText(countryList.get(position).getName());
        holder.name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,countryList.get(position).getName(),Toast.LENGTH_SHORT).show();
            }
        });
        holder.name.setOnClickListener(handleClick(holder.name));

        return convertView;

    }

}

答案 3 :(得分:0)

如果您只想捕获onClick for按钮,则必须为按钮实现onClickListener:holder.name

holder.name.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });

如果要获取单击的项目,请为列表视图设置setOnItemClickListener。或者只是setOnClickListener用于你的customView convertView.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });