我有兩個類:一個是活動,第二個是擴展LinearLayout。這是活動代碼:在代碼中添加一些元素到其他佈局
public class SecondActivity extends Activity{
private Button button;
private ClassTabs tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Button next = (Button) findViewById(R.id.nextActivity);
button = new Button(getApplicationContext());
LayoutInflater inflater = LayoutInflater.from(this);
tab = (ClassTabs) inflater.inflate(R.id.tab, null);
tab.addTab(button);
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(intent);
}
});
}
}
和xml:
<?xml version="1.0" encoding="utf-8"?>
<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/tab1"
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>
這是類擴展的LinearLayout:
public class ClassTabs extends LinearLayout{
Button button;
public ClassTabs(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ClassTabs(Context context) {
super(context);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
((Activity)getContext()).getLayoutInflater().inflate(R.layout.tabview, this);
setupViewItems();
}
private void setupViewItems() {
button = new Button(getContext());
}
public void addTab(Button child){
LinearLayout tab = (LinearLayout) findViewById(R.id.tab);
tab.addView(child);
}
}
和xml:
<?xml version="1.0" encoding="utf-8"?>
<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>
現在,當你可以看到我有辦法給這個la添加一些孩子YOUT。我想從活動中添加一些按鈕到這個佈局。在那個解決方案中,我得到了nullPointer異常。我如何使用其他類的方法從活動中添加一些元素,在這種情況下是addTab()
?
編輯:這就是我想要的:在這種情況下,我有一個活動「第二個活動」,我想從「ClassTabs」使用佈局。我ClassTabs我想要有方法,將按鈕添加到活動中膨脹的佈局。我想在佈局中運行活動,我使用ClassTab的部分佈局。下一步是從ClassTab添加到這個膨脹的佈局,但我想在「第二個活動」的代碼中做到這一點。我想在ClassTab中添加按鈕的方法,因爲我想在其他活動中使用該方法。
什麼是你得到的NullPointerException? – drewmoore