Android dynamically changes layout and Android dynamically Layout

Source: Internet
Author: User

Android dynamically changes layout and Android dynamically Layout

For such a requirement, see the figure below:

It is actually a software login interface, initially the first figure. When the soft keyboard pops up, it becomes the second figure, because the login interface has a user name, password, and login button, otherwise, the keyboard will hide the logon button (in fact, the previous implementation is put in the ScrollView, listening to the keyboard pops up and scrolling to the bottom, and then hiding the keyboard and scrolling to the top ).

The simplest way is to add a few redundant views, hide unnecessary views based on the soft keyboard status, and display the desired View, but it feels too frustrating, then I think of the RelativeLayout layout studied in the previous two years. The layout of the RelativeLayout neutron control is relative. You only need to change the location rules of the application when the keyboard is hidden.

Let's take a look at the layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/root"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="20dp"    tools:context="${packageName}.${activityClass}" >    <RelativeLayout        android:id="@+id/container"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentTop="true" >        <ImageView            android:id="@+id/logo"            android:layout_width="150dp"            android:layout_height="150dp"            android:layout_centerHorizontal="true"            android:scaleType="centerCrop"            android:src="@drawable/ic_launcher"            tools:ignore="ContentDescription" />        <TextView            android:id="@+id/label"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@id/logo"            android:layout_centerHorizontal="true"            android:layout_marginLeft="10dp"            android:layout_marginTop="10dp"            android:text="@string/hello_world"            android:textSize="20sp" />    </RelativeLayout>    <EditText        android:id="@+id/input"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/container"        android:layout_margin="16dp"        android:hint="Input sth."        tools:ignore="HardcodedText" /></RelativeLayout>

The pop-up function of the soft keyboard is hidden by using the OnGlobalLayoutListener listener. The android: windowSoftInputMode = "stateHidden | adjustResize" is applied to the Activity. In this way, the soft keyboard is not displayed at the beginning. When the soft keyboard pops up, its.

Next is the code. All the code is here.

Public class MainActivity extends Activity {private View root; // private View logo on the outermost layer; // private View label on the Logo; // private int rootBottom = Integer near the Logo. MIN_VALUE; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); root = findViewById (R. id. root); logo = findViewById (R. id. logo); label = findViewByI D (R. id. label); root. getViewTreeObserver (). addOnGlobalLayoutListener (new OnGlobalLayoutListener () {@ Override public void onGlobalLayout () {Rect r = new Rect (); root. getGlobalVisibleRect (r); // The layout will be displayed when you enter the Activity. The first time onGlobalLayout is called, record the position at the bottom of the soft keyboard if (rootBottom = Integer. MIN_VALUE) {rootBottom = r. bottom; return;} // adjustResize. The height of the soft keyboard becomes smaller after it is displayed. if (r. bottom <rootBottom) {RelativeLayout. layoutPa Rams lp = (LayoutParams) logo. getLayoutParams (); // if the Logo is not horizontally centered, it indicates that the layout is changed due to the subsequent changes to the Logo size. if (lp. getRules () [RelativeLayout. CENTER_HORIZONTAL]! = 0) {// the Logo is displayed in the upper left corner of the lp. addRule (RelativeLayout. CENTER_HORIZONTAL, 0); // cancel the horizontal center lp. addRule (RelativeLayout. ALIGN_PARENT_LEFT); // align left // reduce the Logo to 1/2 int height = logo. getHeight (); // getMeasuredHeight () int width = logo. getWidth (); lp. width = width/2; lp. height = height/2; logo. setLayoutParams (lp); // The text RelativeLayout under the Logo. layoutParams labelParams = (LayoutParams) label. getLayoutParams (); labelParams. addRule (RelativeLayout. CENTER_HORIZONTAL, 0); // cancel horizontal center labelParams. addRule (RelativeLayout. BELOW, 0); // deselect labelParams at the bottom of the logo. addRule (RelativeLayout. RIGHT_OF, R. id. logo); // labelParams to the right of the Logo. addRule (RelativeLayout. CENTER_VERTICAL); // vertical center label. setLayoutParams (labelParams);} else {// close the keyboard or RelativeLayout during initialization. layoutParams lp = (LayoutParams) logo. getLayoutParams (); // if there is no horizontal center, it means that the keyboard is collapsed; otherwise, it is the initialization at the beginning or the layout is again caused by the statement modification control in the if condition, which is ignored, otherwise, if (lp. getRules () [RelativeLayout. CENTER_HORIZONTAL] = 0) {// center Logo lp. addRule (RelativeLayout. CENTER_HORIZONTAL); lp. addRule (RelativeLayout. ALIGN_PARENT_LEFT, 0); // restore the Logo to the original size int height = logo. getHeight (); int width = logo. getWidth (); lp. width = width * 2; lp. height = height * 2; logo. setLayoutParams (lp); // The text RelativeLayout under the Logo. layoutParams labelParams = (LayoutParams) label. getLayoutParams (); labelParams. addRule (RelativeLayout. CENTER_HORIZONTAL); // sets the horizontal center labelParams. addRule (RelativeLayout. BELOW, R. id. logo); // set labelParams under the Logo. addRule (RelativeLayout. RIGHT_OF, 0); // deselect labelParams on the right of the Logo. addRule (RelativeLayout. CENTER_VERTICAL, 0); // cancel the vertical center label. setLayoutParams (labelParams );}}}});}}

Layout is also performed when the Activity is started.RootBottomRecords the position at the bottom of the outermost layout at the beginning. When the keyboard pops up, the layout is compressed and the position at the bottom of the same View is obtained again.RootBottomThe novel's soft keyboard pops up. If it is greater than or equalRootBottomIt indicates that the keyboard is hidden.

All the code is on the top, and there are also detailed comments. There are two points to note:

We can see the filtering conditions in the above Code. Taking the else statement as an example, the Activity will enter else when it starts. At this time, the Logo is horizontally centered and the if statement in else will be skipped, in this way, the first case is handled.

When the Logo is changed to the upper left corner because the if statement block is changed to display in the upper left corner, the if statement in the else is displayed, And the Logo is changed to the horizontal center, because the size and position of the Logo are modifiedOnGlobalLayoutBut now the Logo has been set to horizontally centered and will not go into the if statement in else again. In this way, the above two points of attention are handled through a condition judgment.

About addRule

The rules applied by each child control in RelativeLayout are saved through arrays, as shown below:

public static final int TRUE = -1;public void addRule(int verb) {    mRules[verb] = TRUE;    mInitialRules[verb] = TRUE;    mRulesChanged = true;}public void addRule(int verb, int anchor) {    mRules[verb] = anchor;    mInitialRules[verb] = anchor;    mRulesChanged = true;}

Take the index of a rule as the subscript, and the value is the anchor corresponding to the rule. If it is relative to another sub-control, the value is the ID of another sub-control. If it is relative to the parent control, the value is 'true', that is,-1. If no rule is applied, the value is 0,RemoveRuleIs to change the value of the corresponding position to 0:

public void removeRule(int verb) {    mRules[verb] = 0;    mInitialRules[verb] = 0;    mRulesChanged = true; }

RemoveRuleYesAPI 17In orderAPI 17Can also be used before, you can use its equivalent method, as in the above example, useAddRule (verb, 0).


How can I dynamically change the background color of the linearlayout layout in android?

It is recommended that selector be used for convenience.

Selector_list_view_item.xml
<? Xml version = "1.0" encoding = "UTF-8"?> <Selector xmlns: android = "schemas.android.com/apk/res/android"> <! -- Default color --> <item android: state_pressed = "false" android: drawable = "@ color/white"> </item> <! -- Click the color --> <item android: state_pressed = "true" android: drawable = "@ color/light_blue"> </item> </selector>
Then, set the root Layout background in the ListView item. xml file to selector_list_view_item.xml.
<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "android: layout_width =" match_parent "android: layout_height =" match_parent "android: orientation =" horizontal "android: background = "@ drawable/selector_list_view_item"> </LinearLayout>
OK!

In the selector_list_view_item.xml file, @ color/white and @ color/light_blue are defined in colors. xml. You can set any color.


How can we achieve Android dynamic layout?

Your problem is to dynamically generate space.
The following answers can be found below.
First, you need to configure the layout of this interface, including AbsoluteLayout, RelativeLayout, and others. Then you can add the control in it:
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
// Determine the page layout
AbsoluteLayout abslayout = new AbsoluteLayout (this );
SetContentView (abslayout );
// Create a button
Button btn1 = new Button (this );
Btn1.setText ("this is a button ");
Btn1.setId (1 );
// Determine the widget size and position
AbsoluteLayout. LayoutParams lp1 =
New AbsoluteLayout. LayoutParams (
ViewGroup. LayoutParams. WRAP_CONTENT,
ViewGroup. LayoutParams. WRAP_CONTENT,
0,100 );
Abslayout. addView (btn1, lp1 );

}
One layout can be arranged on one interface, and multiple la s can be designed together:
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );

// Set the page layout
RelativeLayout relativeLayout = new RelativeLayout (this );
SetContentView (relativeLayout );

// Add an AbsoluteLayout sub-layout and add a button to the layout
AbsoluteLayout abslayout = new AbsoluteLayout (this );
Abslayout. setId (11 );
Button btn1 = new Button (this );
Btn1.setText ("this is a abslayout button ");
Btn1.setId (1 );
AbsoluteLayout. LayoutParams lp0 = new AbsoluteLayout. LayoutParams (ViewGroup. LayoutParams. WRAP_CONTENT,
ViewGroup. LayoutParams. WRAP_CONTENT, 100,0 );
Abslayout. addView (btn1, lp0 );
// Add this sub-layout to the main layout
RelativeLayout. LayoutParams lp1 = new RelativeLayout. LayoutParams (ViewGroup. LayoutParams. WRAP_CONTENT, ViewGroup. LayoutParams. WRAP_CONTENT );
Lp1.addRule (RelativeLayout. ALIGN_PARENT_TOP );
Lp1.addRule (RelativeLayout. CENTER_HORIZONTAL, RelativeLayout. TRUE );
RelativeLayout. addView (AB ...... remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.