方法一:在布局文件中添加自定义的LinearLayout
<com.tang.Javen.TJDigitalClock
android:id="@+id/digitalclock"
android:layout_width="wrap_content"
android:layout_height="100dp">
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:singleLine="true"
android:ellipsize="none"
android:gravity="center"
android:textSize="76sp"
android:text="12:00"/>
<TextView
android:id="@+id/ampm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:text="PM"/>
</com.tang.Javen.TJDigitalClock>
然后在自定义文件中的onFinishInflate()通过findViewById找到自定义布局中的控件
public class TJDigitalClock extends LinearLayout
{
private TextView time, date, ampm = null;
private int timeCount = 0;
private String timefomat;
private Calendar mCalendar;
private static final int CLOCK_TIME_CHANEGE = 999;
private Context mContext = null;
private LayoutInflater layoutInflater = null;
public TJDigitalClock(Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
protected void onFinishInflate()
{
// TODO Auto-generated method stub
super.onFinishInflate();
Log.d("Javen","onFinishInflate");
time = (TextView)findViewById(R.id.time);
ampm = (TextView)findViewById(R.id.ampm);
date = (TextView)findViewById(R.id.date);
}
onFinishInflate() 是当View中所有的子控件均被映射成xml后触发。
方法二:不把自定义的LinearLayout通过xml文件来布局,在布局中只放置一个LinearLayout的位置
<LinearLayout
android:id="@+id/facLayout"
android:gravity="center"
android:background="#8602151a"
android:layout_width="770.0dp"
android:layout_height="320.0dp"
android:layout_marginTop="30dp"/>
然后通过
facLayout = (LinearLayout) findViewById(R.id.facLayout);
来找到这个放置自定义控件的位置,最后addView加载我们需要放置的自定义控件
facLayout.addView(propertyView.getPropertyView());
propertyView.getPropertyView() = LayoutInflater.from(mContext).inflate(R.layout.propertyview, this);
这里的R.layout.propertyview就是我们自定义LinearLayout的布局了
方法三:则是完全使用代码来实现,而不使用xml