将动态字符串资源传递给“setText()”

时间:2015-06-22 10:24:24

标签: android

我正在尝试创建一个动态字符串并转换已传递给setText()函数的硬编码字符串。但它似乎不接受它。 这是我尝试过的:

原始代码:

 device.name.setText("Mac :" + data.macAddress); 

Strings.xml声明:

<string name="mac">Mac :</string>

新代码:

device.name.setText(R.string.mac + data.macAddress); 

代码段:

   public class DeviceAdapter extends RecyclerView.Adapter<Device> {
    private final LayoutInflater mInflater;

    private final Device.IDeviceItem mListener;
    private final TextView mEmpty;

    public Vector<DeviceData> mDeviceData;

    public DeviceAdapter(Context context, TextView emptyView, Device.IDeviceItem listener) {
        mEmpty = emptyView;
        mListener = listener;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public Device onCreateViewHolder(ViewGroup parent, int position) {
        return new Device(mInflater.inflate(R.layout.item_device, parent, false), mListener);
    }

    @Override
    public void onBindViewHolder(Device device, int position) {
        DeviceData data = mDeviceData.elementAt(position);

        device.position = position;
        device.deviceId = data.deviceId;

        device.name.setText("Mac :" + data.macAddress);   // check this
        if (data.temperature == null) {
            device.temperature.setText(R.string.temp_notset);
        }else device.temperature.setText("Temperature set to " + data.temperature + "\u00B0" +" celsius.");

        if (data.powerState) {
            device.btnPower.setImageResource(R.drawable.power_off);

            if (!data.startState) {
                device.status.setText(R.string.pon_running);
                device.btnStart.setImageResource(R.drawable.start_off);
            } else {
                device.status.setText(R.string.pon_stop);
                device.btnStart.setImageResource(R.drawable.start_on);
            }

        } else {
            device.btnPower.setImageResource(R.drawable.power_on);
            device.status.setText(R.string.poff);
        }
    }

    @Override
    public int getItemCount() {
        int sz = mDeviceData.size();
        if (sz == 0) {
            mEmpty.setVisibility(View.VISIBLE);
        } else {
            mEmpty.setVisibility(View.GONE);
        }
        return sz;
    }

    public boolean hasDevice(DeviceData deviceData) {
        for (DeviceData device : mDeviceData) {
            if (device.deviceId.equalsIgnoreCase(deviceData.deviceId) && device.boxid.equalsIgnoreCase(deviceData.boxid))
                return true;
        }
        return false;
    }
}

所以当我有硬编码字符串时:它显示正确的值,但是当动态更改时,它会转换为整数“213136187044”。我究竟做错了什么 ?由于声誉低于10,我无法发布截图。

2 个答案:

答案 0 :(得分:1)

试试这样:

创建一个全局变量,如:

private String name;

然后在“onCreateViewHolder”中写如下:

name= parent.getResources().getString(R.string.mac);

现在,在“onBindViewHolder”中这样写:

device.name.setText(name + data.macAddress);

答案 1 :(得分:0)

请使用此

device.name.setText(data.macAddress + ""); 

device.status.setText(R.string.poff + "");