我有活动,并且在该活动中我想将按钮添加到我的布局中。这是代码:
public class SecondActivity extends Activity{
ClassTabs tabs;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
tabs = new ClassTabs(getApplicationContext());
Button button = new Button(getApplicationContext());
tabs.addTab(button);
Button next = (Button) findViewById(R.id.nextActivity);
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(intent);
}
});
}
}
xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.actionbartest.ClassTabs
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
<Button
android:id="@+id/nextActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_marginTop="100dp"
/>
</LinearLayout>
类标签:
public class ClassTabs extends LinearLayout{
Button button = new Button(getContext());
public ClassTabs(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ClassTabs(Context context) {
super(context);
init(context);
}
// @Override
// protected void onFinishInflate() {
// super.onFinishInflate();
// //((Activity)getContext()).getLayoutInflater().inflate(R.layout.tabview, this);
// LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// inflater.inflate(R.layout.tabview, this);
//
// }
private void init(Context context) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.tabview, this);
}
public void addTab(Button child){
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.tabview, this);
LinearLayout tab = (LinearLayout) view.findViewById(R.id.tab);
tab.addView(child);
}
}
选项卡.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"
android:background="@color/blue"
>
</LinearLayout>
如您所见,我在其中包含其他布局的活动。我想在代码中将按钮添加到其他布局(ClassTab)。我做了类似方法 addTab(Button child) 的事情,但是当我启动我的应用程序时我看不到那个按钮。如何在我的活动代码中添加按钮以包含布局?