如何在自定义视图中为两个视图设置两个不同的“ ID”?

时间:2018-07-09 05:54:33

标签: java android xml android-layout android-custom-view

我有一个自定义布局,其中包含两个TextView,如下所示,

public class DoubleTextView extends LinearLayout {
    LinearLayout layout;
    TextView upTextView;
    TextView downTextView;
    Context mContext;

    public DoubleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;


        String service = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li = (LayoutInflater) getContext().getSystemService(service);

        layout = (LinearLayout) li.inflate(R.layout.custom_double_text, this, true);

        upTextView = layout.findViewById(R.id.text_up);
        downTextView = layout.findViewById(R.id.text_down);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DoubleTextView);

        String upText = a.getString(R.styleable.DoubleTextView_upText);
        String downText = a.getString(R.styleable.DoubleTextView_downText);
        int upTextStyle = a.getResourceId(R.styleable.DoubleTextView_styleUpText, R.style.ListOtherLightInfo);
        int downTextStyle = a.getResourceId(R.styleable.DoubleTextView_styleDownText, R.style.ListOtherLightInfo);
        int upTextId = a.getResourceId(R.styleable.DoubleTextView_upTextId, new Random().nextInt());
        int downTextId = a.getResourceId(R.styleable.DoubleTextView_downTextId, new Random().nextInt());

        upText = upText == null ? "" : upText;
        downText = downText == null ? "" : downText;

        upTextView.setText(upText);
        downTextView.setText(downText);
        upTextView.setId(upTextId);
        downTextView.setId(downTextId);

        Log.e("DoubleTextView", "upTextId" + String.valueOf(upTextId));
        Log.e("DoubleTextView", "downTextId" + String.valueOf(downTextId));

    }
}

这是在xml之类的内部使用的

<com.loconav.common.widget.DoubleTextView
    app:upText="1829 2864 9382"
    app:upTextId="@+id/name"
    app:downText="number"
    android:background="@color/white"
    android:layout_width="wrap_content"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_height="wrap_content"/>

如上所述,我已经在XML中使用了自定义布局,但是无法引用Java类中上述代码段中使用的R.id。它显示DoubleTextView中“ upText”字段的空白。请让我知道如何对由多种类型的视图构成的任何CustomView中使用的字段进行Id的有效引用,以及在使用它们时如何在XML中进行设置。

下面是使用的 attrs.xml

<declare-styleable name="DoubleTextView">
    <attr name="upText" format="string"/>
    <attr name="downText" format="string"/>
    <attr name="styleUpText" format="integer"/>
    <attr name="styleDownText" format="integer"/>
    <attr name="upTextId" format="string"/>
    <attr name="downTextId" format="string"/>
</declare-styleable>

0 个答案:

没有答案