我想动态创建一个线性布局。
如何将其设置为在警报对话框中显示?
我已经看到了一些例子,其中的布局是通过xml创建的,并进行了扩展以显示,但是我不想在可以动态创建xml布局的情况下创建它。
我只限于API16=Android4.1.2
这是我活动的一个按钮…
public void TestOnClick() {
Button test_button = (Button) findViewById(R.id.button_test);
test_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout layout = new LinearLayout(v.getContext());
//Create a TextView to add to layout
TextView textview = new TextView(v.getContext());
textview.setText("My Test");
layout.addView(textview);
//Add abunch of other items to the layout
//blah blah blah
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setView(layout);
builder.setNeutralButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
最佳答案
看起来我必须执行以下操作,以动态和编程方式创建LinearLayout并在AlertDialog上显示该布局:
public void TestOnClick() {
Button test_button = (Button) findViewById(R.id.button_test);
test_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Create LinearLayout Dynamically
LinearLayout layout = new LinearLayout(v.getContext());
//Setup Layout Attributes
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
layout.setOrientation(LinearLayout.VERTICAL);
//Create a TextView to add to layout
TextView textview = new TextView(v.getContext());
textview.setText("My Text");
//Create Spinner
Spinner spinner = new Spinner(v.getContext());
String[] string_list = new String[]{"Test 1", "Test 2", "Test 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_selectable_list_item, string_list);
spinner.setAdapter(adapter);
spinner.setGravity(Gravity.CENTER);
//Create button
Button button = new Button(v.getContext());
button.setText("My Button");
button.setWidth(100);
button.setHeight(50);
//Add Views to the layout
layout.addView(textview);
layout.addView(spinner);
layout.addView(button);
//Create AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
//Give the Dialog a Title
builder.setTitle("Results");
//Set the Dynamically created layout as the Dialogs view
builder.setView(layout);
//Add Dialog button that will just close the Dialog
builder.setNeutralButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//Show the custom AlertDialog
AlertDialog alert = builder.create();
alert.show();
}
});
}