Mimick whatsapp messages layout in android - android

I'm doing trying to recreate whatsapp's layout using android and this is what i have so far
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/message_pane"
android:layout_height="wrap_content"
android:minHeight="300dp"
android:layout_width="match_parent"
android:foregroundGravity="fill">
</FrameLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:id="#+id/linearLayout">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/edit_text"
android:id="#+id/edit_text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send_text"
android:onClick="sendMessage"/>
</LinearLayout>
</RelativeLayout>
And this is what my java file looks like
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void sendMessage(View view) {
EditText message = (EditText) findViewById(R.id.edit_text);
TextView text = new TextView(this);
text.setText(message.getText());
FrameLayout msgs = (FrameLayout) findViewById(R.id.message_pane);
msgs.addView(text);
}
}
When i click on send, the message does appear on the FrameLayout, but the next one's all go to the same location.
I would like to know how to make them go below previous messages and if there are any better layouts i can use to implement Whatsapp's layout.
Thanks.

Haha, got it working at last, i was able to use uiautomatorviewer (suggested by CommonsWare) to view their structure.
It turns out i has to implement a custom adapter in addition to a Listview to get it working, here's the code in case anyone is interested.
MessageAdapter.java
package com.example.mestchat.Adapter;
/**
* Created by elimence on 6/1/13.
*/
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.mestchat.MessageData;
import com.example.mestchat.R;
public class MessageAdapter extends ArrayAdapter {
private final Activity activity;
private final List messages;
public MessageAdapter(Activity activity, List objs) {
super(activity, R.layout.message_list , objs);
this.activity = activity;
this.messages = objs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
MessageView msgView = null;
if(rowView == null)
{
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.message_list, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
msgView = new MessageView();
msgView.msg = (TextView) rowView.findViewById(R.id.message_text);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(msgView);
} else {
msgView = (MessageView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
MessageData currentMsg = (MessageData)messages.get(position);
msgView.msg.setText(currentMsg.getMessage());
return rowView;
}
protected static class MessageView {
protected TextView msg;
}
}
MessageData.java
package com.example.mestchat;
/**
* Created by elimence on 6/1/13.
*/
public class MessageData {
private String message;
public MessageData(String message) {
this.message = message;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
package com.example.mestchat;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import com.example.mestchat.Adapter.MessageAdapter;
import com.example.mestchat.REST.RestWebServices;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity {
MessageAdapter adapter;
List msgs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgs = new ArrayList();
adapter = new MessageAdapter(this, msgs);
setListAdapter(adapter);
}
#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;
}
public void sendMessage(View view) {
EditText message = (EditText) findViewById(R.id.enter_message);
String mText = message.getText().toString();
msgs.add(new MessageData(mText));
adapter.notifyDataSetChanged();
message.setText("");
}
}
message_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:gravity="fill_horizontal"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:textColor="#color/black"
android:background="#color/white"
android:id="#+id/message_text" />
</RelativeLayout>
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<!--<FrameLayout-->
<!--android:background="#color/header_color"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="0dp"-->
<!--android:layout_weight="1">-->
<!--</FrameLayout>-->
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="0dp"
android:layout_weight="10">
<FrameLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="11">
<ListView
android:id="#android:id/list"
android:background="#drawable/background"
android:drawSelectorOnTop="false"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:footerDividersEnabled="true">
</ListView>
</FrameLayout>
<FrameLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#color/send_box_color"
android:id="#+id/linearLayout">
<EditText
android:id="#+id/enter_message"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="#string/edit_text" />
<Button
android:id="#+id/send_button"
android:layout_width="45dp"
android:layout_height="30dp"
android:background="#drawable/send_btn"
android:onClick="sendMessage"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</LinearLayout>

Related

How to fix OnItemClickListener on ListView

This is java class MainActivity.java
package com.example.mhn.intercoapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.mhn.intercoapp.Adapters.EmployeeDirAdapter;
import com.example.mhn.intercoapp.static_class.EmployeeDir;
import java.util.ArrayList;
public class EmployeeDirectoryActivity extends AppCompatActivity {
ListView listView;
ImageView back_button;
EmployeeDir obj;
ArrayList <EmployeeDir> empDir ;
EmployeeDirAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_directory);
listView = (ListView) findViewById(R.id.listView_emp_directory_xml);
back_button = (ImageView) findViewById(R.id.back_button_header_emp_directory_activity_xml);
obj = new EmployeeDir();
empDir = new ArrayList<>();
adapter = new EmployeeDirAdapter(getApplicationContext(),empDir);
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
});
obj.setEmp_name("Hafiz Sadique Umar");
obj.setEmp_email("hsu#gmail.com");
obj.setEmp_contact_num("+923045607057");
empDir.add(obj);
empDir.add(obj);
empDir.add(obj);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Intent intent= new Intent(getApplicationContext(),DoneActivity.class);
startActivity(intent);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
This is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".EmployeeDirectoryActivity">
<RelativeLayout
android:id="#+id/relatice_layout_header_emp_directory_activity_xml"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_height="56dp">
<ImageView
android:id="#+id/back_button_header_emp_directory_activity_xml"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:src="#drawable/back_arrow_header"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Employee Directory"
android:textColor="#fff"
android:textSize="18dp"
android:textStyle="bold"
android:layout_centerInParent="true"
/>
</RelativeLayout>
<ListView
android:clickable="true"
android:id="#+id/listView_emp_directory_xml"
android:layout_below="#id/relatice_layout_header_emp_directory_activity_xml"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
This is Adapter
package com.example.mhn.intercoapp.Adapters;
import android.content.Context;
import android.content.Intent;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mhn.intercoapp.MainActivity;
import com.example.mhn.intercoapp.R;
import com.example.mhn.intercoapp.static_class.EmployeeDir;
import java.util.ArrayList;
public class EmployeeDirAdapter extends BaseAdapter {
Context context;
private LayoutInflater inflater;
private ArrayList<EmployeeDir> menuData=new ArrayList<>();
public EmployeeDirAdapter(Context context, ArrayList<EmployeeDir>EmpDir)
{
this.context = context;
this.menuData=EmpDir;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return menuData.size();
}
#Override
public Object getItem(int i) {
return menuData.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderEmpDir holder;
if (convertView == null) {
holder = new ViewHolderEmpDir();
convertView = inflater.inflate(R.layout.emp_directory_list_row_layout, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name_textView_emp_directory_list_row_layout);
holder.email = (TextView) convertView.findViewById(R.id.email_textView_emp_directory_list_row_layout);
holder.phone = (TextView) convertView.findViewById(R.id.phone);
holder.pic = (ImageView) convertView.findViewById(R.id.emp_pic_emp_directory_list_row_layout);
holder.viewButton = (ImageView) convertView.findViewById(R.id.view_button_emp_dir_list_row_layout);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderEmpDir) convertView.getTag();
}
holder.name.setText(menuData.get(position).getEmp_name());
holder.email.setText(menuData.get(position).getEmp_email());
holder.phone.setText(menuData.get(position).getEmp_contact_num());
//Linkify.addLinks(holder.email,Linkify.EMAIL_ADDRESSES);
//Linkify.addLinks(holder.phone,Linkify.PHONE_NUMBERS);
holder.pic.setImageResource(R.drawable.user_sign_up);
holder.viewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,MainActivity.class);
}
});
//downloadImage(position,holder);
return convertView;
}
// private void downloadImage(int position,ViewHolderShowAllBooking holder)
// {
// Picasso.with(context)
// .load("http://www.efefoundation.net/inklink/uploads/artist/"+menuData.get(position).getArtistId()+".jpg")
// .fit() // will explain later
// .into(holder.profile);
// }
static class ViewHolderEmpDir
{
TextView name;
TextView email;
TextView phone;
ImageView pic;
ImageView viewButton;
}
}
This is list_row_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="4"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_marginTop="5dp"
android:layout_centerHorizontal="true"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="70dp"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/emp_pic_emp_directory_list_row_layout"
android:layout_marginTop="5dp"
android:layout_width="80dp"
android:layout_height="70dp"
android:layout_marginBottom="5dp"
android:src="#drawable/user_sign_up"/>
</RelativeLayout>
<RelativeLayout
android:background="#color/colorAccent"
android:layout_marginTop="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3">
<TextView
android:id="#+id/name_textView_emp_directory_list_row_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textColor="#fff"
android:textSize="18dp"
android:layout_alignParentLeft="true"
android:text="Husnain"/>
<TextView
android:id="#+id/phone"
android:layout_toRightOf="#id/name_textView_emp_directory_list_row_layout"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:autoLink="phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="***********"
android:textColor="#fff"/>
<TextView
android:id="#+id/email_textView_emp_directory_list_row_layout"
android:layout_alignParentLeft="true"
android:layout_below="#id/name_textView_emp_directory_list_row_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="mhn786#gmail.com"
android:autoLink="email"
android:layout_marginLeft="10dp"
android:textSize="18dp"
android:textColor="#fff"
/>
<ImageView
android:id="#+id/view_button_emp_dir_list_row_layout"
android:src="#drawable/view"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
When I apply OnItemClickListener it does not do any action like intent inside the func not called. I tried toast too but nothing shown on clicking the listView Items.
I also tried OnItemSlectedListener , it also not worked for me.
What is the problem here with this code. ?
Thanks Every One. Issue was with autolink on email and phone, I make their focusable=false but nothing happened.Then I remove it and guess what? Clicklistener also starts working.
The attribute android:clickable="true" in your ListView could be overriding all of click events of its child views, you should probably remove it:
<ListView
android:clickable="true" <!-- Remove this attribute -->
android:id="#+id/listView_emp_directory_xml"
android:layout_below="#id/relatice_layout_header_emp_directory_activity_xml"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Android : Activity button shows up on fragment

I have a simple application, with an Activity calling a Fragment.
Question I have is .. why is the Activity's button showing up on the Fragment ?
Seems to be a very simple problem .. just not able to pin point the issue !!
Activity screenshot :
Fragment Screenshot :
Notice that Activity's SUBMIT button shows up on the Fragment, but the TextView and EditText get hidden. Why ??
Activity :
package com.example.deep_kulshreshtha.toddsyndrome;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private TextInputEditText inputEditText;
private EditText editText;
private ToddSyndromeDBHelper dbHelper;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// inputEditText = (TextInputEditText) findViewById(R.id.lastNameEditText);
editText = (EditText) findViewById(R.id.editText);
Button submitButton = (Button) findViewById(R.id.submitButton);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateReportFragment fragment = CreateReportFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main, fragment, "CreateFragment");
transaction.addToBackStack("CreateBackStack");
transaction.commit();
}
});
dbHelper = new ToddSyndromeDBHelper(this);
}
#Override
protected void onStop() {
super.onStop();
if(db != null) {db.close();}
}
public SQLiteDatabase getDb(){
if(db == null) {
// new ConnectionHelper().execute();
db = dbHelper.getWritableDatabase();
}
return db;
}
public void viewPatientReport(View view){
PatientReportFragment fragment = PatientReportFragment.
newInstance(editText.getText().toString());
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main, fragment, "SearchFragment");
transaction.addToBackStack("SearchBackStack");
transaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectionHelper extends AsyncTask<Void, Void, SQLiteDatabase>{
#Override
protected SQLiteDatabase doInBackground(Void... params) {
db = dbHelper.getWritableDatabase();
return db;
}
}
}
Activity xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Content xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="32dp"
android:fontFamily="cursive"
android:text="#string/todd_syndrome" />
<!-- <android.support.design.widget.TextInputLayout
android:id="#+id/layout_last_name"
android:layout_below="#id/headline"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/lastNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint" />
</android.support.design.widget.TextInputLayout>-->
<EditText
android:id="#+id/editText"
android:layout_below="#id/headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint"/>
<Button
android:id="#+id/submitButton"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:layout_below="#id/editText"
android:onClick="viewPatientReport"/>
</RelativeLayout>
Fragment :
package com.example.deep_kulshreshtha.toddsyndrome;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CreateReportFragment extends Fragment
implements View.OnClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
// private OnFragmentInteractionListener mListener;
String name;
boolean hallucegenicDrugs = false;
int age;
String gender;
boolean migraine = false;
private EditText editText;
private Switch switchMigraine;
private Spinner ageSpinner;
private RadioGroup group;
private Switch switchHall;
private Button saveButton;
private View.OnClickListener radioListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean checked = ((RadioButton)v).isChecked();
gender = ((RadioButton)v).getText().toString();
}
};
public CreateReportFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static CreateReportFragment newInstance(/*String param1, String param2*/) {
CreateReportFragment fragment = new CreateReportFragment();
// Bundle args = new Bundle();
// args.putString(ARG_PARAM1, param1);
// args.putString(ARG_PARAM2, param2);
// fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
// mParam1 = getArguments().getString(ARG_PARAM1);
// mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_create_report, container, false);
editText = (EditText) view.findViewById(R.id.createPersonName);
name = editText.getText().toString();
switchMigraine = (Switch) view.findViewById(R.id.migraineToggle);
switchMigraine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
migraine = false;
}
});
ageSpinner = (Spinner) view.findViewById(R.id.ageSpinner);
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 100; i++){ list.add(i); }
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getContext(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ageSpinner.setAdapter(adapter);
ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
age = (int) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
group = (RadioGroup) view.findViewById(R.id.genderButton);
RadioButton maleRadio = (RadioButton) view.findViewById(R.id.radioMale);
maleRadio.setOnClickListener(radioListener);
RadioButton femaleRadio = (RadioButton) view.findViewById(R.id.radioFemale);
femaleRadio.setOnClickListener(radioListener);
switchHall = (Switch) view.findViewById(R.id.switchButton);
switchHall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
hallucegenicDrugs = isChecked;
}
});
saveButton = (Button) view.findViewById(R.id.saveButton);
saveButton.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
int syndromePercentage = 0;
Log.v("Deep", "Patient name : " + name);
Log.v("Deep", "Has migraine : " + migraine);
Log.v("Deep", "Patient age : " + age);
Log.v("Deep", "Patient gender : " + gender);
Log.v("Deep", "Drugs ? : " + hallucegenicDrugs);
if(migraine == true){ syndromePercentage += 25; }
if(age <= 15){ syndromePercentage += 25; }
if(gender.equals("Male")){ syndromePercentage += 25; }
if(hallucegenicDrugs == true){ syndromePercentage += 25; }
SQLiteDatabase db = ((MainActivity)getActivity()).getDb();
ContentValues values = new ContentValues();
values.put(PatientTableContract.FeedEntry.COL_NAME_PATIENT_NAME, name);
values.put(PatientTableContract.FeedEntry.COL_NAME_RISK, syndromePercentage);
db.insert(PatientTableContract.FeedEntry.TABLE_NAME, null, values);
Toast.makeText(getContext(), "Data saved successfully !", Toast.LENGTH_SHORT).show();
editText.setText("");
switchMigraine.setChecked(false);
ageSpinner.setSelection(0);
group.clearCheck();
switchHall.setChecked(false);
}
}
Fragment xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.CreateReportFragment"
android:background="#android:color/white">
<!-- TODO: Update blank fragment layout -->
<android.support.design.widget.TextInputLayout
android:id="#+id/nameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/createPersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint" />
</android.support.design.widget.TextInputLayout>
<!-- <TextView
android:id="#+id/migraineText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/nameLayout"
android:text="#string/hint1"/>-->
<Switch
android:id="#+id/migraineToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hint1"
android:layout_below="#id/nameLayout"
android:checked="false"
android:layout_margin="10dp"
android:padding="10dp" />
<TextView
android:id="#+id/ageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/migraineToggle"
android:text="#string/hint2"
android:layout_margin="10dp"/>
<Spinner
android:id="#+id/ageSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:prompt="#string/hint2"
android:layout_below="#id/migraineToggle"
android:layout_toRightOf="#id/ageText"
android:layout_margin="10dp"
android:layout_marginLeft="20dp"/>
<!-- <TextView
android:id="#+id/genderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ageText"
android:text="#string/hint3"/>-->
<RadioGroup
android:id="#+id/genderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/ageSpinner"
android:checkedButton="#+id/radioMale"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender ?"
android:layout_margin="10dp"/>
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:layout_margin="10dp"/>
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:layout_margin="10dp"/>
</RadioGroup>
<!-- <TextView
android:id="#+id/hallucinogenicText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/genderText"
android:text="#string/hint4"/>
<ToggleButton
android:id="#+id/hallucinogenicToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/hallucinogenicText"
android:hint="#string/hint4" />-->
<Switch
android:id="#+id/switchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/genderButton"
android:text="#string/hint4"
android:checked="false"
android:layout_margin="10dp"/>
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/switchButton"
android:text="Submit"
android:layout_margin="10dp"/>
</RelativeLayout>
Second fragment xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.PatientReportFragment"
android:background="#android:color/white">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/patientReport"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
Second Fragment :
package com.example.deep_kulshreshtha.toddsyndrome;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.deep_kulshreshtha.toddsyndrome.PatientTableContract.FeedEntry;
public class PatientReportFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
private MainActivity activity;
private String[] projection = {FeedEntry._ID, FeedEntry.COL_NAME_PATIENT_NAME,
FeedEntry.COL_NAME_RISK};
private String selection = FeedEntry.COL_NAME_PATIENT_NAME + " = ?";
// private OnFragmentInteractionListener mListener;
public PatientReportFragment() {
// Required empty public constructor
}
public static PatientReportFragment newInstance(String param1) {
PatientReportFragment fragment = new PatientReportFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textView = (TextView) view.findViewById(R.id.patientReport);
SQLiteDatabase db = ((MainActivity)getActivity()).getDb();
Cursor cursor = db.query(FeedEntry.TABLE_NAME,
projection,
selection,
new String[]{mParam1},
null,
null,
null);
if(cursor.getCount() == 0){
textView.setText("No data found");
return /*view*/;
} else {
cursor.moveToFirst();
int riskPercent = cursor.getInt(cursor.getColumnIndex(FeedEntry.COL_NAME_RISK));
textView.setText("Risk percentage : " + riskPercent );
return /*view*/;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_patient_report, container, false);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (MainActivity) context;
}
}
I've solved this by wrapping my button inside a LinearLayout.
Probable cause of the issue: It seems Button has higher z-index rendering when it comes to android and thus not wrapping it inside another layout renders the button higher than all other fragments.
<LinearLayout
android:id="#+id/register_btn_wrapper"
android:orientation="vertical"
android:layout_below="#+id/splash_logo_img"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/register_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/register"
android:textSize="#dimen/text_big"
android:paddingLeft="#dimen/btn_padding"
android:paddingStart="#dimen/btn_padding"
android:paddingRight="#dimen/btn_padding"
android:paddingEnd="#dimen/btn_padding"
android:layout_gravity="center"
android:background="#color/app_color" />
</LinearLayout>
Hope this helps.
When you bind your view in fragment it is always a better approach to bind it in the method
onViewCreated()
When you bind your view in onCreateView() you will face rendering issues.
So bind your view in onViewCreated() method and the problem should be solved
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.name_of_layout,container,false);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//bind your view here
}
In the onCreateView of the fragment try adding this line
View view = inflater.inflate(R.layout.fragment_name, container, false);
view.setBackgroundColor(Color.WHITE);
I had a similar issue and fixed it using the above lines. Also, don't forget to add android:clickable="true" to your fragment_layout.xml parent layout.
I couldn't find the reason for this issue though but here is a small workaround:
Update the below layouts and try:
Activity xml :
Added a Framelayout:
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include layout="#layout/content_main"/>
</FrameLayout>
And in MainActivity: Used Framelayout container
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateReportFragment fragment = CreateReportFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(**R.id.container**, fragment, "CreateFragment");
transaction.addToBackStack("CreateBackStack");
transaction.commit();
}
});
In Content.xml Added android:layout_marginTop
<RelativeLayout 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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_marginTop="?attr/actionBarSize"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
tools:showIn="#layout/activity_main">
In fragment_create_report.xml added android:layout_marginTop
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:background="#android:color/white">
I'm not sure if you still need help with this. But basically the fragment and the activity have to be in different layouts.
This is the general structure for it: (you don't have to use the specific layouts I user below)
<RelativeLayout>
<LinearLayout id="#+id/all_code_relevant_to_activity"></LinearLayout>
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
</LinearLayout>
</RelativeLayout>
Basically you want to have your fragment separate from the rest of the code. So basically you could make a <FrameLayout> around your code in Activity.xml and then add your fragment layout by itself inside the <FrameLayout> but outside <android.support.design.widget.CoordinatorLayout>. Or make two sub layouts the split them apart
It's so wired to show only SUBMIT button on the top of page. I want to suggest you to add fragment instead of replace. please let me know the result after this.
FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_main, fragment, "SearchFragment");
fragmentTransaction.addToBackStack("SearchFragment");
fragmentTransaction.commitAllowingStateLoss();
In your activity xml, add one more element, FrameLayout to host the fragment, like below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="32dp"
android:fontFamily="cursive"
android:text="#string/todd_syndrome" />
<!-- <android.support.design.widget.TextInputLayout
android:id="#+id/layout_last_name"
android:layout_below="#id/headline"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="#+id/lastNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint" />
</android.support.design.widget.TextInputLayout>-->
<EditText
android:id="#+id/editText"
android:layout_below="#id/headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/edit_text_hint"/>
<Button
android:id="#+id/submitButton"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:layout_below="#id/editText"
android:onClick="viewPatientReport"/>
<!-- new layout to host fragment -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_holder"/>
</RelativeLayout>
and add your Fragment to that FrameLayout using.
set button property android:translationZ="-3dp" it will work.
What helped me is to add android:translationZ="10dp" to the layout that above the Buttons

CustomListViewAdapter isn't working

I am new to android and making an with toolbar, drawer, navigation list. and I used CustomlistviewAdapter to fill my list with its data.
The code has no errors however when I run the program close once it starts. the problem is coming from the Listview/Adapter part because when I remove it the program run the main activity successfully (without the list).
would anyone help and figure the problem please.
Previously Thanks for your help.
Main Activity Code:
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle actionBarDrawerToggle;
DrawerLayout drawerLayout;
private Toolbar Toolbar;
private ListView Mylist;
private CustomListViewAdapter customListViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar = (Toolbar) findViewById(R.id.toolbar);
assert Toolbar != null;
Toolbar.setLogo(R.drawable.logo);
Toolbar.setNavigationIcon(R.drawable.ericsson);
setSupportActionBar(Toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.navigation);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,Toolbar,R.string.app_name,R.string.app_name);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
final String[] titles = new String[] {"Home" ,"Cabinet Viewer", "Node Viewer", "Connectivity Viewer", "Connection Tracker"};
ArrayList<HashMap<String, String>> itemslist= new ArrayList<>();
for (int i = 0; i < 5; i++){
HashMap<String, String> data = new HashMap<>();
data.put("title", titles[i]);
itemslist.add(data);
}
Mylist = (ListView) findViewById(R.id.navigation_list);
customListViewAdapter = new CustomListViewAdapter(getApplicationContext(), itemslist);
Mylist.setAdapter(customListViewAdapter);
Mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int newposition = position;
String itemClickedId = Mylist.getItemAtPosition(newposition).toString();
Toast.makeText(getApplicationContext(), "ID Clicked: " + itemClickedId, Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
finish();
return true;
}
if (id == R.id.home) {
drawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER
return true;
}
return super.onOptionsItemSelected(item);
}
}
My CustomListViewUdapter Code:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class CustomListViewAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<HashMap<String, String>> Items;
private static LayoutInflater inflater = null;
public CustomListViewAdapter (Context context, ArrayList<HashMap<String, String>> data){
mContext = context;
Items = data;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Items.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
view = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)view.findViewById(R.id.listiitemtitle);
ImageView icon = (ImageView)view.findViewById(R.id.listitemicon);
HashMap<String, String> mitems = new HashMap<>();
mitems = Items.get(position);
title.setText(mitems.get("title"));
icon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ericsson, null));
}
return null;
}
}
My Main Activity XML:
<?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" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/navigation"
android:fitsSystemWindows="true">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="esmviewer.myandroid.com.esmviewer.MainActivity">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#color/colorPrimary"
app:theme="#style/ThemeOverlay.AppCompat.Light"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark">
</android.support.v7.widget.Toolbar>
</LinearLayout>
<ListView
android:layout_width="220dp"
android:layout_height="match_parent"
android:id="#+id/navigation_list"
android:layout_gravity= "start"
android:choiceMode="singleChoice"
android:divider="#color/colorPrimary"
android:dividerHeight="1dp"
android:background="#B9F6CA"/>
</android.support.v4.widget.DrawerLayout>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="esmviewer.myandroid.com.esmviewer.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Welcome"
android:textStyle="bold"
android:textSize="30sp"
android:textColor="#EF5350"
android:id="#+id/Welcome"
android:layout_above="#+id/esm"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="You can explore our Datacenters
by clicking on the main menu"
android:textSize="20sp"
android:textAlignment="center"
android:id="#+id/welcome_description"
android:layout_marginBottom="124dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Ericsson Services Manager"
android:textSize="25sp"
android:textStyle="bold"
android:id="#+id/esm"
android:textColor="#1A237E"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Viewer Version"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#000000"
android:id="#+id/viewer_version"
android:layout_below="#+id/esm"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/imageView"
android:background="#drawable/etisalat"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
My CustomList XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:padding="5dp"
android:orientation="horizontal">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/iconid"
android:padding="3dp"
android:layout_alignParentLeft="true"
android:layout_margin="5dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/listitemicon"
android:src="#drawable/ericsson"
/>
</android.support.v7.widget.LinearLayoutCompat>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item"
android:id="#+id/listiitemtitle"
android:textStyle="bold"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_marginLeft="60dp"
/>
</RelativeLayout>
I can see one mistake in your getView()
It must return the view, not null
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
...
return view; }

Android Navigation Drawer with Image Error

I have written a simple application for navigation Drawer based on this tutorial: https://www.youtube.com/watch?v=tZ2DNC3FIic
but there is a problem when I run the application.
The Error is i am having a blank or Empty Drawer List when i launch the application, and instead of that i Got the list in the application launch.
like this image:
This is the main_activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
tools:context="com.subhi.tabhost.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/main_content"
android:layout_height="match_parent"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/drawer_pane"
android:layout_gravity="start"
android:background="#FF4081"
android:layout_height="match_parent"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/profile_box"
android:padding="8dp"
android:gravity="center_vertical"
android:layout_height="100dp">
<ImageView
android:id="#+id/icon"
android:layout_margin="5dp"
android:layout_width="50dp"
android:background="#drawable/ic_launcher"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_toRightOf="#+id/icon"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:id="#+id/nav_list"
android:layout_below="#id/profile_box"
android:choiceMode="singleChoice"
android:background="#ffffff"
android:layout_height="match_parent"></ListView>
</android.support.v4.widget.DrawerLayout>
and this is the MainActivity class:
package com.subhi.tabhost;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
RelativeLayout drawerPane;
ListView lvNav;
List<NavItem> listNavItems;
List<Fragment> listFragments;
ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
drawerPane= (RelativeLayout) findViewById(R.id.drawer_pane);
lvNav =(ListView)findViewById(R.id.nav_list);
listNavItems=new ArrayList<NavItem>();
listNavItems.add(new NavItem("sHome", "HomePage", R.drawable.ic_launcher));
listNavItems.add(new NavItem("Setting", "HomePage", R.drawable.ic_launcher));
listNavItems.add(new NavItem("Setting", "HomePage", R.drawable.ic_launcher));
NavListAdapter navListAdapter=new NavListAdapter(getApplicationContext(),R.id.nav_list,listNavItems);
lvNav.setAdapter(navListAdapter);
listFragments=new ArrayList<Fragment>();
listFragments.add(new MyHome());
listFragments.add(new MySettings());
listFragments.add(new MyAbout());
FragmentManager fragmentManager=getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content,listFragments.get(0)).commit();
setTitle(listNavItems.get(0).getTitle());
lvNav.setItemChecked(0, true);
drawerLayout.closeDrawer(drawerPane);
lvNav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, listFragments.get(position)).commit();
setTitle(listNavItems.get(position).getTitle());
lvNav.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerPane);
}
});
actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.drawer_opened,R.string.drawer_closed){
#Override
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
invalidateOptionsMenu();
super.onDrawerClosed(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
and this is the Navlist Adapter Class:
package com.subhi.tabhost;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by subhi on 2/9/2016.
*/
public class NavListAdapter extends ArrayAdapter<NavItem> {
Context context;
int reslayout;
List<NavItem> listNavItem;
public NavListAdapter(Context context, int reslayout, List<NavItem> listNavItem) {
super(context, reslayout, listNavItem);
this.context=context;
this.reslayout=reslayout;
this.listNavItem=listNavItem;
}
#SuppressLint("ViewHolder") #Override
public View getView(int position, View convertView, ViewGroup parent) {
View v=View.inflate(context, reslayout, null);
TextView tvtitle= (TextView) v.findViewById(R.id.titlemain);
TextView tvsubtitle=(TextView)v.findViewById(R.id.subtitle);
ImageView navicon= (ImageView) v.findViewById(R.id.nav_icon);
NavItem navItem=listNavItem.get(position);
tvtitle.setText(navItem.getTitle());
tvsubtitle.setText(navItem.getSubtitle());
navicon.setImageResource(navItem.getResicon());
return v;
}
}
and this is the NavItem Class:
package com.subhi.tabhost;
/**
* Created by subhi on 2/9/2016.
*/
public class NavItem {
private String title;
private String subtitle;
private int resicon;
public NavItem(String title,String subtitle, int resicon ) {
this.subtitle = subtitle;
this.resicon = resicon;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public int getResicon() {
return resicon;
}
public void setResicon(int resicon) {
this.resicon = resicon;
}
}
and this is one of the Fragments that i used when the item is clicked:
package com.subhi.tabhost;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by subhi on 2/9/2016.
*/
public class MyHome extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_home,container,false);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
and this is the item_nav_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="match_parent">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_launcher"
android:id="#+id/nav_icon" />
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical"
android:layout_margin="10dp"
android:layout_height="40dp">
<TextView
android:layout_width="wrap_content"
android:id="#+id/titlemain"
android:textStyle="bold"
android:textSize="18sp"
android:text="Titile"
android:textColor="#000"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:text="title2"
android:textSize="18sp"
android:id="#+id/subtitle"
android:textColor="#000"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
The error is from this line
new NavListAdapter(getApplicationContext(),R.id.nav_list,listNavItems)
The parameter that you have for R.id.nav_list should be a R.layout.nav_item where nav_item.xml is the layout for a row in the NavListAdapter.
Here
NavListAdapter navListAdapter=new NavListAdapter(getApplicationContext(),R.id.nav_list,listNavItems);
you pass R.id.nav_list which then you want to inflate with
View v=View.inflate(context, reslayout, null);
reslayout cannot be R.id, it has to be layout file (R.layout).
EDIT
Now your main_layout is wrong. Should be like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
tools:context="com.subhi.tabhost.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/main_content"
android:layout_height="match_parent"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/drawer_pane"
android:layout_gravity="start"
android:background="#FF4081"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/profile_box"
android:padding="8dp"
android:gravity="center_vertical"
android:layout_height="100dp">
<ImageView
android:id="#+id/icon"
android:layout_margin="5dp"
android:layout_width="50dp"
android:background="#drawable/ic_launcher"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_toRightOf="#+id/icon"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:text="Subhi"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:id="#+id/nav_list"
android:layout_below="#id/profile_box"
android:choiceMode="singleChoice"
android:background="#ffffff"
android:layout_height="match_parent"></ListView>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>

Soft key not appear while tapping on EditText which is inside listView and listView is in AleartBox

In my application customize Alear Box is there. In this alert box there is a customize ListView in which one TextView and one EditText is there. Every thing work fine and Alert Box coming on the screen perfectly.
But when I tap on Edit text to fill the characters into the Edit Text, Android Softkey on appearing. Therefore I am not able to insert and data into Edit Text.
My Code:-
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Population"
android:onClick="getPopulation" />
</RelativeLayout>
alert_box.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
tools:listitem="#layout/list_view_resourse" >
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Add" />
<Button
android:id="#+id/cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel" />
</LinearLayout>
</LinearLayout>
list_view_resourse.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="#+id/district"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000000"
android:textStyle="bold" />
<EditText
android:id="#+id/population"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity
package com.exmp;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener{
private ArrayAdapter<Disrict> adapter;
private ArrayList<Disrict> disricts;
private ListView lView;
private Button add, cancel;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
private void getPopulation() {
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.alert_box, null);
lView = (ListView) view.findViewById(R.id.lView);
add = (Button) view.findViewById(R.id.add);
cancel = (Button) view.findViewById(R.id.cancel);
disricts = new ArrayList<Disrict>();
disricts.add(new Disrict(1, "Bangalore", 45.22));
disricts.add(new Disrict(1, "Gulbarga", 22.22));
adapter = new DistrictAdapter(MainActivity.this, R.layout.list_view_resourse, disricts);
lView.setAdapter(adapter);
cancel.setOnClickListener(this);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Population");
alert.setView(view);
alert.setCancelable(false);
dialog = alert.create();
dialog.show();
}
public void getPopulation(View v){
getPopulation();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
break;
case R.id.cancel:
dialog.dismiss();
break;
}
}
}
Disrict
package com.exmp;
public class Disrict {
private int id;
private String strDistrict;
private double population;
public Disrict(int id, String strDistrict, double population) {
super();
this.id = id;
this.strDistrict = strDistrict;
this.population = population;
}
public int getId() {
return id;
}
public String getStrDistrict() {
return strDistrict;
}
public double getPopulation() {
return population;
}
#Override
public String toString() {
return strDistrict;
}
}
DistrictAdapter
package com.exmp;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class DistrictAdapter extends ArrayAdapter<Disrict> {
private final Context context;
private final int rowResourceId;
private final ArrayList<Disrict> disricts;
public DistrictAdapter(Context context, int resource,
ArrayList<Disrict> disricts) {
super(context, resource, disricts);
this.context = context;
this.rowResourceId = resource;
this.disricts = disricts;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Spinner spinnerPaymentType = null;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.district);
textView.setText(disricts.get(position).getStrDistrict());
return rowView;
}
}
try this code in your listview
<ListView
android:id="#android:id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:descendantFocusability="beforeDescendants"
/>
There are some problems which help me.
It better to use dynamical views rather than ListView when you have e Focasable view inside of Cell
related links:
EditText inside ListView lost focus,
EditText inside ListView will not stay focused,
Android :EditText loses content on scroll in ListView?
ettext.requestFocus();
ettext.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(ettext, 0);
}
},200);

Categories

Resources