IllegalArgumentException Fragment in a Dialog - java

I have a problem with a Fragment.
There is a Dialog inside a Fragment, and a Fragment inside this Dialog.
But when I add the second Fragment, there is an IllegalArgumentException : No view found for id ***** (fr.*****:id/container_list_collections) for fragment FragmentCollectionVignette.
FragmentHP.java
public class FragmentHP extends Fragment {
/** Bouton Ajouter à **/
private Button btAddTo;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
View vueFragmentHP = inflater.inflate(R.layout.fragment_hp, container, false);
getFragmentManager().beginTransaction().replace(R.id.container_dernier_ajout, new FragmentDerniersAjoutsHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_collections, new FragmentCollectionsHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_ebooks, new FragmentEbooksHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_games, new FragmentGamesHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_software, new FragmentSoftwareHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_digital_creation, new FragmentDigitalCreationHP()).commit();
btAddTo = (Button) vueFragmentHP.findViewById(R.id.bt_collections);
btAddTo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_add_to, null);
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
dialog.setCanceledOnTouchOutside(false);
Button btValider = (Button) view.findViewById(R.id.bt_add_to);
getFragmentManager().beginTransaction().add(R.id.container_list_collections, new FragmentCollectionVignette()).commit();
}
});
return vueFragmentHP;
}
}
dialog_add_to.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_add_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_to"/>
<TextView
android:id="#+id/tv_choose_collection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/choose_collection"
android:layout_below="#id/tv_add_to"/>
<FrameLayout
android:id="#+id/container_list_collections"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_choose_collection"/>
<Button
android:id="#+id/bt_add_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/valider"
android:layout_below="#id/container_list_collections"/>
</RelativeLayout>
What is the problem ?
(Sorry for my very bad english)

i think the problem is in this line
getFragmentManager()
.beginTransaction()
.add(R.id.container_list_collections, new FragmentCollectionVignette())
.commit();
change this to
this.getActivity()
.getFragmentManager()
.beginTransaction()
.add(R.id.container_list_collections, new FragmentCollectionVignette())
.commit()

Related

How can i call fragment to activity?

I created a progress dialog into a fragment by using this effect. Now i must call it in different activities. When I call the effect the buttons at the background must not work. How can I do that?
First i need to learn how to call the fragment in a different activity. Then i must make the buttons at the background unclickable but there are many of them so ‘setclickabla(false)’ would be a tiring choice.
Progress Dialog 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ProgressDialogFragment">
<com.skyfishjy.library.RippleBackground
android:id="#+id/ProgressDialogs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CB000000"
app:rb_color="#80FFFFFF"
app:rb_duration="2500"
app:rb_radius="32dp"
app:rb_rippleAmount="4"
app:rb_scale="6">
<ImageView
android:id="#+id/centerImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/logo" />
</com.skyfishjy.library.RippleBackground>
ProgressDialogFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_progress_dialog, container, false);
RippleBackground rippleBackground = (RippleBackground)view.findViewById(R.id.ProgressDialogs);
rippleBackground.startRippleAnimation();
return view;
}
For the buttons at the background to respond to clicks, you have to implement the onClick listener of the various buttons.
<com.skyfishjy.library.RippleBackground
android:id="#+id/ProgressDialogs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CB000000"
app:rb_color="#80FFFFFF"
app:rb_duration="2500"
app:rb_radius="32dp"
app:rb_rippleAmount="4"
app:rb_scale="6">
<Button
android:id="#+id/centerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/logo" />
In your layout above, you are making use of ImageView which I changed to centerButton and you can make it respond to clicks this way:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_progress_dialog, container, false);
RippleBackground rippleBackground = (RippleBackground)view.findViewById(R.id.ProgressDialogs);
rippleBackground.startRippleAnimation();
Button button=(Button)view.findViewById(R.id.centerButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// your respond to clicks
}
});
return view;
}
Call your fragment from your activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment fragment = new MainFragment(); // your fragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
}

onClick not working in fragment. (using imageview as a button)

I want to implement onclick in my fragment to change fragment.
Here is this function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
super.onViewCreated(view, savedInstanceState);
imageView9 = (ImageView)view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
It's 'clicking' cause I hear the typical button sound. But i'm getting this error when clicks:
ssl=0xaf840c00 cert_verify_callback x509_store_ctx=0xa17d2280 arg=0x0
ssl=0xaf840c00 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
Here is my main_activity layout:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarInner"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:id="#+id/content_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#212"
android:layout_below="#+id/toolbar_app_bar_layout">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:id="#+id/toolbar_app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/top_points_bar" />
</LinearLayout>
<android.support.design.widget.TabLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
app:tabMode="scrollable"
app:paddingStart="16dp"
app:tabPaddingStart="16dp"
app:tabPaddingEnd="16dp"
app:tabMinWidth="96dp"
app:tabGravity="center" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<android.support.design.widget.NavigationView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="#color/md_brown_100"
app:menu="#menu/menu_drawer"
android:textColor="#color/okurwa"
app:theme="#style/MyTabStyle"
app:headerLayout="#layout/nav_drawer_header"
app:itemTextAppearance="#style/MyTabTextStyle"
android:clipToPadding="false">
<TextView
android:id="#+id/nav_drawer_wallet_id"
android:layout_width="177dp"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginTop="8dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="8dp"/>
<TextView
android:id="#+id/nav_drawer_total_credits"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="200dp"
android:layout_marginLeft="16dp" />
<TextView
android:id="#+id/nav_drawer_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="22sp"
android:layout_marginTop="150dp"/>
<!--<FrameLayout-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_gravity="bottom"-->
<!--android:background="#color/md_white_1000"-->
<!--android:elevation="4dp"-->
<!--android:layout_marginBottom="-96dp">-->
<!--<Button android:id="#+id/navigation_button_footer"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text=""-->
<!--android:textSize="13sp"-->
<!--android:textColor="#color/md_grey_800"-->
<!--android:lines="3"-->
<!--android:gravity="center"-->
<!--style="#style/Widget.AppCompat.ActionButton"-->
<!--android:paddingTop="20dp"-->
<!--android:paddingLeft="20dp"-->
<!--android:paddingRight="20dp"-->
<!--android:paddingBottom="20dp"/>-->
<!--</FrameLayout>-->
</android.support.design.widget.NavigationView>
<RelativeLayout
android:id="#+id/lay_connection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/actmain_margintop"
android:background="#3c3c3c"
android:visibility="gone" >
<TextView
android:id="#+id/text_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="#string/error_no_internet"
android:textColor="#color/md_white_1000"
android:textSize="#dimen/twentyfive" />
<RelativeLayout
android:id="#+id/lay_dialog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progressBar1"
android:layout_centerHorizontal="true"
android:text="#string/error_no_internet"
android:textColor="#color/md_white_1000"
android:textSize="#dimen/twentyfive" />
</RelativeLayout>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Please help me guys! I see this error first time. I don't know why I'm getting this error and why it's not working. Thanks Stack's Community!
EDIT
This is full code of this fragment:
/**
* Created by otsma on 12.12.2016.
*/
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
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.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import com.commonutility.PreferenceConnector;
import com.justfashion.R;
import java.util.Random;
public class OneFragment extends Fragment {
final Random rnd = new Random();
public OneFragment() {
// Required empty public constructor
}
private static TextView creditWallet;
private String[] myString;
private static final Random rgenerator = new Random();
private TextView firstName, textView13,textView14,textView15,textView16,textView17,textView18;
private Animation animShake, wbijam, load1, load2, load3, load4, load5, load6, wbijam1, wbijam2, wbijam3, wbijam4, wbijam5;
private ImageView img, imageView9,imageView19,imageView4,imageView5,imageView6,imageView7,imageView8;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public static void onUpdateView(Context aiContext) {
// TODO Auto-generated method stub
if (aiContext != null && creditWallet != null)
creditWallet.setText(PreferenceConnector.readInteger(aiContext, PreferenceConnector.WALLETPOINTS, 0) + "");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
imageView9 = (ImageView) view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
img = (ImageView)view.findViewById(R.id.imgRandom);
imageView4 = (ImageView)view.findViewById(R.id.imageView4);
imageView5 = (ImageView)view.findViewById(R.id.imageView5);
imageView6 = (ImageView)view.findViewById(R.id.imageView6);
imageView7 = (ImageView)view.findViewById(R.id.imageView7);
imageView8 = (ImageView)view.findViewById(R.id.imageView8);
firstName = (TextView)view.findViewById(R.id.imie);
textView13 = (TextView)view.findViewById(R.id.textView13);
textView14 = (TextView)view.findViewById(R.id.textView15);
textView15 = (TextView)view.findViewById(R.id.textView16);
textView16 = (TextView)view.findViewById(R.id.textView17);
textView17 = (TextView)view.findViewById(R.id.textView18);
textView18 = (TextView)view.findViewById(R.id.textView19);
final Animation wbijam = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView13.startAnimation(wbijam);
final Animation wbijam1 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView14.startAnimation(wbijam1);
final Animation wbijam2 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView15.startAnimation(wbijam2);
final Animation wbijam3 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView16.startAnimation(wbijam3);
final Animation wbijam4 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView17.startAnimation(wbijam4);
final Animation wbijam5 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView18.startAnimation(wbijam5);
final Animation animShake = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.shak);
img.startAnimation(animShake);
final Animation load2 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load2);
imageView4.startAnimation(load2);
final Animation load3 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load3);
imageView5.startAnimation(load3);
final Animation load4 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load4);
imageView6.startAnimation(load4);
final Animation load5 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load5);
imageView7.startAnimation(load5);
final Animation load6 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load6);
imageView8.startAnimation(load6);
firstName.setText("Hey,"+" " +PreferenceConnector.readString(getActivity().getApplicationContext(), PreferenceConnector.FIRST_NAME, ""));
// Inflate the layout for this fragment
final ImageView img = (ImageView) view.findViewById(R.id.imgRandom);
// return view;
// ^^^^ error remove it
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(q);
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(9);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getActivity().getApplicationContext())
));
return view;
// ^^^ move it here
}
// I have 3 images named img_0 to img_2, so...
protected final static int getResourceID
(final String resName, final String resType, final Context ctx) {
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0) {
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
} else {
return ResourceID;
}
}
}
remove super.onViewCreated(view, savedInstanceState);
return your view
please return the view
retun view;
if the problem still persists
To Make Sure whether the problem is with Onclick or not, comment
Everything inside the onclick method and put a Toast inside it. so, i
think we could get a clear picture about the problem..
try this !!
replace the following line:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
to this:
android.app.FragmentTransaction transaction = getActivity().getFragmentManager().beginTransaction();
Also don't forget to return view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
super.onViewCreated(view, savedInstanceState);
imageView9 = (ImageView)view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
return view;
}
your fragment and fragment manager should be of same type.so either import
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
OR
import android.app.Fragment;
import android.app.FragmentTransaction;
java file
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
imageView9 = (ImageView) view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, newFragment)
.addToBackStack(null)
.commit();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
// your other contents.....
return view;
}
You better implement Interface for click event like this
public class fragment_test extends Fragment implements View.OnClickListener {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
switch (v.getItemId()) {
case R.id.action_zoom_in:
// .....
break;
}
return true;
}
}
}

onClick not working in Fragment

Basically I have listview in my fragment layout. And another layout called item_todo.xml which contains my button.
The onClick() wasn't working while clicking the delete_task button in my layout.
It would be great if you could help me out !
Here is my Class ToDoFragment
public class ToDoFragment extends Fragment {
private static final String TAG = "MainActivity";
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
Button myButton;
FloatingActionButton btnadd;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mHelper = new TaskDbHelper(getActivity());
mTaskListView = (ListView) view.findViewById(R.id.list_todo);
//Floating action button
btnadd = (FloatingActionButton) view.findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText taskEditText = new EditText(getActivity());
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
});
updateUI();
return view;
}
#Override
public void onActivityCreated(Bundle saved){
super.onActivityCreated(saved);
final LayoutInflater factory = getActivity().getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.item_todo, null);
myButton = (Button) textEntryView.findViewById(R.id.task_delete);
myButton.setOnClickListener(new View.OnClickListener() {
// OnClick() Not Working !!
#Override
public void onClick(View view) {
deleteTask(view);
}
});
}
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE,
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{task});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(getActivity(),
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}}
Fragment_two XML
<ListView
android:id="#+id/list_todo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:id="#+id/btnadd"
android:layout_height="50dp"
app:fabSize="normal"
android:clickable="true"
android:src="#drawable/red"
android:scaleType="center"
/>
</LinearLayout>
</RelativeLayout>
item_todo XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical">
<TextView
android:id="#+id/task_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Hello"
android:textSize="20sp" />
<Button
android:id="#+id/task_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="Done" />
</RelativeLayout>
You inflate a new View in your onActivityCreated But you never used that view !!! myButton refer to a button which its view has not been used !
Edit :
There are lots of ways you can reach your goal:
Interfaces
You can initialize an interface and pass it to fragment, so whenever something happen in your activity (button click for example), you will understand
BroadcastReceivers
You can register local broadcast receivers in your fragment and when user click on the button, you send that broadcast, so fragment will understand
i suggest the second one and using EVENTBUS library

How to customize title in DialogFragment

I want to customize my title in my DialogFragment, I know how to How to set the title to my DialogFragment , but I want more not just a title , I need a customized title(color,fontSize ...), So I defined a TextView and customized it
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.height_fragment,container,false);
TextView title = new TextView(getContext());
title.setText("Your Height Information");
title.setGravity(Gravity.CENTER);
title.setTextSize(30);
title.setBackgroundColor(Color.GRAY);
title.setTextColor(Color.WHITE);
getDialog().setCustomTitle(title); //Error Can not resolve method setCustomTitle(android.widget.TextView)
return view;
}
but there is an error on this line
getDialog().setCustomTitle(title);
getDialog().setCustomTitle(title);
I searched a lot before posting this question but I couldn't find how can I customize my title of DialogFragment.
Thank you for taking time to help me
"getDialog" does not have a method "setCustomTitle".This method can only be used for AlertDialog.Builder. Try it like this:
getDialog().setTitle("Your Height Information");
TextView textView=(TextView) getDialog().findViewById(android.R.id.title);
textView.setTextSize(30);
I never could easily customize the Title of my DialogFragment. So, instead, I use to remove the title and add a TextView to Dialog layout (and use it like a Title). This way, you can customize how you want and easily.
Dialog Code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Remove TITLE
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
View dialogView = dialogView = inflater.inflate(R.layout.height_fragment, null);
// Do your stuff
return dialogView;
}
height_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="56dp"
<!-- THIS VIEW IS YOUR TITLE... CUSTOMIZE LYKE YOU WANT -->
android:textColor="#color/white"
android:textSize="18sp"
android:textStyle="bold"
android:layout_gravity="top"
android:text="#string/TITLE"
android:gravity="center_vertical"
android:paddingLeft="16dp" />
<!-- Real Content goes below the title -->
</FrameLayout>
You need to connect your xml to your class. findViewById tells your class which TextView to use. Notice how it must match the android:id in the xml:
public class DialogFragmentTest extends DialogFragment {
public final static String TITLE = "title";
public final static String MESSAGE = "message";
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(view);
Bundle args = getArguments();
String title = args.getString(TITLE, "default title");
String msg = args.getString(MESSAGE, "default message");
TextView tvTitle = (TextView)view.findViewById(R.id.dialog_title);
tvTitle.setText(title);
TextView tvMessage = (TextView)view.findViewById(R.id.dialog_message);
tvMessage.setText(msg);
Button btnDone = (Button)view.findViewById(R.id.dialog_button);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return builder.create();
}
}
dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="300dp"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="title"/>
<TextView
android:id="#+id/dialog_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/dialog_title"
android:layout_marginTop="10dp"
android:text="message"/>
<Button
android:id="#+id/dialog_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/dialog_message"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:text="done"/>
</RelativeLayout>
This is then called from your activity with:
DialogFragmentTest bd = new DialogFragmentTest();
Bundle b = new Bundle();
b.putString(DialogFragmentTest.TITLE, "my title");
b.putString(DialogFragmentTest.MESSAGE, "my message");
bd.setArguments(b);
bd.show(getFragmentManager(), "my title");
Please, use custom dialog, based on DialogFragment:
public class MyCustomDialog extends DialogFragment{
private Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View dialogView = inflater.inflate(R.layout.custom_dialog, null, false);
TextView tvTitle = (TextView) getDialog().findViewById(android.R.id.title);
tvTitle.setTextSize(25);
tvTitle.setTextColor(Color.GREEN);
return dialogView;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(this.context, R.style.CustomDialog);
dialog.setTitle("custom dialog title");
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
return dialog;
}
public static MyCustomDialog newInstance() {
MyCustomDialog myCustomDialog = new MyCustomDialog();
return myCustomDialog;
}
}

DialogFragment: button.setOnClickListener throws NullPointerException

I have an Activity with a button like this:
<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=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="onButtonClickListener"
android:text="Show Fragment" />
</RelativeLayout>
And my onButtonClickListener method from xml is(here I create the DialogFragment and set onClickListener for a clear button from dialog):
public void onButtonClickListener(View view) {
FragmentManager fm = getFragmentManager();
MyDialogFragment dialogFragment = new MyDialogFragment ();
dialogFragment.show(fm, "Sample Fragment");
final EditText messageText = (EditText) findViewById(R.id.editText);
Button clearButton = (Button) findViewById(R.id.button_clear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messageText.setText(null);
}
});
}
My problem is that when DialogFragment shows it throws NullPointerException:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.cristi.dialogfragmenttest2.MainActivity.onButtonClickListener(MainActivity.java:51)
At this line of code: clearButton.setOnClickListener(new View.OnClickListener() {
My xml for DialogFragment is:
<?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">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:maxLength="200" />
<Button
android:id="#+id/button_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true" />
</RelativeLayout>
What could be the problem with the setOnClickListener? Why does it says that my button from DialogFragment is null?
Any reference or advice is welcome! Thanks in advance!
Edit:
-MyDialogFragment code:
public class MyDialogFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog_fragment, container, false);
getDialog().setTitle("Enter message");
return rootView;
}
You must have refernece to the root view where is your button button_clear, then call rootView.findViewById(...) to get the button reference...
Solution:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog_fragment, container, false);
getDialog().setTitle("Enter message");
Button clearButton = (Button) rootView.findViewById(R.id.button_clear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messageText.setText(null);
}
});
return rootView;
}

Categories