是否可以通过按下按钮来复制元素(例如,我已经在活动屏幕上显示的微调器)?而且我将能够同时使用两个微调器并添加所需的数量?
答案 0 :(得分:1)
此代码向您展示如何以编程方式创建微调器并将其添加到LinearLayout。
您可以调用makeSpinner方法并获得重复的微调器。
然后通过调用addView方法将其作为子视图添加到您的ViewGroup中。
提示:您应该存储添加的微调器的参考,以供以后访问。我将它们存储在mSpinners中。
public class MainActivity extends AppCompatActivity {
private LinearLayout mLinearLayout;
private ArrayList<Spinner> mSpinners; // to hold reference of added spinner for reading purposes
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinners = new ArrayList<>();
mLinearLayout = findViewById(R.id.my_linearLayout);
mLinearLayout.addView(makeSpinner()); // First spinner
Button duplicateSpinner = findViewById(R.id.bt_duplicate);
duplicateSpinner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner); // Add another spinner
}
});
Button getSpinner = findViewById(R.id.bt_getSpinner);
getSpinner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (int i = 0; i < mSpinners.size(); i++) { // Read all spinners
Spinner spinner = mSpinners.get(i);
Log.i("TAG", spinner.getSelectedItem().toString());
}
}
});
}
private Spinner makeSpinner() {
Spinner spinner = new Spinner(this, Spinner.MODE_DROPDOWN);
// Setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
spinner.setLayoutParams(layoutParams);
// Prepare data
ArrayList<String> data = new ArrayList<>(); // change it based on your code
data.add("Item 1");
data.add("Item 2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
mSpinners.add(spinner); // store it
return spinner;
}
}
这是activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/my_linearLayout"
android:orientation="vertical"
tools:context="com.khahani.app.stack.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt_duplicate"
android:text="Duplicate"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt_getSpinner"
android:text="Get Selected Item"/>
</LinearLayout>
享受吧。