我需要通過單擊另一個按鈕(添加新)來添加按鈕。我對按鈕的代碼添加新按鈕如何通過單擊另一個按鈕來添加新按鈕
addnew = (Button)findViewById(R.id.btnaddnew);
addnew.setOnClickListener(this);
public void onClick(View v) {
if(v == addnew)
{
Button myButton = new Button(this);
myButton.setText("New Button");
myButton.setId(some_random_id);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
}
上面的代碼工作正常添加按鈕的佈局,但在關閉應用程序後,當我再次打開它加到前面是不是有新的按鈕。有人可以幫
實施sharedprefrences 代碼的onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lvInb = (ListView) findViewById(R.id.lvInb);
addnew = (Button)findViewById(R.id.btnaddnew);
addnew.setOnClickListener(this);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
代碼的onClick
public void onClick(View v) {
if(v == addnew)
{
count = prefs.getInt("count", 0);
for(int i=0;i<count;i++){
Button myButton = new Button(this);
myButton.setText("New Button");
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
count++;
Editor editor = prefs.edit();
editor.putInt("count", count);
editor.commit();
} }
你應該瞭解的基本知識,因爲你的問題是關於國家應用程序和活動生命週期。沒有知識就不應該開始編碼。 – TommyNecessary
檢查此鏈接http://stackoverflow.com/questions/18757381/saving-dynamically-added-linearlayouts-without-using-savedinstancestate – Ranjit