Android Studio Toolbar With NO Layouts - android

I am extremely new to Android Studio, and as a learning exercise, I am trying to create an application without using any xml files other than manifest.
I want to make an activity, layout, toolbar, and drawer menu completely within Java. I know it is not how things are normally done, and I am likely causing myself a lot of unnecessary stress, but, as I said, this is a learning exercise.
Everything seems to execute, but the toolbar does not display. Also, getSupportActionBar().getHeight() returns zero.
Any help is appreciated!
Thanks,
John
Here is my Activity.java
package com.example.john.myblankapplication;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.Snackbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by John on 7/3/2016.
*/
public class MyActivity extends AppCompatActivity {
private RelativeLayout myRelativeLayout;
private LinearLayout myLinearLayout;
private Toolbar myToolbar;
private TextView myTextView;
private ActionBar myActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the main layout programmatically
createRelativeLayout();
createLinearLayout();
// I have tried it with LinearLayout and RelativeLayout
setContentView(myLinearLayout);
// Create the toolbar layout programmatically
createToolbarLayout();
//myLinearLayout.addView(myToolbar); // that turned the whole screen red
setSupportActionBar(myToolbar);
myActionBar = getSupportActionBar();
myActionBar.setDisplayHomeAsUpEnabled(true); // new test - didn't help
// Create the text programmatically
myLinearLayout.addView(createTextView());
Snackbar.make(myTextView, "ActionBarHeight="+myActionBar.getHeight(),
Snackbar.LENGTH_LONG)
.setAction("Action", null).show(); // displays 0
}
private void createRelativeLayout() {
myRelativeLayout = new RelativeLayout(this);
// Specifies the layout properties
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
myRelativeLayout.setLayoutParams(relativeParams);
}
private void createLinearLayout() {
myLinearLayout = new LinearLayout(this);
// Specifies the layout properties
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
myLinearLayout.setLayoutParams(linearParams);
}
private Toolbar createToolbarLayout() {
myToolbar = new Toolbar(this);
Toolbar.LayoutParams toolBarParams = new Toolbar.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
R.attr.actionBarSize, Gravity.TOP
);
myToolbar.setTitle("My Toolbar");
myToolbar.setLayoutParams(toolBarParams);
myToolbar.setBackgroundColor(Color.RED);
myToolbar.setVisibility(View.VISIBLE);
return myToolbar;
}
private TextView createTextView() {
myTextView = new TextView(this);
// Set initial layout parameters
RelativeLayout.LayoutParams textViewParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
// Set alignment parameters
//textViewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
textViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
myTextView.setText("Here is some text");
myTextView.setLayoutParams(textViewParams);
return myTextView;
}
}

You also need to add toolbar to linear layout.
// Create the toolbar layout programmatically
myLinearLayout.addView(// Create the toolbar layout programmatically
createToolbarLayout(););

I would recommend making the toolbar a custom view and just set the dimensions in the layout screen. You can declare the custom view as a toolbar if you import the toolbar package. Then you can use all the toolbar commands built in to add a title and items.
Hope this helps!

Related

Adjust size and gap between FancyButton placed on LinearLayout

I have placed programmatically generated FancyButtons on LinearLayout. But, the generated buttons are placed too compactly, in other words, there is no separation between two successive buttons. Also, I want the buttons to stretch entire with of the layout. I tried btnWordList.setMinimumWidth(MATCH_PARENT) without any result. Please find the code below.
FlexDict.java
package in.dipanjan.flexdict;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.graphics.Color;
import android.content.Intent;
import android.widget.LinearLayout;
import android.graphics.PixelFormat;
import mehdi.sakout.fancybuttons.FancyButton;
import android.support.v7.app.ActionBarActivity;
public class FlexDict extends ActionBarActivity implements View.OnClickListener {
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int listCount, wordLists = 5;
/* http://stackoverflow.com/questions/19078461/android-null-pointer-exception-findviewbyid */
setContentView(R.layout.activity_flex_dict);
LinearLayout container = (LinearLayout)findViewById(R.id.container);
for(listCount = 1; listCount <= wordLists; listCount++)
{
/* https://github.com/medyo/fancybuttons */
FancyButton btnWordList = new FancyButton(this);
btnWordList.setId(listCount);
btnWordList.setText("WordList " + listCount);
btnWordList.setBackgroundColor(Color.parseColor("#3b5998"));
btnWordList.setFocusBackgroundColor(Color.parseColor("#5474b8"));
btnWordList.setTextSize(20);
btnWordList.setIconResource("\uf04b");
btnWordList.setRadius(10);
btnWordList.setOnClickListener(this);
container.addView(btnWordList);
}
setContentView(container);
}
#Override
public void onClick(View view) {
int wordList = view.getId();
/*
* http://www.java-samples.com/showtutorial.php?tutorialid=1525
* http://stackoverflow.com/questions/7980627/pressing-back-button-did-not-go-back-to-previous-activity-android
*/
Bundle params = new Bundle();
params.putInt("WordList", wordList);
Intent intent = new Intent(this, ShowList.class);
intent.putExtras(params);
startActivity(intent);
}
}
activity_flex_dict.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/radialback">
</LinearLayout>
UI
http://s26.postimg.org/rkb0r4ys9/Fancy_Button.png
You need to setLayoutParams on your View.
i.e. btnWordList.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
You need to set layout params for any view even if instantiated in XML or Programatically.
http://developer.android.com/reference/android/view/View.html#setLayoutParams(android.view.ViewGroup.LayoutParams)
Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.
You need to set a margin between your buttons to make a gab between your buttons. and set your width to match_parent to make the button stretch to the width of the layout
int marginBottom = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
5,
r.getDisplayMetrics()
);
for(listCount = 1; listCount <= wordLists; listCount++)
{
/* https://github.com/medyo/fancybuttons */
FancyButton btnWordList = new FancyButton(this);
btnWordList.setId(listCount);
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 0, 0, marginBottom);
btnWordList.setLayoutParams(params);
btnWordList.setText("WordList " + listCount);
btnWordList.setBackgroundColor(Color.parseColor("#3b5998"));
btnWordList.setFocusBackgroundColor(Color.parseColor("#5474b8"));
btnWordList.setTextSize(20);
btnWordList.setIconResource("\uf04b");
btnWordList.setRadius(10);
btnWordList.setOnClickListener(this);
container.addView(btnWordList);
}
You can use LayoutParam with margin
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
lp.bottumMargin = 2;
// or
lp.setMargins(0,0,0,2);
btnWordList.setLayoutParams(lp);

Android - removing layout programmatically

I have an activity that makes a layout programmatically from a Shared Preference using a for loop. The text views and buttons are enclosed in a linear layout. The user can input as many views as he wants. Now, the button will be a delete button. When pressed, I want to delete the linear layout the button and the other textviews are contained. How do I do this?
HERE IS MY CODE:
package com.dirkjan.myschools;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout subjectLeft, subjectRight;
Button addSubj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
subjectLeft = (LinearLayout) findViewById(R.id.llSubjectLeft);
subjectRight = (LinearLayout) findViewById(R.id.llSubjectRight);
//Load the saved subjects
SharedPreferences getSubjects = getSharedPreferences("SubjectInfo_Prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = getSubjects.edit();
int subjectCount = getSubjects.getInt("count", 0);
if (subjectCount > 0 ){
for (int i = 1; i <= subjectCount; i++){
//Set the linear layout for each subject
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
float scale = getResources().getDisplayMetrics().density;
//SET BOTTOM MARGIN
float margin = 5; //RESIZE MARGIN HERE!
int margs = (int) (margin * scale + 0.5f);
//SET PADDING IN DP
float padding = 5; //RESIZE PADDING HERE!
int pads = (int) (padding * scale +0.5f);
llParams.setMargins(0,0,0,margs);
//SETTING THE LINEARLAYOUT PARAMS
ll.setLayoutParams(llParams);
ll.setPadding(pads, pads, pads, pads);
//SETTING THE BACKGROUND COLOR OF THE LINEAR LAYOUT
String chosenColor = getSubjects.getString("chosenColor" + i, "BLUE");
if (chosenColor.equals("Green")){
ll.setBackgroundResource(R.color.HoloGreen);
}else if (chosenColor.equals("Blue")){
ll.setBackgroundResource(R.color.HoloBlue);
}else if (chosenColor.equals("Gray")){
ll.setBackgroundResource(R.color.HoloGray);
}else if (chosenColor.equals("Orange")){
ll.setBackgroundResource(R.color.HoloOrange);
}else {
ll.setBackgroundResource(R.color.HoloYellow);
}
//ADDING THE LAYOUT TO THE APPROPRIATE CONTAINER (LEFT OR RIGHT)
if (i % 2 == 1){
subjectLeft.addView(ll);
} else {
subjectRight.addView(ll);
}
//SETTING THE SUBJECT NAME TEXTVIEW
TextView SubjectName = new TextView(this);
SubjectName.setText(getSubjects.getString("subjectName" + i, "Error"));
SubjectName.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
SubjectName.setTextSize(22);
SubjectName.setTypeface(Typeface.DEFAULT_BOLD);
//SETTING THE SUBJECT NUMB TEXT VIEW
TextView SubjectNumber = new TextView(this);
SubjectNumber.setText(getSubjects.getString("subjectNumb" + i, "Error"));
SubjectNumber.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
SubjectNumber.setTextSize(16);
//Creating the divider line
ImageView divider = new ImageView(this);
LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2);
divider.setLayoutParams(dividerParams);
divider.setBackgroundResource(R.color.Black);
//Add Views into the Layout
ll.addView(SubjectNumber);
ll.addView(SubjectName);
ll.addView(divider);
}
}
addSubj = (Button) findViewById(R.id.buttonPlusSubject);
addSubj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent toAddSubj = new Intent(MainActivity.this,
AddSubjectActivity.class);
startActivity(toAddSubj);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Please do take note that no id is assigned for each layout. It would help if there is a code to identify the parent of the parent of the button (The button is in a relative layout, which is in a linear layout where the linear layout must be removed by clicking the button.
First find your parent layout using
ll = (LinearLayout) findViewById(R.id.main_linearlayout);
get the child layout using
final LinearLayout child = (LinearLayout) ll.findViewById(count);
now to remove the whole layout you can use removeview() method as below
ll.removeView(child);
to only remove all views from the particular layout(here for eg. child) you can use
child.removeAllViews();
You can call view.setVisiblility(View.GONE) if you want to remove it from the layout, or view.setVisibility(View.INVISIBLE) if you just want to hide it.
You can remove a Child View from a parent by calling removeView(View view), for example like this :
parent.removeView(child);
Supposing that your LinearLayout ID is my_linear_layout, just do this in your onClickListener:
findViewById(R.id.my_linear_layout).setVisibility(View.GONE);
In your XML, be sure to put the ID:
<LinearLayout
android:id="#+id/my_linear_layout"
...>
</LinearLayout>
you can do this like get the id of the currently clicked item
and assigned in root layout
LinearLayout layout = (LinearLayout) v.getParent();
And remove using this code given below:
linearLayout.removeView(layout);

Drawing shapes programmatically for Android

I'm new to the Android SDK so I'm trying to figure this out. I have read the documentation and a text book and they haven't been particularly helpful in this matter.
I'm just trying to draw a simple rectangle in a linear layout on the screen. I can't get the shape to show up, however, when I add text to this layout in the same fashion, the text does show up. What am I missing?
package jorge.jorge.jorge;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ShapesActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ShapeDrawable rect = new ShapeDrawable(new RectShape());
rect.getPaint().setColor(Color.GREEN);
ImageView view1 = new ImageView(this);
view1.setImageDrawable(rect);
LinearLayout frame = (LinearLayout)findViewById(R.id.linear1);
frame.addView(view1);
// TextView tx = new TextView(this);
//
// tx.setText("Hello World");
//
// frame.addView(tx);
}
}
The Shape is usually used for making a background to some View. Its width and height is the same of the view that is using it. Then, if this view has no width and height, It'll have no width and height, too.
Basically, I think that your ImageView has no width and height, then it's invisible.
You can see how to set it programatically here:
Set ImageView width and height programmatically?
But, I recomend you to make the layout in XML's way.

How to define attributes in Activity -class itself without an XML file?

I am creating my own UI component class by extending layout class. Now instead of adding my custom attributes like height , width etc in string xml resources as separate xml, I want to define in Activity class itself. I don't want to add in xml and then refer it from R class in my code. Is there any way to define and access attributes in code itself?
Here is a code sample from Pro Android 4:
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
{
private LinearLayout nameContainer;
private LinearLayout addressContainer;
private LinearLayout parentContainer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
createNameContainer();
createAddressContainer();
createParentContainer();
setContentView(parentContainer);
}
private void createNameContainer()
{
nameContainer = new LinearLayout(this);
nameContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
nameContainer.setOrientation(LinearLayout.HORIZONTAL);
TextView nameLbl = new TextView(this);
nameLbl.setText("Name: ");
TextView nameValue = new TextView(this);
nameValue.setText("John Doe");
nameContainer.addView(nameLbl);
nameContainer.addView(nameValue);
}
private void createAddressContainer()
{
addressContainer = new LinearLayout(this);
addressContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
addressContainer.setOrientation(LinearLayout.VERTICAL);
TextView addrLbl = new TextView(this);
addrLbl.setText("Address:");
TextView addrValue = new TextView(this);
addrValue.setText("911 Hollywood Blvd");
addressContainer.addView(addrLbl);
addressContainer.addView(addrValue);
}
private void createParentContainer()
{
parentContainer = new LinearLayout(this);
parentContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
parentContainer.setOrientation(LinearLayout.VERTICAL);
parentContainer.addView(nameContainer);
parentContainer.addView(addressContainer);
}
}
Also See these for more functionalities:
Layout Params Linear Layout
ViewGroup Layout Params
StackOverflow Setting Layout params

Why does my RelativeLayout background become black when I add a button to it?

I have some code below that creates a RelativeLayout and adds a button to it. It draws fine when created from onCreate(), shows a blue button on a red background.
But when creating a new ReltativeLayout when clicking on the first the new button shows on a black background, so my RelativeLayout doesn't show.
The funny thing is that it works if I comment out the line that adds the button, so somehow the button is impacting the relative layout.
Thanks for any help.
package com.android.mikeviewtester;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class ViewTesterActivity extends Activity {
void createNewView( int bgColor, int btnColor ) {
// create a new relative layout
android.widget.RelativeLayout newView = new android.widget.RelativeLayout( this );
// create a button
Button btn = new Button( this );
// set the background color
btn.setBackgroundColor( btnColor );
// create a layoutParams struct for adding the button to the relative layout view
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( 100, 100 );
// add the button to the relative layout
newView.addView( btn, params );
// set the relative layout background color
newView.setBackgroundColor( bgColor );
// set the ontouch listener for the relativeLayout
newView.setOnTouchListener( (android.view.View.OnTouchListener) mOnTouchListener );
// create the layout to fill the activity
RelativeLayout.LayoutParams viewParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
// set the relative layout as the view
setContentView( newView, viewParams );
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
// create and set the initial view
createNewView( Color.RED, Color.BLUE );
}
// ios - (void)buttonWasPressed:(id)whichButton {
private android.view.View.OnTouchListener mOnTouchListener = new android.view.View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if ( v != null )
v.onTouchEvent( event );
if ( event.getAction() == MotionEvent.ACTION_UP ) {
// create and set a new view
createNewView( Color.GREEN, Color.MAGENTA );
}
return true;
}
};
}
Make a change in your code, i.e. add v.setVisibility(View.GONE); before calling createNewView(Color.GREEN, Color.MAGENTA);

Categories

Resources