Android learning notes: UI controls and layout

Keywords: Android SQLite

1. Common properties of view class:
android:id sets the identifier of the control
android:layout_width sets the layout width of the subcomponent
android:layout_height sets the layout height of the subcomponent
android:background sets the background color of the control
android:onClick sets the click event binding listener for the control
android:visibility sets whether the control is visible
android:alpha sets the transparency of the control (a value between 0 and 1)
android:padding sets the inner margin of subcomponents
android:layout_margin sets the outer margin of the subcomponent
android:onClick sets the callback method corresponding to the click event for the control
android:layout_width
android:layout_heigh
2.TextView

<TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="24sp"
        android:textColor="#00ff00"
        android:text="This is TextView"/>
  <!--match_parent/file_parent:Same as parent layout wrap_content:Just fit content
    gravity="center"=center_vertical|center_horizontal;top\bottom\left\right\center
    android:textSize="24sp"//Specify size
    android:textColor="#00ff00 "/ specify color
    -->

3.Button

<Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textAllCaps="false"/>
   <!--android:textAllCaps="false"Display does not convert case-->

4.EditText class inherits from TextView class and has all the properties of TextView. The difference is that the user can edit the EditText control and set a listener for the EditText control to judge whether the user's input is legal.

<EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Type something here"
        android:maxLines="2"/>The maximum number of rows is 2
<EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Type something here"/>Input prompt
Button button=(Button) findViewById(R.id.button);
        EditText editText=(EditText) findViewById(R.id.edit_text);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button:
                        String inputText=editText.getText().toString();
                        Toast.makeText(MainActivity.this,inputText,Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        });

5.ImageView

<ImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img_1"/>
ImageView imageView=(ImageView) findViewById(R.id.image_view) ;
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button:
                        imageView.setImageResource(R.drawable.img_2);
                        break;
                    default:
                        break;
                }
            }
        });

5.ProgressBar
The progress bar is a control commonly used to indicate the download progress of things downloaded at ordinary times. You need to set the layout and style of the ProgressBar in the Xml file corresponding to the Activity.
android:visibility sets whether the control is visible

<ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
ProgressBar progressBar =(ProgressBar) findViewById(R.id.progress_bar);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button:                   
                        /*
                        setVisibility(View.VISIBLE)so
                        setVisibility(View.INVISIBLE)invisible
                        setVisibility(View.GONE)Invisible and does not occupy screen space
                        */
                        if(progressBar.getVisibility()==View.GONE){
                            progressBar.setVisibility(View.VISIBLE);
                        }else {
                            progressBar.setVisibility(View.GONE);
                        }
                        break;
                    default:
                        break;
                }
            }
        });

6. Horizontal progress bar

<ProgressBar
...
style="?android:attr/progressBarStyleHorizontal"
 android:max="100"/>

Each time you click the button, the progress bar increases by 10

ProgressBar progressBar =(ProgressBar) findViewById(R.id.progress_bar);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button:
                int progress=progressBar.getProgress();
                progress=progress+10;
                progressBar.setProgress(progress);
                break;
            default:
                break;
        }
    }
});

7.AlterDialog
Toast is used to display the prompt content, while AlterDialog is a warning box, which can have some controls, such as buttons. Initialize AlterDialog and display it:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button:
                        AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);
                        //Create an AlertDialog instance through AlertDialog.Builder, and set the title, content, and whether to cancel,
                        // setPositiveButton() sets the click event of the OK button,
                        //setNegativeButton() sets the click event of the Cancel button
                        //show() will display the dialog box
                        dialog.setTitle("This is Dialog");
                        dialog.setMessage("Something important");
                        dialog.setCancelable(false);
                        dialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        dialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        dialog.show();
                        break;
                    default:
                        break;
                }
            }
        });

(1) AlterDialog is created through the Builder of AlterDialog. When it is created, it will be specified that the AlterDialog will be displayed on that Activity.
(2) Set the title for AlterDialog through setTitle method, and set the content for AlterDialog through setMessage.
(3) setCancelable() method. When we set false here, it means that the pop-up AlterDialog will not disappear when the user clicks the return key. This value is true by default.
(4) setPositiveButton() method is used to set the event when clicking OK, and setNegativeButton is used to set the event when clicking cancel. Click through Toast to show the event.

8. ProgressDialog (Progress prompt box)
Add Progress on AlterDialog
setCancelable(false);// You cannot cancel the back. When the data is loaded, you must call the disassiss() method of ProgressDialog to close the dialog box. Otherwise, ProgressDialog will always exist.

9. Four layout modes: linear layout, relative layout, frame layout and table layout

10. Linear layout
Set whether to arrange horizontal ly or vertical ly through the android:orientation property

   <LinearLayout xmls:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
 <Button
        android:layout_gravity="top"/>
Layout as horizontal,Control should be vertical vertical upper layout_gravity,
top,center_vertical,bottom Top, middle, bottom
<Button
 android:layout_weight="1"/>
<Button
 android:layout_weight="1"/>
Bisect width horizontally
<Button
 android:layout_weight="2"/>
<Button
 android:layout_weight="3"/>
Horizontal direction 2/5,3/5 width
 Note: layout_weight only LinearLayout realization
</LinearLayout>

11.RelativeLayout
Relative layout can determine the position of other newly added controls according to the fixed controls.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
//Relative to the upper left edge of the parent layout
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
//Relative to the upper right edge of the parent layout
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" 
//Relative to the parent layout
        android:layout_centerInParent="true"
//Relative to the lower left edge of the parent layout
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
//Relative to the upper right edge of the parent layout
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
</RelativeLayout>

Relative to control: button3

android:layout_toRightOf="@+id/button3"
android:layout_toLiftOf="@+id/button3"
android:layout_above="@id/button3"
android:layout_below="@id/button3"

Align relative to control edge:

android:layout_alignLeft="@id/button3"
android:layout_alignRight="@id/button3"
android:layout_alignTop="@id/button3"
android:layout_alignBottom="@id/button3"

layout_margin is offset in the up, down, left and right directions, layout_marginLeft offset left
12. Frame layout
Position of upper left corner

13. Percentage layout

14. Custom layout
Custom title.xml
Use: < include layout = "@ layout / Title" / >
Hide title block

ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }

Add dynamic loading to the layout: layoutinflator

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this);
        //Dynamically load the title block layout, which is realized by layoutinflator,
        //The from method can be used to build a layoutinflator object,
        //The inflate method dynamically loads a layout file (the id of the loaded layout file and adds a parent layout to the loaded layout)
        Button titleBack=(Button) findViewById(R.id.title_back);
        Button titleEdit=(Button) findViewById(R.id.title_edit);
        titleBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Activity) getContext()).finish();
            }
        });
        titleEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),"You clicked Edit button",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

15.ListView displays a large amount of data

 <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
public class MainActivity extends AppCompatActivity {
    private String[] data = { "Apple", "Banana", "Orange", "Watermelon", "Pear",
            "Grape", "Pineapple", "Strawberry", "Cherry", "Mango", "Apple",
            "Banana", "Orange", "Watermelon", "Pear", "Grape", "Pineapple",
            "Strawberry", "Cherry", "Mango" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //The data in the array cannot be directly passed to the ListView, and needs to be completed with the help of the adapter. Android provides many adapter implementation classes, of which the commonly used is ArrayAdapter
        // ArrayAdapter can specify the data type to be adapted through generics, and then pass in the data to be adapted in the constructor.
        // ArrayAdapter has multiple constructor overloads. Select the most appropriate one according to the actual situation.
        // Build the adapter object, and in the constructor of ArrayAdapter, successively pass in the current context, the id of the ListView sub item layout, and the data to be adapted.
        // android.R.layout.simple_list_item_1 as the id of the ListView sub item layout, this is an Android built-in layout file. There is only one TextView in it, which can be used to simply display a piece of text.
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,data);
        ListView listView=(ListView) findViewById(R.id.list_view); 
        // Finally, the setAdapter() method of ListView is invoked to transfer the constructed adapter objects, so that the relationship between ListView and data is established.
        listView.setAdapter(adapter);
    }
}

16. Customize ListView
Fruit class:

package com.example.listviewtest;

public class Fruit {
    private String name;
    private int imageId;
    public Fruit(String name, int imageId) {
        this.name = name;
        this.imageId = imageId;
    }
    public String getName() {
        return name;
    }
    public int getImageId() {
        return imageId;
    }
}

FruitAdapter adapter Customization:

public class FruitAdapter extends ArrayAdapter <Fruit>{
    private int resourceId;
    //Construction method to transfer the context, sub item layout id and data
    public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects){
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }
    @Override
    //Override the getView method, which is called when each child item is scrolled into the screen
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);//Gets the Fruit instance of the current item
        //Use layoutinflator to load the layout we passed in for this child.
        // Dynamically load the layout, which is realized by layoutinflator,
        // A layoutinflator object can be built through the from method, and a layout file (the id of the loaded layout file, adding a parent layout to the loaded layout) can be dynamically loaded by the inflate method
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
        TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
        //Set the displayed picture and text
        fruitImage.setImageResource(fruit.getImageId());
        fruitName.setText(fruit.getName());
        return view;
    }
}
public class MainActivity extends AppCompatActivity {
   private List<Fruit> fruitList = new ArrayList<>();//Fruit instance list
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits(); // Initialize fruit data
        FruitAdapter adapter = new FruitAdapter( MainActivity.this,
                R.layout.fruit_item, fruitList);
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
    }

    private void initFruits() {
        //Create a fruit instance and add it to the fruit instance list
        for (int i = 0; i < 5; i++) {
            Fruit apple = new Fruit("Apple", R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana", R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit("Orange", R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit  watermelon= new Fruit("Watermelon", R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit("Pear", R.drawable.pear_pic);
            fruitList.add(pear );
            Fruit grape = new Fruit("grape", R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("Pineapple", R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit("Strawberry", R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit("Cherry", R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit("Mango", R.drawable.mango_pic);
            fruitList.add(mango);
        }
    }

}

17. Optimization

public class FruitAdapter extends ArrayAdapter <Fruit>{
    private int resourceId;
    //Construction method to transfer the context, sub item layout id and data
    public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects){
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }
    @Override
    public View getView(int position,  View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);//Gets the Fruit instance of the current item
        View view;
        ViewHolder viewHolder;
        // convertView is used to cache previously loaded layouts
        if (convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder=new ViewHolder();
            viewHolder.fruitImage=(ImageView) view.findViewById(R.id.fruit_image);
            viewHolder.fruitName=(TextView) view.findViewById(R.id.fruit_name);
            view.setTag(viewHolder);//Store viewholder in View
        }else {
            view = convertView;
            viewHolder=(ViewHolder) view.getTag();//Retrieve object
        }
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;
    }
    // Add an internal class to cache the instance of the control
    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    }
}

18.ListView setting listening:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Fruit fruit=fruitList.get(position);
                Toast.makeText(MainActivity.this,fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Posted by dagee on Thu, 02 Sep 2021 15:06:42 -0700