我的自定義控件在界面上顯示不出來 這是為什么 老師
這是我自定義的一個控件由兩個按鈕 和一個editText組成 ?可是為什么我的控件不能顯示出來呢
這是我的Java代碼實現一些屬性的設置public class MyTopbar extends RelativeLayout{
? ?private String title,leftbutton,rightbutton;
? ?private Button leftBtn,rightBtn;
? ?private EditText ?editText;
? ?private LayoutParams paramRight,paramsLeft,paramsTitle;
? ?public MyTopbar(Context context, AttributeSet attrs) {
super(context, attrs);
? ? ? ?TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyTopbar);
? ? ? ?title = ta.getString(R.styleable.MyTopbar_title);
? ? ? ?leftbutton = ta.getString(R.styleable.MyTopbar_leftbutton);
? ? ? ?rightbutton = ta.getString(R.styleable.MyTopbar_rightbutton);
? ? ? ?ta.recycle();
? ? ? ?leftBtn = new Button(context);
? ? ? ?rightBtn = new Button(context);
? ? ? ?editText = new EditText(context);
? ? ? ?leftBtn.setText(leftbutton);
? ? ? ?rightBtn.setText(rightbutton);
? ? ? ?editText.setText(title);
? ? ? ?paramsLeft = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
? ? ? ? ? ? ? ?, ViewGroup.LayoutParams.WRAP_CONTENT);
? ? ? ?paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_LEFT,TRUE);
? ? ? ?addView(leftBtn, paramsLeft);
? ? ? ?paramRight = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
? ? ? ? ? ? ? ?, ViewGroup.LayoutParams.WRAP_CONTENT);
? ? ? ?paramRight.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,TRUE);
? ? ? ?addView(rightBtn, paramRight);
? ? ? ?paramsTitle = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
? ? ? ? ? ? ? ?, ViewGroup.LayoutParams.WRAP_CONTENT);
? ? ? ?paramsTitle.addRule(RelativeLayout.CENTER_IN_PARENT,TRUE);
? ? ? ?addView(editText,paramsTitle);
? ?}
}
接下來是我的xml 文件 自定義了屬性
<resources>
? ?<declare-styleable name="MyTopbar">
? ? ? ?<attr name="title" format="string" />
? ? ? ?<attr name="leftbutton" format="string" />
? ? ? ?<attr name="rightbutton" format="string" />
? ?</declare-styleable>
</resources>
然后是引用我自定義的控件
<com.example.administrator.topbar.MyTopbar
? ?android:layout_width="match_parent"
? ?android:layout_height="104dp"
? ?android:paddingLeft="20dp"
? ?android:paddingBottom="40dp"
? ?android:background="#b4ff66"
? ?app:rightbutton="按鈕右"
? ?app:leftbutton="按鈕左"
? ?app:title="這是我的第一個自定義控件"
? ?android:layout_gravity="center">
</com.example.administrator.topbar.MyTopbar>
2017-09-06
樓主 你的這個解決了嗎 ?我也遇到了跟你一樣的問題 解決了的話麻煩回復下 ?謝謝
2015-11-17
我找到原因了,在使用自定義控件的時候,在attrs中定義的每個屬性最好都要設置。我的事title沒有顯示出來,原因就是zyl:titleTextSize="12dp"這個屬性titleTextSize沒有設定,導致沒法顯示。
2015-11-17
我也是,leftbutton顯示出來了,title卻沒有顯示。