定制适配器带单选按钮

时间:2012-03-06 04:59:53

标签: android android-layout

我正在创建自己的自定义适配器。我必须在每个列表项的前面放置单选按钮。我用这个:

List<Address> result = myGeocoder.getFromLocationName(name,
                MAX_RESULT);


public class MyArrayAdapter extends ArrayAdapter<Address> {
    Context mycontext;

    public MyArrayAdapter(Context context, int textViewResourceId,
            List<Address> objects) {
        super(context, textViewResourceId, objects);            
        mycontext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int maxAddressLineIndex = getItem(position)
                .getMaxAddressLineIndex();
        String addressLine = "";
        for (int j = 0; j <= maxAddressLineIndex; j++) {
            addressLine += getItem(position).getAddressLine(j) + ",";
        }

        TextView rowAddress = new TextView(mycontext);
        rowAddress.setText(addressLine + "\n");

        return rowAddress;

    }

有人可以告诉我如何添加单选按钮。

2 个答案:

答案 0 :(得分:1)

试试这个

List<Address> result = myGeocoder.getFromLocationName(name,
            MAX_RESULT);

public class MyArrayAdapter extends ArrayAdapter {     上下文mycontext;

public MyArrayAdapter(Context context, int textViewResourceId,
        List<Address> objects) {
    super(context, textViewResourceId, objects);            
    mycontext = context;
}

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
    int maxAddressLineIndex = getItem(position)
            .getMaxAddressLineIndex();
    String addressLine = "";
    for (int j = 0; j <= maxAddressLineIndex; j++) {
        addressLine += getItem(position).getAddressLine(j) + ",";
    }
    LinearLayout lyt = new LinearLayout(mycontext);
    TextView rowAddress = new TextView(mycontext);
    rowAddress.setText(addressLine + "\n");
    RadioButton rdo = new RadioButton(mycontext);

    lyt.addView(rowAddress);
    lyt.addView(rdo);
    return lyt;

}

答案 1 :(得分:0)

首先,您要为列表项创建自定义布局,然后在getView()方法中使用LayoutInflater。

  

LayoutInflater将布局XML文件实例化为其对应的   查看对象。它永远不会直接使用。相反,使用   getLayoutInflater()或getSystemService(String)来检索标准   已连接到当前的LayoutInflater实例   上下文并为您正在运行的设备正确配置。

一个很好的例子是here,你可以在其中看到基本原理。这里有一个简单的片段:

…
private LayoutInflater mInflater;
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
…

@Override
        public View getView(int position, View convertView, ViewGroup parent) {
            System.out.println("getView " + position + " " + convertView);
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listItem, null);
                …
            } else {
                …
            }
            …
            return convertView;
        }

    }

参考:
developer.android