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
Related
I am totally new in the world of Android development and have some trouble to understand how a RecycleViewAdapter works with a CardView when the CardView is a Fragment. I was trying to understand the example on https://github.com/firebase/quickstart-android/blob/master/database/README.md but since they are using a lot of stuff which is related to Firebase I tried to port this to my own example.
I want to have a list which contains several cards just like this:
However, the user should be able to add and remove different cards. At the beginning the view should be empty and if the user press the floating button on the right corner
a new card should be created.
I've just ported the way I thought it should work. Unfortunately, when I press the button nothing is happening (of course the Hello World is printed).
Thanks for you help.
Here is the code of my MainActivity:
package com.example.dynamicfragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity
{
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("Hello World");
fragmentTransaction.add(new CardListFragment(), "CardListFragment");
}
});
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the class who extend the CardListFragment:
package com.example.dynamicfragment;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.dynamicfragment.adapter.CardAdapter;
import com.example.dynamicfragment.model.Party;
import java.util.ArrayList;
public class CardListFragment extends Fragment
{
private static final String TAG = "CardListFragment";
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
private CardAdapter mAdapter;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_card_list, container, false);
mRecycler = rootView.findViewById(R.id.messagesList);
mRecycler.setHasFixedSize(true);
ArrayList<Party> demo = new ArrayList<>();
demo.add(new Party(0,"Demo", R.drawable.ic_action_account_circle_40));
this.mAdapter = new CardAdapter(demo);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
mRecycler.setAdapter(null);
}
#Override
public void onStart()
{
super.onStart();
if (null != mAdapter)
{
//mAdapter.startListening();
}
}
#Override
public void onStop()
{
super.onStop();
if (null != mAdapter)
{
//mAdapter.stopListening();
}
}
}
Here is the code of my data model:
package com.example.dynamicfragment.model;
import java.util.Objects;
public class Party
{
private int id;
private String name;
private int image;
public Party(int id, String name, int image)
{
this.id = id;
this.name = name;
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
#Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Party party = (Party) o;
return id == party.id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
Here is my Adapater class:
package com.example.dynamicfragment.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.dynamicfragment.R;
import com.example.dynamicfragment.model.Party;
import java.util.ArrayList;
public class CardAdapter extends RecyclerView .Adapter<CardAdapter.CardViewHolder>
{
private ArrayList<Party> dataList;
public static class CardViewHolder extends RecyclerView.ViewHolder
{
TextView partyName;
ImageView imageViewIcon;
public CardViewHolder(View itemView)
{
super(itemView);
this.partyName = (TextView) itemView.findViewById(R.id.postAuthor);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.postAuthorPhoto);
}
}
public CardAdapter(ArrayList<Party> data)
{
this.dataList = data;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(final CardViewHolder holder, final int listPosition)
{
TextView partyName = holder.partyName;
ImageView imageView = holder.imageViewIcon;
partyName.setText(dataList.get(listPosition).getName());
imageView.setImageResource(dataList.get(listPosition).getImage());
}
#Override
public int getItemCount()
{
return dataList != null ? dataList.size() : 0;
}
}
Content files:
activity_main.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"
tools:context=".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_main.xml:
<?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">
<include layout="#layout/fragment_card_list" />
</android.support.constraint.ConstraintLayout>
fragment_card_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<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">
<android.support.v7.widget.RecyclerView
android:id="#+id/messagesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:clipToPadding="false"
android:padding="5dp"
android:scrollbars="vertical"
tools:listitem="#layout/card_view" />
</FrameLayout>
card_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<include
android:id="#+id/postAuthorLayout"
layout="#layout/include_post_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<LinearLayout
android:id="#+id/starLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/postAuthorLayout"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/postAuthorLayout"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/star"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:background="?attr/selectableItemBackground"
android:src="#drawable/ic_toggle_star_outline_24" />
<TextView
android:id="#+id/postNumStars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
tools:text="7" />
</LinearLayout>
<include layout="#layout/include_post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/postAuthorLayout"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
include_post_author.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="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/postAuthorPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_account_circle_40" />
<TextView
android:id="#+id/postAuthor"
style="#style/Base.TextAppearance.AppCompat.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
tools:text="someauthor#email.com" />
</LinearLayout>
include_post_text.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">
<TextView
android:id="#+id/postTitle"
style="#style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textStyle="bold"
tools:text="My First Post" />
<TextView
android:id="#+id/postBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
tools:text="Hallo Welt" />
</LinearLayout>
#Christoph M. The Fragment Transaction if you want to applu on ui u need to give a FrameLayout Id.
Create a FrameLayout with one id in your main class then attach your fragment to id value
like this below
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FirstFragment fragment = new FirstFragment();
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, fragment);
transaction.addToBackStack(ConstantVariables.FirstFragment);
transaction.commit();
}
<?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">
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I'm trying to make an app to keep score during a game of golf. To do this I have 18 tabs in a tab activity (one for each hole) and then in each tab I have a ListView with a list of players, their score for the hole, and a plus and minus button.
I need to make it so that hitting the plus button in a row increases that players score for that hole but I'm having trouble figuring out where and how to do an OnClickListener and how to handle the indexing for the player and the hole.
I'm very new to Android Studio so any help is greatly appreciated!
HoleTabsActivity.java
package com.txstate.zms22.urban;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class HoleTabsActivity extends FragmentActivity {
int NUMBER_OF_HOLES = 18;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hole_tabs);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
String[] names = getResources().getStringArray(R.array.players);
int[] scores = new int[names.length];
ListView tabbedScorecard_ListView = findViewById(R.id.tabbedScorecard_ListView);
ItemAdapter adapter = new ItemAdapter(getApplicationContext(), names, scores);
tabbedScorecard_ListView.setAdapter(adapter);
Button minus_Button = findViewById(R.id.minus_Button);
minus_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scores[i]++;
}
});
}
#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_hole_tabs, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hole_tabs, container, false);
TextView textView = view.findViewById(R.id.sectionLabel_TextView);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
Button minus_Button = view.findViewById(R.id.minus_Button);
TextView holeScore_TextView = view.findViewById(R.id.holeScore_TextView);
return view;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 1 page per number of holes
return NUMBER_OF_HOLES;
}
}
}
activity_hole_tabs.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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.txstate.zms22.urban.HoleTabsActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
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:layout_weight="1"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
fragment_hole_tabs.xml
<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:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.txstate.zms22.urban.HoleTabs$PlaceholderFragment">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Header" />
<ListView
android:id="#+id/tabbedScorecard_ListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<View
android:id="#+id/myRectangleView"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#drawable/hole_number_background" />
</LinearLayout>
<TextView
android:id="#+id/sectionLabel_TextView"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:text="Hole ##"
android:textColor="#color/holeUnderline"
android:textSize="24dp"
app:layout_constraintBottom_toTopOf="#+id/holeUnderline_View"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1" />
<View
android:id="#+id/holeUnderline_View"
android:layout_width="112dp"
android:layout_height="8dp"
android:background="#drawable/hole_number_underline"
app:layout_constraintEnd_toStartOf="#+id/linearLayout"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/linearLayout"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_editor_absoluteY="481dp" />
</android.support.constraint.ConstraintLayout>
ItemAdapter.java
package com.txstate.zms22.urban;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ItemAdapter extends BaseAdapter {
LayoutInflater mInflater;
String[] players;
int[] scores;
public ItemAdapter(Context c, String[] p, int[] s) {
players = p;
scores = s;
mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return players.length;
}
#Override
public Object getItem(int i) {
return players[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = mInflater.inflate(R.layout.player_list, null);
TextView name_TextView = v.findViewById(R.id.name_TextView);
String name = players[i];
name_TextView.setText(name);
TextView holeScore_TextView = v.findViewById(R.id.holeScore_TextView);
int score = scores[i];
holeScore_TextView.setText(score +"");
Button minus_Button = v.findViewById(R.id.minus_Button);
Button plus_Button = v.findViewById(R.id.plus_Button);
return v;
}
}
player_list.xml
<?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"
tools:layout_editor_absoluteY="81dp">
<TextView
android:id="#+id/name_TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Player Name"
android:textSize="#dimen/text_size"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/holeScore_TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="3"
android:textSize="#dimen/text_size"
app:layout_constraintBottom_toBottomOf="#+id/minus_Button"
app:layout_constraintEnd_toStartOf="#+id/plus_Button"
app:layout_constraintStart_toEndOf="#+id/minus_Button"
app:layout_constraintTop_toTopOf="#+id/minus_Button"
app:layout_constraintVertical_bias="0.45" />
<Button
android:id="#+id/minus_Button"
android:layout_width="#dimen/box_size"
android:layout_height="#dimen/box_size"
android:layout_marginStart="225dp"
android:text="-"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="#+id/name_TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/name_TextView" />
<Button
android:id="#+id/plus_Button"
android:layout_width="#dimen/box_size"
android:layout_height="#dimen/box_size"
android:layout_marginEnd="16dp"
android:text="+"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="#+id/holeScore_TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/holeScore_TextView"
app:layout_constraintVertical_bias="0.55" />
</android.support.constraint.ConstraintLayout>
Player List Layout
The layout of each player's information in the ListView
If there's any more information I should include in my post let me know!
Thanks again.
After clicking on the Add button it only show the First item. But when I touch the edit text field the remaining items are shown and gone.
Here is the MainActivity:
package com.example.mysecondapp.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
EditText editText;
Button add,ins;
ArrayList<item> list;
Adapter adpter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ins= (Button) findViewById(R.id.button1);
add= (Button) findViewById(R.id.button2);
editText= (EditText) findViewById(R.id.editText2);
recyclerView= (RecyclerView) findViewById(R.id.recycler);
list=new ArrayList<item>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adpter =new Adapter(new ArrayList<item>());
recyclerView.setAdapter(adpter);
ins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String str=editText.getText().toString();
InputMethodManager inputMethodManager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
editText.setText(" ");
Toast.makeText(getBaseContext(),"Added to list",Toast.LENGTH_SHORT).show();
item i=new item(str);
list.add(i);
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adpter.adplist=list;
Toast.makeText(getBaseContext(),"Adding to Recycler View",Toast.LENGTH_SHORT).show();
adpter.notifyDataSetChanged();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).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_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);
}
}
Here is the Adapter
package com.example.mysecondapp.myapplication;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {
ArrayList<item> adplist;
public ArrayList<item> getAdplist() {
return adplist;
}
public void setAdplist(ArrayList<item> adplist) {
this.adplist = adplist;
}
public Adapter(ArrayList<item>list) {
adplist=new ArrayList<item>();
adplist=list;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
item i=adplist.get(position);
holder.tv.setText(i.getStr());
}
#Override
public int getItemCount() {
return adplist.size();
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView tv;
public MyHolder(View itemView) {
super(itemView);
tv=itemView.findViewById(R.id.item_text_view);
}
}
}
Here is The item
package com.example.mysecondapp.myapplication;
public class item {
String str;
public item(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
Here is 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.mysecondapp.myapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
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>
Here is content xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main"
tools:context="com.example.mysecondapp.myapplication.MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/editText2"
android:layout_weight="1" />
<Button
android:text="INSERT"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:id="#+id/button1"
android:layout_weight="2" />
<Button
android:text="ADD"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:id="#+id/button2"
android:layout_weight="2" />
</LinearLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"/>
</RelativeLayout>
And the item xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/item_text_view"/>
</LinearLayout>
What's wrong with the code ?
Thanks in advance
Try this:
i have changed layout_height of LinearLayout to wrap_content
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/item_text_view"/>
</LinearLayout>
The problem is that you have set the height of the recycler item to match parent which means that the first item of your recycler view is taking the full screen. If you scroll you will find the other items at the bottom.
To fix this
In item.xml use
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
Instead of
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
I got a fragment that get the data in runtime and I think that what cause the problem, but I'm not sure.
it show the button twice and I cant scroll. if i'm writing false insted of true in View v = inflater.inflate(R.layout.fragment_book_view, container, true);
it shows only the button.
the fragment load in runtime in to FrameLayout at the activity, that layout suppose to contain diffrent fragment each time.
my fragment code:
java:
package javaproject.project5776;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import entities.Book;
import model.backend.Backend;
import model.backend.BackendFactory;
import util.ImageLoader;
/**
* A simple {#link Fragment} subclass.
*/
public class BookView extends Fragment {
private Bitmap bitmap;
private String name;
public static BookView newInstance(String book,Bitmap bitmap) {
Bundle args = new Bundle();
BookView fragment = new BookView();
fragment.bitmap = bitmap;
fragment.name = book;
fragment.setArguments(args);
return fragment;
}
public BookView() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_book_view, container, true);
Backend backend = BackendFactory.getInstance();
try {
Book b = backend.readBook(name);
((TextView)v.findViewById(R.id.bookView_name)).setText(b.getBookName());
((TextView)v.findViewById(R.id.bookView_author)).setText(b.getAuthor());
((TextView)v.findViewById(R.id.bookView_category)).setText(b.getCategory().name());
((TextView)v.findViewById(R.id.bookView_description)).setText(b.getDescription());
((TextView)v.findViewById(R.id.bookView_pages)).setText(Integer.toString(b.getPages()));
((TextView)v.findViewById(R.id.bookView_publishingDate)).setText(b.getPublishingDate());
final ImageView imageView = (ImageView)v.findViewById(R.id.bookView_image);
if(bitmap != null){
imageView.setImageBitmap(bitmap);
} else{
ImageLoader imageLoader = new ImageLoader();
imageLoader.setListener(new ImageLoader.ImageTaskListener() {
#Override
public void onActionEnd() {}
#Override
public void onImageDownload(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
});
imageLoader.execute(b.getImage());
}
}
catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(e.getMessage());
builder.create().show();
}
return inflater.inflate(R.layout.fragment_book_view, container, false);
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/bookview.imageWidth"
android:layout_height="250dp"
android:id="#+id/bookView.image"/>
<TextView
android:textSize="#dimen/custom_book_text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_toEndOf="#id/bookView.image"
android:id="#+id/bookView.name"/>
<TextView
android:textSize="#dimen/custom_book_text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_toEndOf="#id/bookView.image"
android:layout_below="#id/bookView.name"
android:id="#+id/bookView.author"/>
<TextView
android:textSize="#dimen/custom_book_text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_toEndOf="#id/bookView.image"
android:layout_below="#id/bookView.author"
android:id="#+id/bookView.pages"/>
<TextView
android:textSize="#dimen/custom_book_text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_toEndOf="#id/bookView.image"
android:layout_below="#id/bookView.pages"
android:id="#+id/bookView.category"/>
<TextView
android:textSize="#dimen/custom_book_text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_toEndOf="#id/bookView.image"
android:layout_below="#id/bookView.category"
android:id="#+id/bookView.publishingDate"/>
<TextView
android:id="#+id/bookView.description"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:layout_below="#id/bookView.image"/>
<Button
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_below="#id/bookView.description"
android:text="#string/bookView_button"/>
</RelativeLayout>
</ScrollView>
Try to change
return inflater.inflate(R.layout.fragment_book_view, container, false) ;
to
return v;
change the first line third parameter to false,and as Lauren.Liuling said neen to change the last line to return v;.
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>