Using DialogFragments. Are there bugs in the official example? - android

I have just copied the official example, and my dialog is very narrow. Why?
My code.
The dialog.
package com.redplanet;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditNameDialog extends DialogFragment implements OnEditorActionListener {
public interface EditNameDialogListener {
void onFinishEditDialog(String inputText);
}
private EditText mEditText;
public EditNameDialog() {
// Empty constructor required for DialogFragment
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_name, container);
mEditText = (EditText) view.findViewById(R.id.txt_your_name);
getDialog().setTitle("Hello");
// Show soft keyboard automatically
mEditText.requestFocus();
getDialog().getWindow().setSoftInputMode(
LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mEditText.setOnEditorActionListener(this);
return view;
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
// Return input text to activity
EditNameDialogListener activity = (EditNameDialogListener) getActivity();
activity.onFinishEditDialog(mEditText.getText().toString());
this.dismiss();
return true;
}
return false;
}
}
The activity.
package com.redplanet;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.widget.Toast;
import com.redplanet.EditNameDialog.EditNameDialogListener;
public class FragmentDialogDemo extends FragmentActivity implements EditNameDialogListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showEditDialog();
}
private void showEditDialog() {
FragmentManager fm = getSupportFragmentManager();
EditNameDialog editNameDialog = new EditNameDialog();
editNameDialog.show(fm, "fragment_edit_name");
}
#Override
public void onFinishEditDialog(String inputText) {
Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
}
Activity layout file.
<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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="#string/hello_world"
tools:context=".FragmentDialogDemo" />
</RelativeLayout>
Dialog layout file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/edit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/lbl_your_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your name" />
<EditText
android:id="#+id/txt_your_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="text" />
</LinearLayout>

In order not to puzzle over workarounds, I'd prefer an AlertDialog to a DialogFragment. The issue I asked about was on Android 2.3.6 and wasn't on Android 4.1.2.

Related

firebaseRecyclerAdapter gets filled, yet wont show anything in a dialog - Android Studio

So, I tried putting a recyclerView in a "popup" dialog using a firebaseRecyclerAdapter.
My problem is, that I know for sure the adapter gets filled because I was using the Logcat to tell me when it adds another "user" to the adapter, but it wont show anything in the recyclerview in the dialog.
I'm having this problem for a couple of days and couldn't find an answer yet, glad if you could help me :)
I'm using a main screen which changes fragments, and from a certain fragment I'm calling this specific dialog.
These are my files:
UserViewHolder - the class which holds the "sets" for the cardview:
public static class UserViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UserViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setName(String name)
{
TextView teacherName=(TextView) mView.findViewById(R.id.txtNameTea);
teacherName.setText(name);
}
public void setEmail(String email)
{
TextView txtEmailTea=(TextView) mView.findViewById(R.id.txtEmailTea);
txtEmailTea.setText(email);
}
public void setImage(final Context ctx, Uri imageUri, User cUser)
{
final ImageView imgProfileTea=(ImageView) mView.findViewById(R.id.imgProfileTea);
Picasso.with(ctx).load(cUser.getImageUri()).into(imgProfileTea);
if(imgProfileTea.getDrawable()==null) {
StorageReference load = FirebaseStorage.getInstance().getReference().child("usersProfilePic/" + cUser.getImageName());
load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri.toString()).into(imgProfileTea);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG);
}
});
}
}
}
Schedules - the fragment which calls the dialog from its toolbar:
package com.example.android.aln4;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.example.android.aln4.LoginActivity.myUser;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static java.lang.System.in;
import static com.example.android.aln4.navDrawerMain.studentsQuery;
public class Schedules extends Fragment {
private Toolbar ScheduleToolbar;
private Button addEvent;
//private TextView txt;
private RecyclerView mRecyclerViewStudentEvent;
private CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM-yyyy", Locale.getDefault());
private String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addEvent:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
mRecyclerViewStudentEvent = (RecyclerView) mView.findViewById(R.id.mRecyclerViewStudentEvent);
mRecyclerViewStudentEvent.setHasFixedSize(true);
mRecyclerViewStudentEvent.setLayoutManager(new LinearLayoutManager(getContext()));
setStudentsList();
mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
final EditText edtEventTitle = (EditText) mView.findViewById(R.id.edtEventTitle);
final TextView txtEventStartTime = (TextView) mView.findViewById(R.id.txtEventStartTime);
final TextView txtEventEndTime = (TextView) mView.findViewById(R.id.txtEventEndTime);
final EditText edtEventLocation = (EditText) mView.findViewById(R.id.edtEventLocation);
Button btnOfferEvent = (Button) mView.findViewById(R.id.btnOfferEvent);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
btnOfferEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int startHour = Integer.parseInt(txtEventStartTime.getText().toString().substring(0, 2));
int startMinute = Integer.parseInt(txtEventStartTime.getText().toString().substring(3, 5));
startTime.set(Calendar.HOUR_OF_DAY, startHour);
startTime.set(Calendar.MINUTE, startMinute);
int endHour = Integer.parseInt(txtEventEndTime.getText().toString().substring(0, 2));
int endMinute = Integer.parseInt(txtEventEndTime.getText().toString().substring(3, 5));
endTime.set(Calendar.HOUR_OF_DAY, endHour);
endTime.set(Calendar.MINUTE, endMinute);
String mId =/*dataSelected+*/ String.valueOf(startHour) + String.valueOf(startMinute);//+selectedUserID
EventCreation newEvent = new EventCreation(mId, startTime, endTime, edtEventTitle.getText().toString(), edtEventLocation.getText().toString(), R.color.colorPrimary);
dialog.dismiss();
}
});
dialog.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
ScheduleToolbar = (Toolbar) getView().findViewById(R.id.schedule_toolbar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
((AppCompatActivity) getActivity()).setSupportActionBar(ScheduleToolbar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
int year = cal.get(Calendar.YEAR);
getActivity().setTitle(month + "-" + year);
compactCalendar = (CompactCalendarView) getView().findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
long millis = System.currentTimeMillis() % 1000;
Event ev1 = new Event(Color.RED, millis, "First try");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
//put events into scroll view adapter
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getActivity().setTitle(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedules, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
private void setStudentsList() {
studentsQuery=mDatabaseReference.orderByChild("teacherNum").equalTo(myUser.getTeacherNum());
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,studentsQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName() + " " + model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()), model);
}
};
mRecyclerViewStudentEvent.setAdapter(firebaseRecyclerAdapter);
}
}
The dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/title"/>
<EditText
android:id="#+id/edtEventTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="כותרת"
android:layout_marginRight="50dp"/>
<android.support.v7.widget.RecyclerView
android:layout_marginTop="50dp"
android:id="#+id/mRecyclerViewStudentEvent"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/clock"/>
<TextView
android:layout_width="wrap_content"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="שעת התחלה"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="50dp"
android:layout_marginTop="5dp"
android:text="21:00" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="25dp"
android:layout_marginRight="50dp"
android:background="#color/darkgray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:text="שעת סיום"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventEndTime"
android:layout_width="match_parent"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="30dp"
android:text="21:45" />
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/location"/>
<EditText
android:id="#+id/edtEventLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="מיקום תחילת השיעור"
android:layout_marginRight="50dp"/>
</RelativeLayout>
<Button
android:id="#+id/btnOfferEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="הצע שיעור"/>
</LinearLayout>
One more thing is that I know is that I'm already able to bring up users into the recyclerView in other fragments.. Here's the code in another fragment:
package com.example.android.aln4;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.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 android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static com.example.android.aln4.navDrawerMain.teachersQuery;
public class TeachersList extends Fragment {
private RecyclerView mRecyclerViewTeacher;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("מורים");
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
mRecyclerViewTeacher=(RecyclerView) getView().findViewById(R.id.mRecyclerViewTeacher);
mRecyclerViewTeacher.setHasFixedSize(true);
mRecyclerViewTeacher.setLayoutManager(new LinearLayoutManager(getContext()));
setTeachersList();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.teachers_list_frag,container,false);
}
private void setTeachersList() {
teachersQuery=mDatabaseReference.orderByChild("type").equalTo("Teacher");
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,teachersQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName()+" "+model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()),model);
}
};
mRecyclerViewTeacher.setAdapter(firebaseRecyclerAdapter);
}
}
and its xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecyclerViewTeacher"
android:layout_marginTop="57dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
It's one of my first questions here so I apologize if I missed something :)
Any help would be appriciated.
Solved. All I did was regenerating the SHA1 in the firebase settings, and removing the setHasFixedSize line from Schedules activity and it worked just fine.

fragment stuck - can't go to previous fragment

I have a fragment(A) , where another fragment(B) is being opened . When I press back button it just refreshes the fragment(B) instead of exiting from it and returning to fragment A.
I tried poping back the fragment A in the Activity's onBackPressed callback method but it didn't change a thing :
#Override
public void onBackPressed() {
if(B.active)
{
mFragmentManager.popBackStack( A.TAG , 0);
B.active = false;
}
}
** the active boolean is just something I added as part of the solution. It's initialized to TRUE once the fragment is instantiated.
I don't know how to commit a project!
package com.example.a;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/9.
*/
public class ActivityA extends AppCompatActivity{
#InjectView(R.id.c)
LinearLayout c;
#InjectView(R.id.btn)
TextView btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c);
ButterKnife.inject(ActivityA.this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.e, FragA.newInstance(), "A");
// fragmentTransaction.addToBackStack("A");
fragmentTransaction.commitAllowingStateLoss();
}
});
}
}
package com.example.a;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/10.
*/
public class FragA extends Fragment{
private View rootView;
public static FragA newInstance() {
return new FragA();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public FragA() {
}
#InjectView(R.id.a)
LinearLayout a;
#InjectView(R.id.btn)
TextView btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fraga,container,false);
ButterKnife.inject(this,rootView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.e, FragB.newInstance(), "B");
fragmentTransaction.addToBackStack("B");
fragmentTransaction.commitAllowingStateLoss();
}
});
return rootView;
}
}
package com.example.a;
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;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by 77930 on 2015/11/10.
*/
public class FragB extends Fragment{
private View rootView;
public static FragB newInstance() {
return new FragB();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public FragB() {
}
#InjectView(R.id.b)
LinearLayout b;
#InjectView(R.id.btn)
TextView btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragb,container,false);
ButterKnife.inject(this, rootView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStackImmediate();
}
});
return rootView;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/c"
android:background="#4b14b1"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/e"
android:layout_width="match_parent"
android:layout_height="300dp">
</FrameLayout>
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="c"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/a"
android:background="#4b14b1"
android:layout_height="match_parent">
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="A"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/b"
android:background="#4b14b1"
android:layout_height="match_parent">
<TextView
android:id="#+id/btn"
android:textColor="#ffffff"
android:textSize="100dp"
android:gravity="center"
android:text="B"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

xml layout loads but my activity doesn't respond to button clicks

I'm new at this but I already made a small app that worked the same way.
I can't see what I'm doing wrong because the code looks quiet the same as my previous app.
When I run it or debug my app it shows my layout on my emulator so it does load the page that has to be loaded but that's all it does, it doesn't listen to button clicks. I also gives me no errors.
Here's my XML code for fragment_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: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$PlaceholderFragment">
<TextView
android:text="Eventaris"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="100px"
android:textStyle="bold"
android:id="#+id/lblEventaris"
/>
<LinearLayout
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:id="#+id/login">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Gebruikersnaam"
android:id="#+id/txtGebruikersnaam"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Wachtwoord"
android:inputType="textPassword"
android:layout_below="#id/txtGebruikersnaam"
android:id="#+id/txtWachtwoord"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Inloggen"
android:id="#+id/btnInloggen"
android:layout_below="#id/txtWachtwoord"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_below="#id/login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nog geen account?"
android:gravity="center"
android:id="#+id/lblRegistratie"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registeren"
android:id="#+id/btnRegistreren"
android:layout_below="#id/lblRegistratie"/>
</RelativeLayout>
</RelativeLayout>
Here's my fragmennt activity MainFragment.Java
package com.example.arno.eventaris;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import java.sql.SQLException;
/**
* Created by Arno on 28/04/2015.
*/
public class MainFragment extends Fragment {
private OnMainFragmentInteractionListener mListener;
private View view;
public MainFragment()
{
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.fragment_main, container, false);
Button btnInloggen = (Button) view.findViewById(R.id.btnInloggen);
btnInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
inloggen();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
Button btnRegistreren = (Button) view.findViewById(R.id.btnRegistreren);
btnRegistreren.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
navigeerRegistratie();
}
});
return view;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try{
mListener = (OnMainFragmentInteractionListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + "must implement OnFragmentInteractionListener");
}
}
public void inloggen() throws SQLException {
EditText gebr=(EditText) view.findViewById(R.id.txtGebruikersnaam);
EditText wachtw=(EditText) view.findViewById(R.id.txtWachtwoord);
String gebruiker = gebr.getText().toString();
String wachtwoord = wachtw.getText().toString();
mListener.login(gebruiker, wachtwoord);
}
public void navigeerRegistratie()
{
mListener.navigeerRegistratie();
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnMainFragmentInteractionListener {
//Todo: Update argument type and name
public void login(String gebruiker, String wachtwoord) throws SQLException;
public void navigeerRegistratie();
}
}
Here is my Main Activity MainActivity.java
package com.example.arno.eventaris;
import android.app.DialogFragment;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.arno.eventaris.Database.DBAdapter;
import java.sql.SQLException;
public class MainActivity extends ActionBarActivity implements MainFragment.OnMainFragmentInteractionListener,RegistratieFragment.OnRegistratieFragmentInteractionListener{
private Cursor gebruikerCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.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);
}
#Override
public void login(String gebruiker, String wachtwoord) throws SQLException {
DBAdapter db = new DBAdapter(this);
db.open();
gebruikerCursor = db.getGebruiker(gebruiker);
if(gebruikerCursor.moveToFirst()) {
gebruikerCursor.moveToFirst();
String wwControle = gebruikerCursor.getString(gebruikerCursor.getColumnIndex("wachtwoord"));
if (wachtwoord.equals(wwControle)) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("gebruikersnaam", gebruiker);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
} else {
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Wachtwoord incorrect!");
}
}
else
{
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Gebruikersnaam incorrect!");
}
db.close();
}
#Override
public void navigeerRegistratie() {
getFragmentManager().beginTransaction().replace(R.id.container, new RegistratieFragment()).commit();
}
#Override
public void registreren(String gebruiker, String voornaam, String naam, String email, String wachtwoord, String herhaalWachtwoord) {
if(wachtwoord.equals(herhaalWachtwoord)) {
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertGebruiker(gebruiker, voornaam, naam, email, wachtwoord);
getFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit();
}
else
{
DialogFragment errorregistratie = new ErrorRegistratie();
errorregistratie.show(getFragmentManager(), "Wachtwoorden komen niet overeen!");
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And as last here is my activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame" />
Thanks in advance!
Fixed it by making a new project with the same code, had to be a problem way deeper than my code.

Android Fragments UI Design Example

I am getting error following error. give me a suggestion if you faced the same issue.
fragmentslayout\app\src\main\java\com\example\fragmentslayout\app\MainActivity.java
Error:(9, 8) error: MainActivity is not abstract and does not override abstract method Message(String) in Communicator
fragmentslayout\app\src\main\java\com\example\fragmentslayout\app\MyListFragment.java
Error:(23, 28) error: incompatible types: OnItemSelectedListener cannot be converted to Communicator
My Code:
MainActivity.java
package com.example.fragmentslayout.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity implements Communicator
{
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onRssItemSelected(String OS_Name) {
DetailFragment detailfragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail_Fragment);
if (detailfragment != null && detailfragment.isInLayout()) {
detailfragment.setText(OS_Name);
}
}
}
DetailFragment.java
package com.example.fragmentslayout.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
return view;
}
// we call this method when button from listfragment is clicked
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.display_tv);
view.setText(item);
}
}
MyListFragment.java
package com.example.fragmentslayout.app;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MyListFragment extends Fragment implements OnClickListener
{
private Communicator communicator;
Button android_btn, ios_btn, windows_btn;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.Communicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
// Initialize Views
android_btn = (Button) view.findViewById(R.id.android_btn_id);
ios_btn = (Button) view.findViewById(R.id.ios_btn_id);
windows_btn = (Button) view.findViewById(R.id.windows_btn_id);
// set on click Listeners for buttons
android_btn.setOnClickListener(this);
ios_btn.setOnClickListener(this);
windows_btn.setOnClickListener(this);
return view;
}
public interface OnItemSelectedListener {
public void Message(String OS_Name);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.android_btn_id:
updateFragment("Android");
break;
case R.id.ios_btn_id:
updateFragment("IOS");
break;
case R.id.windows_btn_id:
updateFragment("Windows");
break;
}
}
private void updateFragment(String OS_Name) {
communicator.Message(OS_Name);
}
}
Communicator Interface
package com.example.fragmentslayout.app;
public interface Communicator {
public void Message(String tutUri);
}
Layout:
activity_main.xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<fragment
android:id="#+id/list_Fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
class="com.example.fragmentslayout.app.MyListFragment" >
</fragment>
<fragment
android:id="#+id/detail_Fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
class="com.example.fragmentslayout.app.DetailFragment" >
</fragment>
</LinearLayout>
detail_fragment.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"
android:background="#FFFF99"
android:orientation="vertical"
android:padding="20dp" >
<TextView
android:id="#+id/display_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="40sp" />
</LinearLayout>
list_fragment.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"
android:background="#CCFF99"
android:orientation="vertical"
android:padding="5dp" >
<Button
android:id="#+id/android_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android" />
<Button
android:id="#+id/ios_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IOS" />
<Button
android:id="#+id/windows_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Windows" />
</LinearLayout>
Your MainActivity implements Communicator,so you must override abstract method Message(String). Just add the method Message(String) to your MainActivity.
Your MainActivity implements Communicator, is your Communicator in activity same Communicator in fragment!!,so you must override abstract method Message(String), move your code in onRssItemSelected(string) function to new message function
just add this function to mainactivity
#Override
public void Message(String OS_Name) {
DetailFragment detailfragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail_Fragment);
if (detailfragment != null && detailfragment.isInLayout()) {
detailfragment.setText(OS_Name);
}
}

Android: Error when triggering fragment from within the fragment itself

I'm trying to learn fragments on android and my code is not working.
FragmentCustomAnimations contains MainActivity.
What i want is the frame MainActivity to change when i push the button on MainActivity.
The error message on logcat is Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.FragmentCustomAnimations for onClick handler on view class android.widget.Button with id 'button1'
Eventhough there is no function sendmessage in all my file.
FYI, its working when i put the button on FragmentCustomAnimations.
Is it impossible to use the button on fragment to trigger action to change the fragment itself?
Here is the code:
FragmentCustomAnimations.java
package com.example.myfirstapp;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentCustomAnimations extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_stack);
if (savedInstanceState == null) {
Fragment newFragment = InitialFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public static class InitialFragment extends Fragment {
static InitialFragment newInstance() {
InitialFragment f = new InitialFragment();
Bundle args = new Bundle();
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
return v;
}
}
}
fragment_stack.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:background="#drawable/window2x"
android:layout_width="match_parent" android:layout_height="match_parent">
<FrameLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
MainActivity.java
package com.example.myfirstapp;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button inner = (Button) findViewById(R.id.button1);
inner.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
getActionBar().setDisplayShowHomeEnabled(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onClick(View v) {
addFragmentToStack();
}
void addFragmentToStack() {
Fragment newFragment = CountingFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
R.animator.fragment_slide_left_exit,
R.animator.fragment_slide_right_enter,
R.animator.fragment_slide_right_exit);
ft.replace(R.id.simple_fragment, newFragment);
ft.addToBackStack(null);
ft.commit();
}
public static class CountingFragment extends Fragment {
static CountingFragment newInstance() {
CountingFragment f = new CountingFragment();
Bundle args = new Bundle();
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_display_message, container, false);
return v;
}
}
}
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"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="?android:attr/actionBarSize"
android:layout_gravity="center_vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edit_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_message"
android:layout_gravity="center_vertical"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/editTextEmail"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/editTextPassword"
android:inputType="textPassword" />
<Button
android:id="#+id/button1"
style="#style/CodeFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#drawable/custom_button"
android:text="#string/button_send" />
</LinearLayout>

Categories

Resources