到目前为止我有两节课。
MainActivity.java
public class MainActivity extends AppCompatActivity {
private PageBuilder pb = new PageBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.empty);
pb.mainMenu();
} }
PageBuilder.java
public class PageBuilder extends MainActivity {
public void mainMenu() {
LinearLayout ll = (LinearLayout) findViewById(R.id.empty);
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Button btnOne = new Button(getApplicationContext());
btnOne.setLayoutParams(btnParams);
btnOne.setText("One");
ll.addView(btnOne);
Button btnTwo = new Button(getApplicationContext());
btnTwo.setLayoutParams(btnParams);
btnTwo.setText("Two");
ll.addView(btnTwo);
Button btnThree = new Button(getApplicationContext());
btnThree.setLayoutParams(btnParams);
btnThree.setText("Three");
ll.addView(btnThree);
} }
我认为问题是我正在尝试从另一个班级findViewById
?当我在同一个类中调用方法时,它可以正常工作。
我试过public class PageBuilder extends Activity
&& AppCompatActivity
。调用该方法但它不喜欢LinearLayout ll = (LinearLayout) findViewById(R.id.empty);
(empty.xml确实存在且位于布局目录中)。
我在另一个课程中使用这些方法的唯一真正原因是清洁,但我认为这是一个非常基本的要求。
答案 0 :(得分:2)
在你的MainActivity中
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PageBuilder obj = new PageBuilder(this);
obj.mainMenu();
}}
在PageBuilder.java中
public class PageBuilder {
Context mContext;
PageBuilder(Context mContext){
this.mContext = mContext;
}
public void mainMenu() {
LinearLayout ll = new LinearLayout(mContext);
LinearLayout.LayoutParams llP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
ll.setLayoutParams(llP);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Button btnOne = new Button(mContext.getApplicationContext());
btnOne.setLayoutParams(btnParams);
btnOne.setText("One");
ll.addView(btnOne);
Button btnTwo = new Button(mContext.getApplicationContext());
btnTwo.setLayoutParams(btnParams);
btnTwo.setText("Two");
ll.addView(btnTwo);
Button btnThree = new Button(mContext.getApplicationContext());
btnThree.setLayoutParams(btnParams);
btnThree.setText("Three");
ll.addView(btnThree);
Activity activity = (Activity)mContext;
activity.setContentView(ll);
}}