Android基础

  1. 闪屏界面

  1. 、关键代码

private Context context;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //取消状态栏
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_splash);
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(new Intent(SplashActivity.this,LoginActivity.class));
        }
    },3000);

 

  1. 、修改AndroidManifest.xml代码

android:theme="@style/Theme.AppCompat.Light.NoActionBar"

 

  1. 登录界面

  1. 、ActionBar设置

//ActionBar的设置
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.mipmap.ic_launcher_round);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setTitle("智慧农业");

  1. 、记住密码

sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean remember = sp.getBoolean("remember_password",false);
if(remember)
{
     EdtUsername.setText(sp.getString("username",""));
     EdtPassword.setText(sp.getString("password",""));
     CbRememberPassword.setChecked(true);
}

 

String Username = edtusername.getText().toString();
String Password = edtpassword.getText().toString();
list = databaseQuery.queryLoginInfo();
for(int i = 0;i<list.size();i++)
{
    if(list.get(i).getUsername().equals(Username)&&list.get(i).getPassword().equals(Password))
    {
        flag = true;
    }
}
if(flag == true)
{
    editor = sp.edit();
    if(cbrempassword.isChecked())
    {

        editor.putString("username",Username);
        editor.putString("password",Password);
        editor.putBoolean("remember_password",true);
        startActivity(new Intent(LoginActivity.this,MainActivity.class));
    }
    else
    {
        startActivity(new Intent(LoginActivity.this,MainActivity.class));
        editor.clear();
    }
    editor.apply();
}
else
{
    Toast.makeText(LoginActivity.this,"用户名不存在,或密码错误!",Toast.LENGTH_SHORT).show();
}

 

(3)、自动登录

boolean auto = sp.getBoolean("auto_login",false);
if(remember)
{
     edtusername.setText(sp.getString("username",""));
     edtpassword.setText(sp.getString("password",""));
     cbrempassword.setChecked(true);
     if(auto)
     {
         cbautologin.setChecked(true);
        startActivity(new Intent(LoginActivity.this,MainActivity.class));
     }
}
cbautologin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
     @Override
     public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked)

{
        if(cbautologin.isChecked())
        {
            editor = sp.edit();
            editor.putBoolean("auto_login",true);
            editor.commit();
        }
        else
        {
            editor = sp.edit();
            editor.putBoolean("auto_login",false);
            editor.commit();
        }
    }
});

(4)、显示密码

cbshowpassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
     @Override
     public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked)

{
        if(cbshowpassword.isChecked())
        {             edtpassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
        else
        {          edtpassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }
});

 

  1. 注册界面

private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private DatabaseQuery databaseQuery;
private Context context;
private List list = new ArrayList<>();
private boolean flag;

 

 

context = this;
openHelper = new LoginDB(context);
db = openHelper.getWritableDatabase();
databaseQuery = new DatabaseQuery(db);
list = databaseQuery.queryLoginInfo();
edtRusername = findViewById(R.id.edt_Rusername);
edtRpassword = findViewById(R.id.edt_Rpassword);
btnRegister = findViewById(R.id.btn_Rregister);
btnRegister.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String username = edtRusername.getText().toString();
        String password = edtRpassword.getText().toString();
        for(int i = 0;i<list.size();i++)
        {
            if (list.get(i).getUsername().equals(username))
            {
                flag = true;
            }
        }
        if(flag == true)
        {
            Toast.makeText(RegisterActivity.this,"用户名已存在!",Toast.LENGTH_SHORT).show();
        }
        else
        {
            db.execSQL("insert into login(username,password)values('"+username+"','"+password+"')");
            Toast.makeText(RegisterActivity.this,"注册成功!",Toast.LENGTH_SHORT).show();
            startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
        }
    }
});

 

  1. 主界面

  1. 、侧边栏

 

  1. 、底部导航栏

FragmentTabHost

布局

<FrameLayout
     android:id="@+id/realtabcontent"
     android:layout_width="match_parent"
     android:layout_height="0dip"
     android:background="#00ff00"
     android:layout_weight="1"/>
<android.support.v4.app.FragmentTabHost
     android:id="@+id/tabhost"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="#dddeee">
     <FrameLayout
         android:id="@+id/tabcontent"
         android:layout_width="0dp"
         android:layout_height="0dp"
         android:layout_weight="0"/>

android.support.v4.app.FragmentTabHost>

 

<ImageView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:focusable="false"
     android:padding="3dp"/>
<TextView
     android:id="@+id/textView"
     android:layout_width="wrap_content"
     android:layout_height="30dp"
     android:text="首页"
     android:gravity="center_vertical"
     android:textSize="10dp"
     android:textColor="#000000"/>

 

MainActivity中关键代码

 

private FragmentTabHost mTabHost;
//定义一个布局
private LayoutInflater layoutInflater;
//定义数组来存放Fragment界面
private Class fragmentArray[] = {FragmentPage1.class,FragmentPage2.class,FragmentPage3.class,FragmentPage4.class,FragmentPage5.class};
//Tab选项卡的文字
private String mTextviewArray[] = {"首页","消息","好友","广场","更多"};
private Context context;
@Override


protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     context = this;
     initView();
}

private void initView() {
     //实例化布局对象
     layoutInflater = layoutInflater.from(context);
     //实例化TabHost对象,得到TabHost,标签页容器
     mTabHost = findViewById(R.id.tabhost);
     //给mtabHos设置父容器。设置标签页对应的内容
     mTabHost.setup(context,getSupportFragmentManager(),R.id.realtabcontent);
     //得到fragment的个数
     int count = fragmentArray.length;
     for(int i = 0;i
     {
         //为Tabhost中的分页tabSpec(首页、消息、 好友、 广场、 更多)设置对应的分页按钮对象。
          TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
         //将Tabhost中的分页tabSpec和对应的Fragment界面对应起来
         mTabHost.addTab(tabSpec, fragmentArray[i], null);
     }
     }
//给Tab按钮设置图标和文字
private View getTabItemView(int index) {
     View view = layoutInflater.inflate(R.layout.tab_item_view,null);
     TextView textView = view.findViewById(R.id.textView);
     textView.setText(mTextviewArray[index]);
     return view;
}

fragment中代码

public class FragmentPage1 extends Fragment implements View.OnClickListener{
    private TextView textView1;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_1,null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        textView1 = getActivity().findViewById(R.id.textView1);
        textView1.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(getActivity(),"nihao",Toast.LENGTH_SHORT).show();
    }
}

 

BottomNavigation

<FrameLayout
     android:id="@+id/content"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_weight="1">
     <LinearLayout
         android:id="@+id/linearLayout"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="horizontal">
     LinearLayout>

FrameLayout>
<android.support.design.widget.BottomNavigationView
     android:id="@+id/navigation"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginEnd="0dp"
     android:layout_marginStart="0dp"
     android:background="?android:attr/windowBackground"
     app:layout_constraintBottom_toBottomOf="parent"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:menu="@menu/navigation" />

MainActivity关键代码

private LinearLayout linearLayout;
private View View1,View2,View3;
private FrameLayout frameLayout;

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
         = new BottomNavigationView.OnNavigationItemSelectedListener() {

     @Override
     public boolean onNavigationItemSelected(@NonNull MenuItem item) {
         linearLayout.removeAllViews();
        switch (item.getItemId()) {
            case R.id.navigation_home:
                linearLayout.removeAllViews();
                linearLayout.addView(View1);
                return true;
            case R.id.navigation_dashboard:
                linearLayout.removeAllViews();
                linearLayout.addView(View2);
                return true;
            case R.id.navigation_notifications:
                linearLayout.removeAllViews();
                linearLayout.addView(View3);
                return true;
        }
        return false;
    }
};

 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bottom);
    linearLayout = findViewById(R.id.linearLayout);
    View1 = getLayoutInflater().inflate(R.layout.view1,null);
    View2 = getLayoutInflater().inflate(R.layout.view2,null);
    View3 = getLayoutInflater().inflate(R.layout.view3,null);
    linearLayout.addView(View1);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}

  1. 数据库的增、删、该、查(SqliteDataBase)

(1)创建数据库、

public class LoginDB extends SQLiteOpenHelper {
    public LoginDB(Context context) {
        super(context, "login.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table login(onepassword,twopassword)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

  1. 、增

Insert into 表名(属性名,属性名)values(‘ ”+值+” ’,’ “+值+” ’);

  1. 、删

Delete from 表名 where 属性名 = 值;

  1. 、改

Update 表名 set 要更改的属性名 = 要更改的值 where 属性名 = 值;

  1. 、查

   Select * from 表名;

查询数据库的方法

public class LoginDao {
    private SQLiteDatabase db;

    public LoginDao(SQLiteDatabase db) {
        this.db = db;
    }
    public List QueryInfo()
    {
        List list = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from login",null);
        while (cursor.moveToNext())
        {
            LoginEntity loginEntity = new LoginEntity();
            loginEntity.setOnePassword(cursor.getString(0));
            loginEntity.setTwoPassword(cursor.getString(1));
            list.add(loginEntity);
        }
        return list;
    }
}

  1. OkHttp
  1. 、get

Request request = new Request.Builder()
        .url("http:172.11.59.41:8083//transportservice/action/GetLightIntensity")
        .build();
/*.post(body)*/
OkHttpClient client = new OkHttpClient();
 Response response = client.newCall(request).execute();
final String result = response.body().string();

  1. 、post

JSONObject json = new JSONObject();
json.put("ControlMode",ControlMode);
MediaType JSON = MediaType.parse("application/json;charset=utf-8");
RequestBody body = RequestBody.create(JSON, String.valueOf(json));
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://172.11.59.41:8083//transportservice/action/SetRoadLightControlMode")
        .post(body)
        .build();
Response response = client.newCall(request).execute();
String result = response.body().string();

  1. android中的小细节

防误触:

private Hanlde handle = new Handle();

private long startTime = 0;

private Content content;

public void onBackPressed()

{

long currentTime = System.currentTimeMills();

If(currentTime -startTime >= 3000)

{

Toast.makeText(RegisterActivity.this,"再按一次退出",Toast.LENGTH_SHORT).show();

startTime = currentTime;

}

else

{

finish();

}

}

你可能感兴趣的:(Android基础)