Android 如何以编程方式并排放置元素?
我有一个微调器、复选框和eddittext。目前他们都是一个在另一个,但我想让它,所以他们是肩并肩的 例如: 左边是微调器,右边是edittext,然后是edittext右边的复选框 因为这些元素是通过编程方式创建的,所以可以通过编程方式实现吗 java代码Android 如何以编程方式并排放置元素?,android,android-layout,android-view,Android,Android Layout,Android View,我有一个微调器、复选框和eddittext。目前他们都是一个在另一个,但我想让它,所以他们是肩并肩的 例如: 左边是微调器,右边是edittext,然后是edittext右边的复选框 因为这些元素是通过编程方式创建的,所以可以通过编程方式实现吗 java代码 public class create extends AppCompatActivity { private LinearLayout mLinearLayout; private ArrayList<Searc
public class create extends AppCompatActivity {
private LinearLayout mLinearLayout;
private ArrayList<SearchableSpinner> mSpinners;
private List<AppCompatButton> mButtons = new ArrayList<>();
private List<CheckBox> mCheckboxes = new ArrayList<>();
private List<TextView> mTextviews = new ArrayList<>();
private List<EditText> mEdittexts = new ArrayList<>();
private List<View> mViews = new ArrayList<>();
private Map<String, String> numberItemValues = new HashMap<>();
private Spinner spinner;
private TextView textview;
private CheckBox checkbox;
List<String> itemList = new ArrayList<>();
LinearLayout verticallayout,horizontalLayout;
public static final String MY_PREFS_NAME = "MyPrefsFile";
TextView newTextview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.my_linearLayout).requestFocus();
verticallayout = findViewById(R.id.verticalLayout); //got
//Arrays
ArrayList<String> items = new ArrayList<>();
items.add(String.valueOf(mSpinners)); // add you selected item
mSpinners = new ArrayList<>();
//Initializing Variables Here
mLinearLayout = findViewById(R.id.my_linearLayout);
//verticallayout = findViewById(R.id.verticalLayout);
textview = findViewById(R.id.textview);
checkbox = findViewById(R.id.checkbox);
//TODO getting shared prefs on create
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
try {
JSONArray jsonArray2 = new JSONArray(prefs.getString("key", null));
for (int i = 0; i < jsonArray2.length(); i++) {
/* final Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner);*/
final View newView = makeView();
//Add a new view
mLinearLayout.addView(newView);
mViews.add(newView);
/* final EditText newEdittext = makeEdittext();
mLinearLayout.addView(newEdittext);
mEdittexts.add(newEdittext);
final CheckBox newCheckbox = makeCheckbox();
mLinearLayout.addView(newCheckbox);
//TODO add checkbox to your list
mCheckboxes.add(newCheckbox);*/
createRow();
newTextview = makeTextview();
mLinearLayout.removeAllViews();
mLinearLayout.addView(newTextview);
mTextviews.add(newTextview);
final int listSize = mViews.size();
//TODO deleting item
horizontalLayout.setOnClickListener(new View.OnClickListener() {
//start
@Override
public void onClick(View view) {
//when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.
final View.OnClickListener context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create.this);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
if (listSize > 0) {
//mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
mSpinners.get(listSize - 1).setVisibility(View.GONE);
// mSpinners.remove(listSize - 1);
mViews.get(listSize - 1).setVisibility(View.GONE);
mTextviews.get(listSize - 1).setVisibility(View.GONE);
// mEdittexts.get(listSize - 1).setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
int positionOfSpinner = (int) jsonArray2.get(i);
spinner.setSelection(positionOfSpinner);
}
} catch (Exception e) {
e.printStackTrace();
}
//end of shared pref code
//TODO FAB BUTTON
FloatingActionButton floatingActionButton =
(FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();
spinner = findViewById(R.id.spinner);
// Handle ze click.
/* final Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) spinner.getLayoutParams();
layoutParams.setMargins(5, 100, 10, 0); //top 70
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
layoutParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
layoutParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
spinner.setLayoutParams(layoutParams);
*/
final View newView = makeView();
mLinearLayout.addView(newView);
mViews.add(newView);
/* final EditText newEdittext = makeEdittext();
mLinearLayout.addView(newEdittext);
mEdittexts.add(newEdittext);*/
createRow();
final int listSize = mViews.size();
//code for deleting the said item.
horizontalLayout.setOnClickListener(new View.OnClickListener() {
//start
@Override
public void onClick(View view) {
//when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.
final View.OnClickListener context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create.this);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
if (listSize > 0) {
//mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
mSpinners.get(listSize - 1).setVisibility(View.GONE);
mSpinners.remove(listSize - 1);
mViews.get(listSize - 1).setVisibility(View.GONE);
mTextviews.get(listSize - 1).setVisibility(View.GONE);
//mEdittexts.get(listSize - 1).setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//Add a new checkbox
/* final CheckBox newCheckbox = makeCheckbox();
mLinearLayout.addView(newCheckbox);
//TODO add checkbox to your list
mCheckboxes.add(newCheckbox);*/
newTextview = makeTextview();
mLinearLayout.removeAllViews();
mLinearLayout.addView(newTextview);
mTextviews.add(newTextview);
//TODO Add the spinner on item selected listener to get selected items
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String currentItem = itemList.get(position);
String aisleNumber = numberItemValues.get(currentItem);
//TODO you can use the above aisle number to add to your text view
//mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
newTextview.setText(aisleNumber);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// code here, do nothing
}
});
}
});
}
//TODO OVERFLOW MENU
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
/*Intent startSettingsActivity = new Intent(this, AppCompatPreferenceActivity.class);
startActivity(startSettingsActivity);
//start the settings activity here.*/
startActivity(new Intent(create.this, settings.class));
return true;
}
else if (id == R.id.action_delete) {
//code to delete list here.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.clear();
editor.commit();
Toast.makeText(getBaseContext(), "List removed.", Toast.LENGTH_SHORT).show();
return true;
}
else if (id ==R.id.action_help) {
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Help");
builder.setMessage("To use this app, first go to Create your Shopping List.\n" +
"Here, you can add items to your list. Once you have added all items, you can click the menu at the top right corner (or if it doesnt appear press your menu button beside your home button on your device, then click View your List.\n" +
"This will take you to the screen where you can view you shopping list with the items in aisle order to make your shop much easier.\n" +
"You can still add items at this point. Press the white background of each item to delete the item if you wish.");
// add a button
builder.setPositiveButton("OK", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
else if (id == R.id.action_gotoview) {
//takes the size of the list of spinners, for reference
ArrayList<Integer> spinnerList = new ArrayList<>();
for(int i = 0; i < mSpinners.size(); i++) {
spinnerList.add(mSpinners.get(i).getSelectedItemPosition());
}
Bundle newBundle = new Bundle();
newBundle.putIntegerArrayList("arraylist", spinnerList);
Intent newIntent = new Intent(create.this, viewscreen.class);
newIntent.putExtra("extraBundle", newBundle);
startActivity(newIntent);
//code to go to view screen, aka intent
return true;
}
return super.onOptionsItemSelected(item);
}
public void createRow(View view){
createRow(); //got
}
private void createRow() { //got
horizontalLayout = new LinearLayout(this);
LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalParams.height = 80;
horizontalParams.setMargins(0, 15, 0, 15); // LEFT, TOP, RIGHT, BOTTOM
horizontalLayout.setLayoutParams(horizontalParams);
horizontalLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.addButtons));
makeEdittext();
makeCheckbox();
makeSpinner();
makeTextview();
verticallayout.addView(horizontalLayout, horizontalParams);
}
//DUPLICATING ITEMS WHEN FAB IS PRESSED//
private CheckBox makeCheckbox() {
//Create new Checkbox
CheckBox checkbox = new CheckBox(this);
// Setup layout
/* LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//setup relative layout for the positioning of the objects
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams((int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)), (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)));
relativeParams.addRule(RelativeLayout.RIGHT_OF, R.id.textview);
checkbox.setLayoutParams(relativeParams);
checkbox.setLayoutParams(layoutParams);*/
LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
checkParams.setMargins(10, 10, 10, 10);
checkParams.gravity = Gravity.LEFT;
checkbox.setLayoutParams(checkParams);
horizontalLayout.addView(checkbox);
return checkbox;
}
private TextView makeTextview() {
//create new textview
TextView textview = new TextView(this);
//setup layout
/* LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(layoutParams);*/
LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
editParams.setMargins(10, 10, 10, 10);
editParams.width = 70;
editParams.height = 50;
textview.setLayoutParams(editParams);
horizontalLayout.addView(textview);
textview.setTextSize(30);
return textview;
}
private EditText makeEdittext() {
//create new edittext
EditText edittext = new EditText(this);
//setup layout
/* final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(70, 50); // Width , height
edittext.setLayoutParams(lparams);*/
LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
editParams.setMargins(10, 10, 10, 10);
editParams.width = 70;
editParams.height = 50;
edittext.setLayoutParams(editParams);
horizontalLayout.addView(edittext);
edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
edittext.setHint("qty");
return edittext;
}
//set the 3d effect to view
private View makeView() {
//create new View
View view = new View(this);
view.setBackgroundColor(Color.parseColor("#ffffff"));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100);
new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);
view.setLayoutParams(layoutParams);
view.setClickable(true);
//view.setLayoutParams(layoutParams);
//setup layout
return view;
}
private Spinner makeSpinner() {
//opens csv
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
//TODO I made this variable global, declared it at the very top of this file
itemList = csvFile.read();
//Create new spinner
// SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);
SearchableSpinner spinner = new SearchableSpinner(this);
// Setup layout
LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
spinnerParams.setMargins(10, 10, 10, 10);
spinnerParams.gravity = Gravity.LEFT;
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
spinnerParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
spinnerParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
spinner.setLayoutParams(spinnerParams);
horizontalLayout.addView(spinner);
/* LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
spinner.setLayoutParams(layoutParams);*/
MyListAdapter adapter = new MyListAdapter(this, R.layout.listrow, R.id.txtid, itemList);
spinner.setAdapter(adapter);
//Add it to your list of spinners so you can retrieve their data when you click the getSpinner button
mSpinners.add(spinner);
//TODO Add the spinner on item selected listener to get selected items
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String currentItem = itemList.get(position);
String aisleNumber = numberItemValues.get(currentItem);
//TODO you can use the above aisle number to add to your text view
//mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
newTextview.setText(aisleNumber);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
return spinner;
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
//on stop, the things are saved into shared prefs
@Override
protected void onStop () {
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
JSONArray jsonArray = new JSONArray();
for(int i = 0; i < mSpinners.size(); i++) {
jsonArray.put(mSpinners.get(i).getSelectedItemPosition());
}
editor.putString("key", jsonArray.toString());
editor.apply();
super.onStop();
}
}
在这条线上
mLinearLayout.addView(newTextview);
将线性布局方向设置为水平
<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:id="@+id/my_linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
我能够通过使用XML中的静态线性布局(垂直方向)和动态添加元素的水平行来实现这一点 layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="right"
android:onClick="createRow"
android:text="Create Row" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/verticalLayout"
android:layout_below="@id/button">
</LinearLayout>
</RelativeLayout>
动态添加布局的活动
public class MyLayoutActivity extends AppCompatActivity {
LinearLayout verticallayout,horizontalLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_poc);
verticallayout = findViewById(R.id.verticalLayout);
}
public void createRow(View view){
createRow();
}
private void createRow() {
horizontalLayout = new LinearLayout(this);
LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalLayout.setLayoutParams(horizontalParams);
createSpinner();
createCheckbox();
createEditText();
verticallayout.addView(horizontalLayout);
}
private void createEditText() {
EditText editText = new EditText(this);
LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
editParams.setMargins(10, 10, 10, 10);
editText.setLayoutParams(editParams);
horizontalLayout.addView(editText);
}
private void createCheckbox() {
CheckBox checkBox = new CheckBox(this);
LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
checkParams.setMargins(10, 10, 10, 10);
checkParams.gravity = Gravity.LEFT;
checkBox.setLayoutParams(checkParams);
horizontalLayout.addView(checkBox);
}
private void createSpinner() {
Spinner spinner = new Spinner(this);
//ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, spinnerArray);
//spinner.setAdapter(spinnerArrayAdapter);
LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
spinnerParams.setMargins(10, 10, 10, 10);
spinnerParams.gravity = Gravity.LEFT;
spinner.setLayoutParams(spinnerParams);
horizontalLayout.addView(spinner);
}
}
公共类MyLayoutActivity扩展了AppCompatActivity{
线性布局垂直布局、水平布局;
@凌驾
创建时受保护的void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout\u poc);
垂直布局=findViewById(R.id.verticallayout);
}
公共void createRow(视图){
createRow();
}
私有void createRow(){
水平布局=新的线性布局(本);
LinearLayout.LayoutParams horizontalParams=新的LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_父项,LinearLayout.LayoutParams.WRAP_内容);
水平布局。设置方向(线性布局。水平);
水平布局。设置布局参数(水平参数);
createSpinner();
createCheckbox();
createEditText();
垂直布局。添加视图(水平布局);
}
私有void createEditText(){
EditText EditText=新的EditText(本);
LinearLayout.LayoutParams editParams=新的LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_父项,LinearLayout.LayoutParams.WRAP_内容);
editParams.setMargins(10,10,10,10);
editText.setLayoutParams(editParams);
水平布局。添加视图(编辑文本);
}
私有void createCheckbox(){
复选框=新复选框(此复选框);
LinearLayout.LayoutParams checkParams=新建LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_内容,LinearLayout.LayoutParams.WRAP_内容);
checkParams.setMargins(10,10,10,10);
checkParams.gravity=gravity.LEFT;
checkBox.setLayoutParams(checkParams);
水平布局。添加视图(复选框);
}
私有void createSpinner(){
微调器微调器=新微调器(此);
//ArrayAdapter SpinnerayAdapter=新的ArrayAdapter(这是android.R.layout.simple\u spinner\u dropdown\u项目,Spinnerary);
//spinner.setAdapter(SpinNearrayaAdapter);
LinearLayout.LayoutParams喷丝头Params=新的LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_内容,LinearLayout.LayoutParams.WRAP_内容);
喷丝头参数毛缘(10,10,10,10);
喷丝头参数gravity=gravity.LEFT;
spinner.setLayoutParams(spinnerParams);
水平布局。添加视图(微调器);
}
}
根据您的逻辑将数据添加到微调器阵列适配器中。您可以根据设计更改布局参数。我的代码给出的输出如下图所示:
试试这个方法 home_activity.xml
HomeActivity.java
公共类HomeActivity扩展了AppCompatActivity{
线性布局垂直布局、水平布局;
整数宽度;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home_活动);
垂直布局=findViewById(R.id.verticallayout);
DisplayMetrics DisplayMetrics=新的DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
宽度=displayMetrics.widthPixels;
}
公共void createRow(视图){
createRow();
}
私有void createRow(){
水平布局=新的线性布局(本);
LinearLayout.LayoutParams horizontalParams=新的LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_父项,LinearLayout.LayoutParams.WRAP_内容);
水平布局。设置方向(线性布局。水平);
水平布局。设置布局参数(水平参数);
createSpinner();
createCheckbox();
createEditText();
垂直布局。添加视图(水平布局);
}
私有void createEditText(){
EditText EditText=新的EditText(本);
LinearLayout.LayoutParams editParams=新的LinearLayout.LayoutParams((宽度/3),convertdptopix(40));
editParams.setMargins(10,10,10,10);
editText.setLayoutParams(editParams);
setHint(“输入某物”);
editText.setTextSize(14f);
水平布局。添加视图(编辑文本);
}
私有void createCheckbox(){
复选框=新复选框(此复选框);
LinearLayout.LayoutParams checkParams=新的LinearLayout.LayoutParams((宽度/3),convertdptopix(40));
checkParams.setMargins(10,10,10,10);
//checkParams.gravity=gravity.LEFT;
checkBox.setLayoutParams(checkParams);
checkBox.setText(“适用”);
水平布局。添加视图(复选框);
}
私有void createSpinner(){
微调器微调器=新微调器(此);
LinearLayout.LayoutParams spinnerParams=新的LinearLayout.LayoutParams((宽度/3),convertDpToPixel(40));;
喷丝头参数毛缘(10,10,10,10);
//喷丝头参数gravity=gravity.LEFT;
spinner.setLayoutParams(spinnerParams);
字符串[]项=新字符串[]{“item1”、“item2”、“item3”、“item4”、“item5”、“item6”、“item7”};
ArrayAdapter spinnerayadapter=新的ArrayAdap
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="createRow"
android:text="Create Row" />
<LinearLayout
android:id="@+id/verticalLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
public class HomeActivity extends AppCompatActivity {
LinearLayout verticallayout, horizontalLayout;
int width;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
verticallayout = findViewById(R.id.verticalLayout);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
}
public void createRow(View view) {
createRow();
}
private void createRow() {
horizontalLayout = new LinearLayout(this);
LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalLayout.setLayoutParams(horizontalParams);
createSpinner();
createCheckbox();
createEditText();
verticallayout.addView(horizontalLayout);
}
private void createEditText() {
EditText editText = new EditText(this);
LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams((width/3), convertDpToPixel(40));
editParams.setMargins(10, 10, 10, 10);
editText.setLayoutParams(editParams);
editText.setHint("Enter something");
editText.setTextSize(14f);
horizontalLayout.addView(editText);
}
private void createCheckbox() {
CheckBox checkBox = new CheckBox(this);
LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams((width/3), convertDpToPixel(40));
checkParams.setMargins(10, 10, 10, 10);
// checkParams.gravity = Gravity.LEFT;
checkBox.setLayoutParams(checkParams);
checkBox.setText("Is Applicable");
horizontalLayout.addView(checkBox);
}
private void createSpinner() {
Spinner spinner = new Spinner(this);
LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams((width/3), convertDpToPixel(40));;
spinnerParams.setMargins(10, 10, 10, 10);
// spinnerParams.gravity = Gravity.LEFT;
spinner.setLayoutParams(spinnerParams);
String[] item = new String[]{"item1","item2","item3","item4","item5","item6","item7"};
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, item);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println(parent.getSelectedItem().toString());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
horizontalLayout.addView(spinner);
}
public int convertDpToPixel(int dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
return dp * ((int) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
}
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.yourxmlrow, null, false);
linearLayout.addView(v);
mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);