Android自定义LinearLayout的三种方法

方法一:在布局文件中添加自定义的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值