android: dialog AlertDialog

The implementation of the Android dialog box needs to use  the AlertDialog.Builder  instance object

Then we use the following method of this object

Here are a few commonly used methods

setTitle(): Set the title   
setview(): Set a custom page (the custom page will be described in detail below) 
setPositiveButton(): Generally used to determine the function 
setNegativeButton(): Generally used to cancel the function 
setOnShowListener(): The dialog box appears 
setOnCancelListener( ): the dialog disappears

show(): Used to display the dialog box   Note: Without this sentence your dialog box will not be displayed


Generally, when we customize the page, we will not write all in one page, resulting in code confusion

It is often necessary to create a new page. Here, there is no need to create a new Activity, only a Layout layout page is needed

Here simply write a

 code show as below:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:orientation="vertical">

    <EditText
        android:id="@+id/ed_ip"
        android:layout_width="269dp"
        android:layout_height="83dp"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="68dp"
        android:ems="10"
        android:gravity="center"
        android:hint="请输入IP,例如192.168.1.1"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/ed_port"
        android:layout_width="261dp"
        android:layout_height="86dp"
        android:layout_marginTop="120dp"
        android:layout_marginEnd="72dp"
        android:ems="10"
        android:gravity="center"
        android:hint="请输入端口,例如8080"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

So how do we add to AlertDialog?

Set a custom page by using setview():

View view=LayoutInflater.from(IntroductoryActivity.this).inflate(R.layout.ipconfig,null);
ip = view.findViewById(R.id.edit_ip);
port = view.findViewById(R.id.edit_port);
setview(view);

Note: This is different from our usual method of taking controls, we must add view. Plus controls

           Otherwise, a null pointer error will be reported

All code examples are attached below (this example is a guide page, which involves the knowledge points of data storage, you can see my other blogs)

 

MainActivity: default code, no function
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Layout file corresponding to MainActivity: also the default code 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

GuideActivity : the main interface of the guide page 

package com.example.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;


public class GuideActivity extends AppCompatActivity {

    private ViewPager vp;
    private List<ImageView> imageViews;
    private int[] imgs = {R.drawable.y0, R.drawable.y1, R.drawable.y2, R.drawable.y3};
    private Button btn, btn2;
    private EditText ed_ip, ed_port;
    private ImageView[] dotViews;
    private GuideAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_guide);
        vp = findViewById(R.id.guide_vp);
        btn = findViewById(R.id.guide_btn);
        btn2 = findViewById(R.id.guide_btn2);

        //初始化图片
        initImgs();
        //初始化底部圆点指示器
        initDots();
        adapter = new GuideAdapter(imageViews);
        vp.setAdapter(adapter);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("isFirst", "1");
                editor.apply();
                Intent intent = new Intent(GuideActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = LayoutInflater.from(GuideActivity.this).inflate(R.layout.ipconfig, null);
                ed_ip = view.findViewById(R.id.ed_ip);
                ed_port = view.findViewById(R.id.ed_port);

                AlertDialog.Builder builder = new AlertDialog.Builder(GuideActivity.this);
                SharedPreferences sp = getSharedPreferences("demo1", MODE_PRIVATE);
                ed_ip.setText(sp.getString("ip", ""));
                ed_port.setText(sp.getString("port", ""));
                builder.setTitle("端口设置")
                        .setView(view)

                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                SharedPreferences.Editor editor = sp.edit();
                                editor.putString("ip", ed_ip.getText().toString());
                                editor.putString("port", ed_port.getText().toString());
                                editor.apply();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(GuideActivity.this, "取消端口设置", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();


            }
        });
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < dotViews.length; i++) {
                    if (position == i) {
                        dotViews[i].setImageResource(R.drawable.guide_selector);
                    } else {
                        dotViews[i].setImageResource(R.drawable.guide_white);
                    }

                    if (position == dotViews.length - 1) {
                        btn.setVisibility(View.VISIBLE);
                        btn2.setVisibility(View.VISIBLE);
                    } else {
                        btn.setVisibility(View.GONE);
                        btn2.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    /**
     * 初始化底部圆点指示器
     */
    private void initDots() {
        LinearLayout layout = findViewById(R.id.guide_ll);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
        params.setMargins(10, 0, 10, 0);
        dotViews = new ImageView[imgs.length];
        for (int i = 0; i < imageViews.size(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(params);
            imageView.setImageResource(R.drawable.guide_white);
            if (i == 0) {
                imageView.setImageResource(R.drawable.guide_selector);
            } else {
                imageView.setImageResource(R.drawable.guide_white);
            }
            dotViews[i] = imageView;
            final int finalI = i;
            dotViews[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    vp.setCurrentItem(finalI);
                }
            });
            layout.addView(imageView);
        }
    }

    /**
     * 初始化图片
     */
    private void initImgs() {
        ViewPager.LayoutParams params = new ViewPager.LayoutParams();
        imageViews = new ArrayList<ImageView>();
        for (int i = 0; i < imgs.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(params);
            imageView.setImageResource(imgs[i]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageViews.add(imageView);
        }
    }


}

activity_guide.xml: guide page layout file 

<?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">


    <androidx.viewpager.widget.ViewPager
        android:id="@+id/guide_vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/guide_ll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="100dp"
        android:orientation="horizontal" />

    <Button
        android:id="@+id/guide_btn"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:layout_above="@id/guide_ll"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:background="#2990E3"
        android:text="开始体验"
        android:textColor="#ffffff"
        android:visibility="invisible" />
    <Button
        android:id="@+id/guide_btn2"
        android:layout_width="100dp"
        android:layout_height="40dp"
      android:layout_alignRight="@id/guide_vp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:background="#2990E3"
        android:text="端口设置"
        android:textColor="#ffffff"
        android:visibility="invisible"/>

</RelativeLayout>

GuideAdapter : guide page adapter 

package com.example.myapplication;



import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public class GuideAdapter extends PagerAdapter {

    private final List<ImageView> imageViews;

    public GuideAdapter(List<ImageView> imageViews) {
        this.imageViews= imageViews;
    }

    /**
     * 获取当前要显示对象的数量
     */
    @Override
    public int getCount() {
        return imageViews.size();
    }

    /**
     * 判断是否用对象生成界面
     */
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view== o;
    }

    /**
     * 从ViewGroup中移除当前对象
     */
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(imageViews.get(position));

    }
    /**
     * 当前要显示的对象
     */
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(imageViews.get(position));
        return imageViews.get(position);
    }

}


ipconfig.xml: ip configuration interface 

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:orientation="vertical">

    <EditText
        android:id="@+id/ed_ip"
        android:layout_width="269dp"
        android:layout_height="83dp"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="68dp"
        android:ems="10"
        android:gravity="center"
        android:hint="请输入IP,例如192.168.1.1"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/ed_port"
        android:layout_width="261dp"
        android:layout_height="86dp"
        android:layout_marginTop="120dp"
        android:layout_marginEnd="72dp"
        android:ems="10"
        android:gravity="center"
        android:hint="请输入端口,例如8080"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 guide_white.xml: white dot not selected

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:height="20dp" android:width="20dp"/>
    <solid android:color="#fff"/>
</shape>

guide_selector.xml : select the blue dot

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:height="20dp" android:width="20dp"/>
    <solid android:color="#0687ED"/>
</shape>

The 4 pictures on the guide page can be added by yourself 

Guess you like

Origin blog.csdn.net/weixin_63987141/article/details/129715660