我如何在第二个受保护的void finishButton中使用受保护的void onCreate中的linearLayout和params变量?我需要将finishButton添加到linearLayout。这是我的代码:
public class MainActivity extends AppCompatActivity {
public static int score = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
final LinearLayout linearLayout = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(linearLayout.VERTICAL);
linearLayout.setPadding(0, 110, 0, 0);
scrollView.addView(linearLayout);
TextView iq_Test_Title = new TextView(this);
iq_Test_Title.setText("Text");
iq_Test_Title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
iq_Test_Title.setGravity(Gravity.CENTER);
iq_Test_Title.setTextColor(Color.RED);
linearLayout.addView(iq_Test_Title);
finishButton();
// other code
}
protected void finishButton() {
final Button finishButton = new Button(this);
finishButton.setText(R.string.finish_button);
finishButton.setLayoutParams(params);
linearLayout.addView(finishButton);
finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finishButton.setEnabled(false);
}
});
}
}
谢谢!
答案 0 :(得分:1)
要访问finishButton
方法中的视图,只需将其设为类级别变量:
public class MyActivity...
private LinearLayout mLinearLayout;
protected void onCreate(..){
mLinearLayout = new LinearLayout(this);
...
}
private void finishButton(){
...
mLinearLayout.addView(..);
}
}
答案 1 :(得分:0)
如果我理解正确,您可能希望将该按钮从finishButton()返回给调用者。然后将其添加到onCreate中的视图。
将finishButton的声明更改为
protected Button finishButton()
配置完成后,添加以下行:
return finishButton;
在该方法的最后。然后在onCreate:
linearLayout.addView(finishButton());