Ways you can handle button click in Android Studio Project


In a Android project you need to handle button click for completion of data processing, a double click maiy not enough create automatic Event handler as in Microsoft visual Studio projects. You have to do it in Java style.

You have two options, one is to handle click in Oncreate method or simply add new Method and attach it to the Onclick property [Layout]

 The first Method

Most of the coders love this method and it can save time as well. The code reside in OnCreate method

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);    
    textView = (TextView) findViewById(R.id.text1);
    Button button2=findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setText("I clciked button2 - Oncreate");
        }
    });
     
}
The Second Method

This will require Create a Public Method with View as argument. Keep in mind that all controls should be declared just below the beggining of the class and assing controls at OnCreate method

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         
        textView = (TextView) findViewById(R.id.text1);
   
    }
The hadler method

Place the code after the OnCreate

public void ButtonClick1(View view) {
    textView.setText("I Clicked Button1");
}

Go to the layout and  find the onclick property of the button ther you will see the ButtonClick1 choose the right one

or you can configure it in the XML file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="ButtonClick1"
            android:text="OnClick 1"
            tools:layout_editor_absoluteX="30dp"
            tools:layout_editor_absoluteY="58dp" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Onclick 2"
            tools:layout_editor_absoluteX="128dp"
            tools:layout_editor_absoluteY="58dp" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Watch the tutorial video on Youtube

I think this was enough for begiiners, leave comments and questions below

 

 

 

 

How to create ListView with CustomAdapter in Android Studio


Default ListView layout let you display single piece of information while a customised list view layout let you design your own components. All you need is a separate layout file

1

and a adaptor which extends BaseAdpter or ArrayAdapter. Continue reading How to create ListView with CustomAdapter in Android Studio

Create and read simple JSON_STRING in Android Studio


JSON_STRING strings are similar to Dictionary and List in Python, they can be searched quickly. JSON_STRING can be used to store data for your application.

This post will teach you how to create and read JSON_STRING objects in Android Studio/Eclipse Android apps.

  1. Go ahead and create a simple activity app
  2. Switch to Android View
  3. Create simple JSON_STRING as follows in the MainActivity.Java class
    String JSON_STRING = "{\"DSLR\":{\"Model\":\"Sony Alpha 58\",\"Sensor\":APC}}";

    [Drop the above code at the beginning of the OnCreate method]

  4. Open main_activity.xml [can find under res/layout]
  5. Drag and Drop two TextView control to the Form.
  6. Change the name of the controls in the content_main.xml file as ‘model’ and ‘sensor’ respectively
  7. Now create variable to read a string from JSON and assign the values to controls
String model, sensor;
TextView Model, Sensor;
Model = (TextView) findViewById(R.id.model);
Sensor = (TextView) findViewById(R.id.sensor);
try {
 // get JSONObject from JSON file
 JSONObject obj = new JSONObject(JSON_STRING);
 // fetch JSONObject named employee
 JSONObject dslr = obj.getJSONObject("DSLR");
 // get employee name and salary
 model = dslr.getString("Model");
 sensor = dslr.getString("Sensor");
 // set employee name and salary in TextView's
 Model.setText("Model: "+model);
 Sensor.setText("Sensor: "+sensor);

} catch (JSONException e) {
 e.printStackTrace();
}

Alt+Enter to auto import libraries. Here the JSONObject will help you to fetch ‘DSLR’ String. In our example, we have one only one JSON string so that used two Text views only.

Remember JSON strings are case sensitive.

You can download the source code from GitHub

DISPLAY DIFFERENT LAYOUTS USING FRAGMENT IN A ANDROID STUDIO APP


Android Studio makes App development so easy with supported libraries and classes. Today we are discussing how to show different layout within the main fragment. ( A layout is GUI Windows in Android Studio, where we can place controls and widgets)

How ?

Basically, this can be done by placing a frame layout inside the main fragment layout and place the different layouts.

Create the Drawer Activity App

Android Studio Version:  1.3

Android Version: 22

Begin a New Android Project with Navigation Drawer Activity. Go to Layout folder of the project and access  fragment_main.xml  and add a FrameLayout at the end of the Relative Layout tag, replace the TextView, if exist.

<FrameLayout
    android:id="@+id/FrameContainer"    android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>

Note that we assigned an id for the FrameLayout, which can be accessible using the id. You can also customize the Drawer menu by changing the string.xml resource file.

Now we need two additional resources.

  1. An addition Layout
  2. Java Class representing Additional Layout.

Creating a Frame Layout

In Android a Window has two sides, one has GUI and design and a program part/machine part.

Let create our first FrameLayout XML file By Right click the Layout folder – New – Layout Resource File and enter following Details

Name:dashboard_fragment

Root Element : FrameLayout

Click OK and Drag Large Text Files and add “This is my Dashboard” as Text, in order to identify. We also need the second part, a class to represent the Layout.

Creating Class

A Java Class is behind the wheel for every Layout, it should extend the fragment class.

Right click your Main_Activity -New – Java Class with Name DashboardFragment and add the following overridden OnCreateView method.

public class DashboardFragment extends android.support.v4.app.Fragment {
    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) { View rootview=inflater.inflate(R.layout.
dashboard_fragment_main,container,false); return rootview;    }
}

The Navigation Fragment event

We can fill the  MainFragment’s FrameLayout with the help of fragment manager, just go to the NavigationDrawerFragment.Java  and find the private void selectItem(int position) method, at bottom of the line add the following code.

android.support.v4.app.FragmentManager frg=getFragmentManager();if (position==0){
    frg.beginTransaction().replace(R.id.FrameContainer, new DashboardFragment()).commit();

In the above code, we just replace the content of FrameContainer with new FrameLayout. You can add as many as the layout in the same manner. Here position carries menu item id.

Let’s Run the project

One Layout Class and many fragment layouts in Android Studio


Fragment programming seems to be smart steps towards making worthy applications in Android Studio. In my last experiment, I tried to develop fragments in my app, but I realized that each fragment layout is represented by a Java class which handles the activities. 2017-02-26_001655

How can I use same Java class for different layouts? The first option created an argument constructor for the Java class, but the Fragment sibling Java class doesn’t support thing like that, instead, Android Studio supplies SetArguments and getArguments methods for the purpose.

I have group Main fragment layout carries many buttons for various functions like create,  list, Report fragments respectively. I want to use same Java Class for every fragment including the maingroupFragment.

2017-06-22_084924

The Drawer app code

private void selectItem(int position) {

    mCurrentSelectedPosition = position;
    if (mDrawerListView != null) {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
    android.support.v4.app.FragmentManager frg=getFragmentManager();
    switch (position){
        case 0:
            frg.beginTransaction().replace(R.id.FrameContainer, new DashboardFragment()).commit();
            break;
        case 1:
            frg.beginTransaction().replace(R.id.FrameContainer, new LedgerFragment()).commit();
            break;
        case 2:
            frg.beginTransaction().replace(R.id.FrameContainer, new PaymentFragment()).commit();
            break;
        case 3:
            frg.beginTransaction().replace(R.id.FrameContainer, new ReceiptFragment()).commit();
            break;
        case 4:
            frg.beginTransaction().replace(R.id.FrameContainer, new ReportFragment()).commit();
            break;
        case 5:
            Bundle b=new Bundle();
            b.putInt("GroupIndex", R.layout.groupmain_fragment);
            GroupFragment g=new GroupFragment();
            g.setArguments(b);
            frg.beginTransaction().replace(R.id.FrameContainer,g).commit();
            break;
    }
}

The Fragment class

package com.example.developerm.myapplication;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
* Created by developerM on 14-Jun-2017.
*/
public class GroupFragment extends Fragment {



@Override
public void setArguments(Bundle args) {
super.setArguments(args);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View rootview=inflater.inflate(R.layout.group_registration,container,false);
View rootview=null;
if(getArguments().getInt("GroupIndex")==R.layout.groupmain_fragment){
rootview = inflater.inflate(getArguments().getInt("GroupIndex", 0), container, false);
}
else if(getArguments().getInt("GroupNew")==R.layout.group_registration){

rootview = inflater.inflate(getArguments().getInt("GroupNew", 1), container, false);
}
else if(getArguments().getInt("GroupManage")==R.layout.managegroupsfragment)
{
rootview = inflater.inflate(getArguments().getInt("GroupManage", 2), container, false);
}
else if(getArguments().getInt("GroupAcReports")==R.layout.acreportgroupfragment)
{
rootview = inflater.inflate(getArguments().getInt("GroupAcReports", 3), container, false);
}
else if(getArguments().getInt("GroupList")==R.layout.grouplistfragment)
{
rootview = inflater.inflate(getArguments().getInt("GroupList", 4), container, false);
}

Bundle b=new Bundle();
Button bt;
if(getArguments().getInt("GroupIndex")==R.layout.groupmain_fragment){
bt=(Button) rootview.findViewById(R.id.btn_newGroup);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle b=new Bundle();
b.putInt("GroupNew", R.layout.group_registration);
GroupFragment g=new GroupFragment();
g.setArguments(b);
android.support.v4.app.FragmentManager frg=getFragmentManager();
frg.beginTransaction().replace(R.id.FrameContainer, g).commit();
}
});
bt=(Button) rootview.findViewById(R.id.btn_findEdit);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle b=new Bundle();
b.putInt("GroupManage", R.layout.managegroupsfragment);
GroupFragment g=new GroupFragment();
g.setArguments(b);
android.support.v4.app.FragmentManager frg=getFragmentManager();
frg.beginTransaction().replace(R.id.FrameContainer, g).commit();
}
});
bt=(Button) rootview.findViewById(R.id.btn_acReports);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle b=new Bundle();
b.putInt("GroupAcReports", R.layout.acreportgroupfragment);
GroupFragment g=new GroupFragment();
g.setArguments(b);
android.support.v4.app.FragmentManager frg=getFragmentManager();
frg.beginTransaction().replace(R.id.FrameContainer, g).commit();
}
});
bt=(Button) rootview.findViewById(R.id.btn_groupList);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle b=new Bundle();
b.putInt("GroupList", R.layout.grouplistfragment);
GroupFragment g=new GroupFragment();
g.setArguments(b);
android.support.v4.app.FragmentManager frg=getFragmentManager();
frg.beginTransaction().replace(R.id.FrameContainer, g).commit();
}
});


}

return rootview;
}
}

The above codes will be explained what you have to do. Use the Argument and getArgument in place.

Expect comments and suggestions