如何使用不同活动的按钮在另一个活动中自动创建按钮?
问题描述:
我在MainActivity中有一个按钮。如何使用不同活动的按钮在另一个活动中自动创建按钮?
我想在第二个活动中创建新的按钮。
每次用户按下MainActivity中的按钮时,都应该在第二个活动中自动创建相同数量的按钮。
答
以下是获取否的示例代码。按钮点击另一个活动。在这里,如果用户点击了3次,6次或9次,然后再次调用第二个活动并创建了许多按钮,则需要执行此操作。
MainActivity.java
public class MainActivity extends Activity {
Button btn;
int i =0;
SharedPreferences.Editor preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
i++;
preferences.putInt("value", i).apply();
if(i==3 || i==6 || i==9){
Intent intent = new Intent(MainActivity.this, Second.class);
startActivity(intent);
}
}
});
}
}
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sample.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text22"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="Button" />
</RelativeLayout>
SecondActivity.java
public class SecondActivity extends Activity {
int value;
SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
preferences = PreferenceManager.getDefaultSharedPreferences(SecondActivity.this);
value = preferences.getInt("value", 0);
System.out.println("SecondActivity.onCreate() of i ----- " + value);
for (int i = 1; i <= value; i++) {
Button myButton = new Button(this);
myButton.setText("Add Me");
LinearLayout ll = (LinearLayout) findViewById(R.id.layout);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
myButton.setLayoutParams(lp);
ll.addView(myButton, lp);
}
}
}
second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/layout"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.example.sample.Second" >
</LinearLayout>
下面是截图。
计数的点击次数,把它作为一个整数意图而开始另一个活动。根据点击次数,使用循环在运行时创建按钮。 –
欢迎来到Stack Overflow!据我所知,我编辑了你的问题。但是,加入你的努力,如代码,图片等,以便更多有知识的人会看到它。祝你好运! – manetsus