我创建了一个带有textview和3个按钮的复合控件。它的工作很好,当我添加到一个布局使用xml。但它需要在运行时使用java代码添加它。当我尝试使用java代码添加它时,其他控件是可见的,但我的复合控件不显示。
复合控件XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/border_lines"
>
<TextView android:id="@+id/msg_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SAMPLE MESSAGE TITLE"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button android:id="@+id/btn_shw"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="SHOW MSG"
android:layout_weight="1"
/>
<Button android:id="@+id/btn_dis"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text=" DISABLE"
android:layout_weight="1"
/>
<Button android:id="@+id/btn_del"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text=" DELETE "
android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
用于添加控件的JAVA代码
package deepak.android.remainder;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class RemainderList extends Activity
{
ScrollView sv1;
LinearLayout ll1;
deepak.android.remainder.RemainderControl rc1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sv1=new ScrollView(this);
ll1=new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
sv1.addView(ll1);
TextView tv1=new TextView(this);
tv1.setText("THIS IS SAMPLE TEXT");
ll1.addView(tv1);
**LinearLayout.LayoutParams lp;
lp=new LineararLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);**
for(int i=0;i<5;i++)
{
rc1=new deepak.android.remainder.RemainderControl(this);
**ll1.addView(rc1,lp);**
}
setContentView(sv1);
}
}
您可以通过查询ll1
(LinearLayout
)的特定(编号)子节点来实现。例如,
View child1 = ll1.getChildAt(0);
View child2 = ll1.getChildAt(1);
// and so on...
当然,在您可以强制转换和使用子元素之前,您需要做null检查和instanceof
检查。