5 Aug 2017

Android Java User Interface Layout Parameters of views child parent gravity

In a mobile android app, we all want to scroll things. So our root element ,or outermost screen visible to user will be a scroll-supporting type i.e., ScrollView 
(This is a kind of a container which can contain small small elements , base class is ViewGroup)

Next we need horizontal buttons for users to click. As its linear in shape, we call int as LinearLayout.
(This is also a kind of container which can contain small small elements, base class is ViewGroup).
We need this Linear Layout to be laid horizontally. Its children will be "Button" views. 
("Button" class has base class of "view".) . Also we want them placed central in the horizontal bar.

Now we need another Linear Layout. This one should be laid vertically. So all text-articles can be vertically stacked here for users to see. These children text are called TextView (Base class is "view").

ScrollView sv;             //declares a grandParent scrollview ViewGroup
LinearLayout ll;           //declares a Parent LinearLayout ViewGroup
TextView tv;               
EditText et;                 //This is for getting input like user filling a form
Button btn;

sv=new ScrollView(this);     //defines a grandParent scrollview ViewGroup
ll=new LinearLayout(this);  //defines a Parent LinearLayout ViewGroup
btn=new Button(this);          //gives a child Button View

sv.add(ll);   //attaches parent to grandparent
ll.add(btn);  //attaches child to parent
ll.setGravity(Gravity.CENTER); //ensures all buttons are centralized in the horizontal bar of Buttons
ll.setPadding(2,2,2,2);  // gives a padding to its contents.

//first we calculate height and width of mobile screen as below:- 
Display d = getWindowManager().getDefaultDisplay();maxH = d.getHeight();maxW=d.getWidth();


lp=new LinearLayout.LayoutParams(maxW,maxH); //lp is layout parameter to be set to scrollview
sv.setLayoutParams(lp);                                              // maxW=maximum Width of screen

//define properties of a button
btn.setTextSize(10);                                             //Put small size font only 10 pixel for button-text
btn.setText("SUBMIT BUTTON");                    //Put this text on Button-Shape
btn.setOnClickListener(this);                              // let the present class-object be searched for a                                                                                          // method/function called "onClick" & run it
btn.setTextColor(Color.CYAN);                         // set text color inside button
btn.setBackgroundResource(R.drawable.btn);   //attach image "btn.png" in res/drawable folder

//define properties of textview elements,  shortform=tv
tv.setBackgroundColor(Color.WHITE);
tv.setPadding(2,2,2,2);

//below we want textview to have a width equal to his parent, but height adjusted as per amount of //text in the text-article displayed to user. We define such a "lp" below:-
lp = new LinearLayout.LayoutParams ( ViewGroup.LayoutParams.MATCH_PARENT , ViewGroup.LayoutParams.WRAP_CONTENT);

 lp.setMargins(2,2,2,2);                //set margin (left,top,bottom,right) of 'tv' through its 'lp', not directly
tv.setLayoutParams(lp);               //set the lp layout-parameter to the tv text-view
tv.setPadding(2,2,2,2);                 //set padding of contents for tv directly , no need to come via 'lp'
tv.setTextColor(Color.GRAY);    //set color of its text
tv.setText("An Article on Democracy.");    //set the text to be displayed in this textview                       
ll.addView(tv);                              // add the child 'tv' to its parent 'll' i.e. linear layout, a ViewGroup
tv.setBackgroundColor(Color.WHITE) //set background color for text-article

Next some message to display to user, we can use toast command.
It makes a bread-toast for the user to eat & digest...ha ha ha..!
Meaning that displays a message without disturbing the User-interface layout and message will vanish in a flash.
// LENGTH_SHORT means show the message for short time

Toast.makeText(this, "Hi dude!", Toast.LENGTH_SHORT) .show();

Now, when you need to interact with user to get user's input ...then what to do?
We call it a dialogue between our Android Robot Mobile & the User playing the Robot Android.

Dialogue-box will have two buttons 'OK' & 'CANCEL' 
OK means your typed input is POSITIVE & correct. So Robot will act accordingly.
CANCEL means you dont want to go ahead with all this & you are NEGATIVE about it.

What we will do is we create an 'AlertDialog' by asking its inner class called 'Builder' to 'create' it
or define it or instantiate an object of its class type. 
For that we dictate & detail various properties/attributes of how we want the dialog to its builder, the constructor.


So we code it as under:-

AlertDialog.Builder adb;                                            // declare  "Alert-dialog-builder"  object
adb=new AlertDialog.Builder( this );                                  
et=new EditText(this);                                                //declare editable text-box for taking user input
adb.setTitle("Tell me what is the value of this item?");      //tell user what its about...
adb.setMessage("Input value: ");                                        //give more description....
adb.setView(et);                                                       //attach the editable textbox to dialog

//Now below is setting of actions on clicking ok & cancel buttons

adb.setPositiveButton(    "OK",new DialogInterface.OnClickListener()
      {
@Override
public void onClick(DialogInterface d,int w)
{
String userInput = et.getText().toString();
                                                                        //Code & Functions/Methods to be called next.

}
      }
    );
adb.setNegativeButton(    "CANCEL",new DialogInterface.OnClickListener()
      {
@Override
public void onClick(DialogInterface d,int w)
{
d.cancel();
 
}
      }
    );


AlertDialog ad=adb.create();          //Let the DialogBuilder now create the actual Dialog
ad.show();                                       //Let the Robot Android Mobile show this on its screen


So thats it. Below I submit full code of a working app called 'My Memo' which illustrates above concepts.

package com.ani;

import android.app.*;import android.os.*;import android.content.*;import android.app.DatePickerDialog.*;import android.app.TimePickerDialog.*;
import android.view.View.*;import android.view.*;import android.widget.*;import android.database.sqlite.*;import android.database.*;
import java.text.*;import java.util.*;import android.widget.*;import android.graphics.Color;

public class HomePage extends Activity implements View.OnClickListener

{
SQLiteDatabase db;Context ctx;String DB="MyDiary.db",TBL="MyMemo";
TextView tv;EditText et;LinearLayout ll1,ll2,ll3;ScrollView sv;Button btn;
LinearLayout.LayoutParams lp;
ArrayList<String> memo=new ArrayList<String>();
static int total=0,maxH=0,maxW=0;;
static String mykey,myvalue;
@Override
public void onClick(View v)
{
Button b=(Button)v;String str=b.getText().toString();

if(str=="ADD ITEM")
{
AlertDialog.Builder adb;
adb=new AlertDialog.Builder( this );
et=new EditText(this);
adb.setTitle("Input your item");
adb.setMessage("Press OK to save.");
adb.setView(et);
adb.setPositiveButton(    "OK",new DialogInterface.OnClickListener()
      {
@Override
public void onClick(DialogInterface d,int w)
{
mykey="'"+et.getText().toString()+"'";
et.setText(null);
}
      }
    );
adb.setNegativeButton(    "CANCEL",new DialogInterface.OnClickListener()
      {
@Override
public void onClick(DialogInterface d,int w)
{
d.cancel();
}
      }
    );
AlertDialog ad = adb.create();
ad.show();  
}
if(str=="ADD VALUE")
{
AlertDialog.Builder adb;
adb=new AlertDialog.Builder( this );
et=new EditText(this);
adb.setTitle("Tell me what is the value of this item?");
adb.setMessage("Input value: ");
adb.setView(et);
adb.setPositiveButton(    "OK",new DialogInterface.OnClickListener()
      {
@Override
public void onClick(DialogInterface d,int w)
{
myvalue="'"+et.getText().toString()+"'";
et.setText(null);putData();
}
      }
    );
adb.setNegativeButton(    "CANCEL",new DialogInterface.OnClickListener()
      {
@Override
public void onClick(DialogInterface d,int w)
{
d.cancel();
}
      }
    );
AlertDialog ad = adb.create();
ad.show();  
}

if(str=="DELETE ALL"){killTable();}
if(str=="EXIT")      {HomePage.this.finish();}
}

@Override
public void onCreate(Bundle b)
        {
super.onCreate(b);ctx=getApplicationContext();

Display d = getWindowManager().getDefaultDisplay();maxH = d.getHeight();maxW=d.getWidth();

sv=new ScrollView(this);lp=new LinearLayout.LayoutParams(maxW,maxH);sv.setLayoutParams(lp);

lp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
ll1=new LinearLayout(this);ll1.setOrientation(LinearLayout.VERTICAL);ll1.setLayoutParams(lp);

ll2=new LinearLayout(this);ll2.setBackgroundColor(Color.WHITE);
lp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
ll2.setLayoutParams(lp);ll2.setGravity(Gravity.CENTER);

ll3=new LinearLayout(this);ll3.setOrientation(LinearLayout.VERTICAL);
lp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(maxH-100));
lp.setMargins(2,2,2,2);
ll3.setLayoutParams(lp);ll3.setPadding(2,2,2,2);
ll3.setBackgroundColor(Color.LTGRAY);



btn=new Button(this);btn.setTextSize(10);btn.setText("ADD ITEM");btn.setOnClickListener(this);ll2.addView(btn);
btn.setTextColor(Color.CYAN);
btn.setBackgroundResource(R.drawable.btn);
btn=new Button(this);btn.setTextSize(10);btn.setText("ADD VALUE");btn.setOnClickListener(this);ll2.addView(btn);
btn.setTextColor(Color.CYAN);
btn.setBackgroundResource(R.drawable.btn);
btn=new Button(this);btn.setTextSize(10);btn.setText("DELETE ALL");btn.setOnClickListener(this);ll2.addView(btn);
btn.setTextColor(Color.CYAN);
btn.setBackgroundResource(R.drawable.btn);
btn=new Button(this);btn.setTextSize(10);btn.setText("EXIT");btn.setOnClickListener(this);ll2.addView(btn);
btn.setTextColor(Color.CYAN);
btn.setBackgroundResource(R.drawable.btn);
ll1.addView(ll2);ll1.addView(ll3);sv.addView(ll1);

getTable();getData();showData();
setContentView(sv);
}

public void getTable()
{
db=openOrCreateDatabase(DB,Context.MODE_PRIVATE,null);
db.execSQL(  "CREATE TABLE IF NOT EXISTS " + TBL +" (ID INTEGER PRIMARY KEY ,MYKEY TEXT,MYVALUE TEXT);"  );
db.close();
}

public void killTable()
{
db=openOrCreateDatabase(DB,Context.MODE_PRIVATE,null);
db.execSQL(  "DROP TABLE " + TBL );
db.close();

ll3.removeAllViews();
getTable();getData();
}
public void putData()
{
db=openOrCreateDatabase(DB,Context.MODE_PRIVATE,null);
db.execSQL(  "INSERT INTO " + TBL +" (MYKEY,MYVALUE) VALUES (" + mykey +"," + myvalue + ")"  );
db.close();

ll3.removeAllViews();
getData();showData();
}
public void getData()
{
db=openOrCreateDatabase(DB,Context.MODE_PRIVATE,null);
String qry="SELECT * FROM "+TBL;Cursor allrows=db.rawQuery(qry,null);String msg;total=0;memo.clear();

if(allrows.moveToFirst())
 {do  {String key=allrows.getString(1),value=allrows.getString(2);msg= key + " : " + value;memo.add(msg);total+=1; }while(allrows.moveToNext());}
else   {Toast.makeText(ctx,"No Records as yet...",Toast.LENGTH_SHORT).show();}

db.close();
}
public void showData()
{    
ll3.removeAllViews();
for(int i=0;i<total;i++){
String str=memo.get(i);tv=new TextView(this);tv.setBackgroundColor(Color.WHITE);tv.setPadding(2,2,2,2);
lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(2,2,2,2);tv.setLayoutParams(lp);tv.setTextColor(Color.GRAY);tv.setText(str);ll3.addView(tv);
}
}



No comments:

Post a Comment