I have a MainActivity initially empty with an action bar. Clicking on the "plus" in the action bar,I open a DialogFragment with an EditText and two buttons, "cancel" and "continue". I can not post a picture because I do not have enough reputation, but when I click on "continue" I create two buttons; one positioned at the top right of the layout of MainActivity and the other, just below the previous one, on the left. What I would like is that every time I click on "continue", I can create two buttons positioned according to the same pattern that I explained earlier.
This is the code I've written but it does not work as I would like.
MainActivity
public class MainActivity extends FragmentActivity implements IProjectDialFrag {
private ProjectDialogFragment projectDialFrag = new ProjectDialogFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
//TODO
return true;
case R.id.filters:
Intent intent1 = new Intent(MainActivity.this, FiltersActivity.class);
startActivity(intent1);
return true;
case R.id.action_new:
return true;
case R.id.add_button:
Intent intent2 = new Intent(MainActivity.this, ButtonsActivity.class);
startActivity(intent2);
return true;
case R.id.add_project:
projectDialFrag.show(getFragmentManager(), "projectDialog");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
return;
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText editText = (EditText) dialog.getDialog().findViewById(R.id.project_name);
String projectName = editText.getText().toString();
Button projectButton = new Button(this);
projectButton.setText(projectName);
ImageButton playButton = new ImageButton(this);
playButton.setImageResource(R.drawable.ic_action_play_over_video);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.button_row);
linearLayout.addView(projectButton);
linearLayout.addView(playButton);
}
}
The Interface
public interface IProjectDialFrag {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
And the DialogFragment
public class ProjectDialogFragment extends DialogFragment {
private IProjectDialFrag iProjDialFrag;
#SuppressLint("InflateParams")
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder createProjectAlert = new AlertDialog.Builder(getActivity());
createProjectAlert.setTitle("Create Project");
LayoutInflater inflater = getActivity().getLayoutInflater();
createProjectAlert.setView(inflater.inflate(R.layout.project_dialog_fragment, null))
.setPositiveButton(R.string.conti_nue, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
iProjDialFrag.onDialogPositiveClick(ProjectDialogFragment.this);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
iProjDialFrag.onDialogNegativeClick(ProjectDialogFragment.this);
}
});
return createProjectAlert.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
iProjDialFrag = (IProjectDialFrag) activity;
}
}
The layout of MainActivity
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/button_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" >
</LinearLayout>
</RelativeLayout>
If you need a screenshot, please give me a point reputation and I'll place it immediately. Than you
Thank you again. Here is my screenshot:
This is the result I'd like to have:
For each Button I have to be able to add more "play".
But see your layout.
Your linear layout is "wrap_conent" on the width.
Also your linear layout is glued to the right side of parent.
So that is exactly what you will be getting... all the linear layout content glued to the right side and taking exaclty size of it's content... Well Button. You are getting what you told Android to get.
If you want to get what you drawn, then 1st your linear layout for button shoul be match_parent in widht, and you can set it's gravity to left for play buttons and to right for CIAO and LUCA buttons...
<LinearLayout
...
android:layout_width="wrap_content"
... >
in MainActivity layout should change to
<LinearLayout
...
android:layout_width="fill_parent"
... >
and add these lines
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT) <---
lp.gravity = Gravity.RIGHT; <---
Button projectButton = new Button(this);
projectButton.setText(projectName);
projectButton.setLayoutParams(lp); <---
lp.gravity = Gravity.LEFT; <---
ImageButton playButton = new ImageButton(this);
playButton.setImageResource(R.drawable.ic_action_play_over_video);
playButton.setLayoutParams(lp); <---
#udiboy1209
I simply refactor your code as I show below:
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText editText = (EditText) dialog.getDialog().findViewById(R.id.project_name);
String projectName = editText.getText().toString();
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp1.gravity = Gravity.END;
Button projectButton = new Button(this);
projectButton.setText(projectName);
projectButton.setLayoutParams(lp1);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.gravity = Gravity.START;
Button playButton = new Button(this);
playButton.setBackgroundResource(R.drawable.play_button_green);
playButton.setLayoutParams(lp2);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.button_row);
linearLayout.addView(projectButton);
linearLayout.addView(playButton);
}
Related
I am building a quiz app that has two types of questionnaires. I have a DialogAlert that allows the user to choose which questionnaire (two options: either "history" or "chemistry") they want to complete and have the results display in a fragment.
My goal is to be able to display the textview ("history" or "chemistry") that the questionnaire they selected in the result fragment.
I have a Dialog class:
public class DialogAlert extends DialogFragment {
private Context context;
String selection;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] items = {"History", "Chemistry"};
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Select a topic to complete")
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selection = items[which];
}
})
// Set the action buttons
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
switch (selection)
{
case("History"):
Intent intent_hist = new Intent(getActivity(), historyquestions.class);
startActivity(intent_hist);
break;
case("Chemistry"):
Intent intent_chem = new Intent(getActivity(), chemistryquestions.class);
startActivity(intent_chem);
break;
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(), "No topic was selected", Toast.LENGTH_SHORT)
.show();
dialog.cancel();
}
});
return builder.create();
}
My Result fragment in which I have a placeholder textview that I want to display what the user had selected (either history or chemistry) based on the positive/ negative button above:
public class homeFragment extends Fragment{
TextView topic
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_home, container, false);
topic = (TextView) layoutView.findViewById(R.id.topic);
return layoutView;
}
}
How should I approach this? The challenge is that the result is shown in one of the fragments and I am unsure how would I "pass" what the user had selected in the Dialog to the Result fragment. Can someone please help?
Thank you in advance!
*Edit with the home fragment Id
<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=".ui.home.homeFragment">
<FrameLayout
android:id="#+id/home_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<LinearLayout
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginStart="10dp"
android:layout_marginTop="270dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/layout_bg"
android:orientation="vertical"
android:weightSum="300">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="10"
android:fontFamily="#font/inter_regular"
android:text="Selection of topic"
android:textColor="#000000"
android:textSize="22sp" />
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/topic"
android:layout_width="340dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:fontFamily="#font/inter_regular"
android:text="Topic"
android:textColor="#000000"
android:textSize="20sp" />
</TableRow>
</LinearLayout>
</FrameLayout>
Edit 2023-02-13
HomeViewModel class:
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class HomeViewModel extends ViewModel {
private final MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is a home fragment");
}
// getText method
public LiveData<String> getText() {
return mText;
}
// function to update the mText value
public void setText(String updateText) {
mText.setValue(updateText);
}
}
homeFragment class:
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.annotation.Nullable;
public class homeFragment extends Fragment{
private HomeViewModel homeViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_home, container, false);
homeViewModel =
ViewModelProviders.of(requireActivity()).get(HomeViewModel.class);
final TextView topic = (TextView)layoutView.findViewById(R.id.topic);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
topic.setText(s);
}
});
return layoutView;
}
Dialog class:
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProviders;
import com.example.quizzApp.MainActivity;
import com.example.quizzApp.ui.home.HomeViewModel;
public class DialogAlert extends DialogFragment {
private Context context;
String selection;
private HomeViewModel model;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = ViewModelProviders.of(requireActivity()).get(HomeViewModel.class);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] items = {"History", "Chemistry"};
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
// Set the dialog title
builder.setTitle("Select a topic to complete")
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selection = items[which];
}
})
// Set the action buttons
// User clicked OK, so save the selectedItems results somewhere
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
switch (selection)
{
case("History"):
model.setText("History");
Intent intent_hist = new Intent(getActivity(), MainActivity.class);
startActivity(intent_hist);
break;
case("Chemistry"):
model.setText("Chemistry");
Intent intent_chem = new Intent(getActivity(), MainActivity.class);
startActivity(intent_chem);
break;
}
}
})
// or return them to the component that opened the dialog
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(), "No topic was selected", Toast.LENGTH_SHORT)
.show();
dialog.cancel();
}
});
return builder.create();
}
Scenario
You have created an App with Bottom Navigation Activity template. There should be 3 tabs Home, Dashboard, Notifications. And somehow you have opened a DialogFragment and that allows you to choose between History or Chemistry as the topic. And upon selecting either one and press OK, your Home fragment should display the topic selected.
Possible solution
If you are using Bottom Navigation Activity template, there should be a HomeViewModel class. You can make use of this HomeViewModel class, share it among different Fragments, and update the view accordingly.
HomeFragment class:
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private Button btnDialog;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// Please notice the below line, getting ViewModel using the below method can ensure
// the model can be shared across different Fragments
homeViewModel =
ViewModelProviders.of(requireActivity()).get(HomeViewModel.class);
// new ViewModelProvider(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
// You have registered the ViewModel to change your HomeFragment TextView. So if the value
// of mText has been updated, the TextView in HomeFragment will also be updated
// accordingly.
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
// This btnDialog is just my testing button, it is a button to open your mentioned
// DialogFragment. So you can ignore this button and the openDialog(View) function.
btnDialog = root.findViewById(R.id.btnDialog);
btnDialog.setOnClickListener(this::openDialog);
return root;
}
// As mentioned above, this function can be ignored
public void openDialog(View v) {
DialogAlert frag = new DialogAlert();
frag.show(getChildFragmentManager(), "DialogAlert");
}
}
HomeViewModel class:
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is home fragment");
}
public LiveData<String> getText() {
return mText;
}
// You need to add a function so that you can update mText value
public void setText(String updateText) {
mText.setValue(updateText);
}
}
DialogAlert class:
public class DialogAlert extends DialogFragment {
private Context context;
String selection;
// Define a variable to hold the ViewModel class
private HomeViewModel model;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the HomeViewModel so that we can update the value of mText and sync to view in
// HomeFragment
model = ViewModelProviders.of(requireActivity()).get(HomeViewModel.class);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] items = {"History", "Chemistry"};
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Select a topic to complete")
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selection = items[which];
}
})
// Set the action buttons
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
switch (selection) {
case ("History"):
// Magic line, it will trigger the onChanged() in HomeFragment
model.setText("History");
dialog.dismiss();
break;
case ("Chemistry"):
// Magic line, it will trigger the onChanged() in HomeFragment
model.setText("Chemistry");
dialog.dismiss();
break;
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(), "No topic was selected", Toast.LENGTH_SHORT)
.show();
dialog.cancel();
}
});
return builder.create();
}
}
With the above code, after you have selected the option in DialogFragment, your HomeFragment TextView should be updated at once.
Misconception
Regarding on the following code:
switch (selection)
{
case("History"):
Intent intent_hist = new Intent(getActivity(), historyquestions.class);
startActivity(intent_hist);
break;
case("Chemistry"):
Intent intent_chem = new Intent(getActivity(), chemistryquestions.class);
startActivity(intent_chem);
break;
}
The above code will start an Activity to either historyquestions Activity or chemistryquestions Activity (if you have properly created these Activity), instead of proceeding to your result homeFragment Fragment.
Additional Note
It is a good practice to follow Java naming conventions when you name classes. For example:
homeFragment should be named as HomeFragment
historyquestions should be named as HistoryQuestions
I want to create a custom dialog with a recycler view on it. If I choose the recycler view cell and press ok button in dialog, then the textview will change. I created recycler view adapter, custom dialog, but I don't know how to connect dialog and adapter and what to put in onClick function..help me please..
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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/writing_dialog"
android:layout_width="match_parent"
android:layout_height="400dp">
<TextView
android:id="#+id/textView8"
android:layout_width="0dp"
android:layout_height="50dp"
android:fontFamily="#font/nexon"
android:text="choose!"
android:textAlignment="center"
android:gravity="center"
android:textColor="#341867"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/writing_dialog_ok"
android:layout_width="65dp"
android:layout_height="39dp"
android:layout_marginEnd="20dp"
android:background="#00FFFFFF"
android:fontFamily="#font/nexon"
android:text="ok"
android:textColor="#341867"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<Button
android:id="#+id/writing_dialog_cancel"
android:layout_width="65dp"
android:layout_height="39dp"
android:layout_marginEnd="30dp"
android:background="#00FFFFFF"
android:text="cancel"
android:textColor="#341867"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/writing_dialog_ok"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="355dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/writing_dialog_recy"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="20dp"
app:layout_constraintBottom_toTopOf="#+id/guideline6"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView8" />
</androidx.constraintlayout.widget.ConstraintLayout>
recyclerview cell
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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/dialog_container"
android:layout_width="match_parent"
android:layout_height="45dp">
<RadioButton
android:id="#+id/dialog_radio"
android:layout_width="0dp"
android:layout_height="45dp"
android:fontFamily="#font/nexon"
android:text="시리즈 1"
android:textSize="18dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
recycler view adapter
public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder>{
private Context context;
private ArrayList<WritingNovel_data> dataList;
public WritingNovelAdapter(Context context, ArrayList<WritingNovel_data> dataList){
this.context = context;
this.dataList = dataList;
}
public static class Holder extends RecyclerView.ViewHolder{
protected ConstraintLayout dialog_container;
protected RadioButton dialog_radio;
public Holder(View view){
super(view);
this.dialog_container = view.findViewById(R.id.dialog_container);
this.dialog_radio = view.findViewById(R.id.dialog_radio);
}
}
#Override
public WritingNovelAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.writing_dialog_cell, parent, false);
Holder holder = new WritingNovelAdapter.Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull WritingNovelAdapter.Holder holder, final int position) {
String title = dataList.get(position).title;
if(title.length() > 16){
title = title.substring(0, 15) + "…";
}
holder.dialog_radio.setText(title);
holder.dialog_container.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
//????????????????????????????
}
});
}
#Override
public int getItemCount() {
if(dataList == null){
return 0;
}
else{
return dataList.size();
}
}
}
custom dialog class
class CustomDialog {
private Context context;
public CustomDialog(Context context)
{
this.context = context;
}
public void callDialog()
{
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.writing_novel_series_dialog);
dialog.show();
final RecyclerView writing_dialog_recy = dialog.findViewById(R.id.writing_dialog_recy);
final Button writing_dialog_ok = dialog.findViewById(R.id.writing_dialog_ok);
final Button writing_dialog_cancel = dialog.findViewById(R.id.writing_dialog_cancel);
writing_dialog_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
writing_dialog_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}
====EDIT-1====
I call my dialog in here!
public class writing_novel extends AppCompatActivity {
private static final int GALLERY_REQUEST = 979;
private RichEditor mEditor;
private ColorPicker colorPicker;
androidx.appcompat.app.AlertDialog.Builder textSizeDialogBuilder;
private NumberPicker textPicker;
androidx.appcompat.app.AlertDialog.Builder youtubeDialogBuilder;
private EditText etYoutubeUrl;
private Button writing_novel_btn_series;
private ImageButton writing_novel_novel_ibtn_next;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:{
finish();
return true;
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_writing_novel);
Toolbar toolbar = findViewById(R.id.writing_novel_main_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
writing_novel_novel_ibtn_next = findViewById(R.id.writing_novel_novel_ibtn_next);
writing_novel_novel_ibtn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(writing_novel.this);
builder.setTitle("정말 다음으로 넘어가시겠습니까?").setMessage("다음으로 넘어가기전, 한번 더 검토해주세요.");
builder.setPositiveButton("넘어가기", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(getApplicationContext(), "OK Click", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(writing_novel.this, decide_novel_title.class);
startActivity(intent);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(getApplicationContext(), "Cancel Click", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.setCancelable(false);
builder.create().show();
}
});
writing_novel_btn_series = findViewById(R.id.writing_novel_btn_series);
writing_novel_btn_series.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args = new Bundle();
args.putString("id", "");
DialogFragment dialogFragment = new DialogFragment();
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "id");
CustomDialog dialog = new CustomDialog(writing_novel.this);
dialog.show(getSupportFragmentManager(), "CustomDialog");
}
});
If I understand correctly, you are trying to figure out how to display the RecyclerView list of items, and when an item is clicked, show its data in a TextView below. Please correct me if I am wrong.
For the first step, you are close. All you need to do is instantiate a new layout manager and an instance of your adapter class, and pass them to your RecyclerView.
Add this to your CustomDialog class:
public void callDialog() {
...
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
writing_dialog_recy.setLayoutManager(layoutManager);
// I'm assumming you are passing a list of data here
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList);
writing_dialog_recy.setAdapter(adapter);
...
As for showing the text in the textView, you have a few different ways to implement this. Its hard to say without seeing the rest of the related code, but I would recommend implementing a callback interface and calling the method from your ViewHolder, like so:
Define the interface in your Adapter class
public interface CallbackInterface {
void showText(String text);
}
Implement a callback interface in your CustomDialog class and implement the setText method, which is where you will set the text in the TextView. This will require that you have an instance of the TextView that you want to show that text in, meaning you must call this somewhere: TextView textView = findViewById(R.id.textView8);
class CustomDialog implements CallbackInterface {
...
public void showText(String text) {
textView.setText(text);
}
}
Pass an instance of your CustomDialog to the adapter (make sure to redefine adapter constructor to accept an instance of CustomDialog
public void callDialog() {
...
// I'm assumming you are passing a list of data here
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList, this);
writing_dialog_recy.setAdapter(adapter);
...
}
Call the callback method from the adapter class when the recyclerview cell is clicked
public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder> {
private Context context;
private ArrayList<WritingNovel_data> dataList;
private CallbackInterface callbackInterface;
public WritingNovelAdapter(Context context, ArrayList<WritingNovel_data>
dataList, CallbackInterface callbackInterface){
this.context = context;
this.dataList = dataList;
this.callbackInterface = callbackInterface;
}
...
holder.dialog_container.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
callbackInterface.showText(title);
}
});
}
Edit #1
Your comment stated that your dialog is not showing up. Unless you left some code out of your CustomDialog class, this is because all your CustomDialog class is, is a Java class. You need to extend a superclass such as AlertDialog or DialogFragment. I'll do my best to summarize how to do this, but you should take a look at the android docs -> https://developer.android.com/guide/topics/ui/dialogs
Here is an example of a DialogFragment you could try creating:
public class CustomDialog extends DialogFragment implements CallbackInterface {
private Context context;
private TextView textView;
private RecyclerView writing_dialog_recy;
public CustomDialog(Context context) {
this.context = context;
}
/* This is the method which builds and essentially shows the dialog */
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate your view that contains the recyclerview
View view = inflater.inflate(R.layout.custom_dialog);
// Your text view where you want to show the text after an item is clicked
textView = view.findViewById(R.id.textView8);
// Your recyclerview in your custom_dialog.xml
writing_dialog_recy = view.findViewById(R.id.writing_dialog_recy);
// Create the layout manager
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
writing_dialog_recy.setLayoutManager(layoutManager);
// Create and set the adapter
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList, this);
writing_dialog_recy.setAdapter(adapter);
builder.setView(view);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do whatever you want when user clicks the positive button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create(); // return the dialog builder
}
public void showText(String text) {
textView.setText(text);
}
}
Then in whatever activity you are creating this dialog from, you show the DialogFragment and pass it the activity's FragmentManager and a tag
CustomDialog dialog = new CustomDialog(this);
dialog.show(getSupportFragmentManager(), "CustomDialog");
I tried this method and inflate home.xml in my HomeFragment.java:
public View onCreateView(#NonNull LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.home, container, false);
return root;
}
public void OnClickOnTransit(View v){
final Button n = (Button) v;
final String id = n.getTag().toString();
AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1);
arrayAdapter.add("Tag as On Transit");
arrayAdapter.add("Cancel");
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String strOption = arrayAdapter.getItem(which);
if(strOption.equalsIgnoreCase("Tag as On Transit"))
{
Tag_as_on_transit(id);
}
else if(strOption.equalsIgnoreCase("Cancel"))
{
//confirmViewLeveling(emp_tag[1],emp_name.getText().toString());
}
else
{
}
}
});
builderSingle.show();
}
Here is my home.xml where i put my listview.
<ListView
android:id="#+id/lv_customer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
And this is my nested_listview.xml where my button was placed.
<Button
android:id="#+id/btn_ontransit"
android:layout_width="40dip"
android:layout_height="40dip"
android:background = "#drawable/ic_local_shipping_orange_24dp"
android:textColor="#ff4500"
android:textStyle="bold"
android:text=""
android:textSize="25sp"
android:onClick="OnClickOnTransit"/>
What i want is to call OnClickOnTransit from nested_listview.xml. Thanks in advance!
In that case your parentActivity must have this method
public void OnClickOnTransit(View v){
}
However if you don't want that, You can implement like this in your fragment's onViewcreated method.
Button btn_conferma = (Button) view.findViewById(R.id.btn_conferma);
btn_conferma.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// do something
}
});
I am working on a game.I have an AlertDialog for exit the game but when i press cancle button ao alertDialog my game stop for 3 seconds and resume again. i have implement this code but the text is not visible in center of the screen.
i thing which i want is when i press cancle button 3 2 1 text show on the screen and after display 1 text is invisible and game starts again.
here's my code
public class Game extends Activity {
MediaPlayer backgroungMusic;
Toast toast;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_game);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//turn title off
requestWindowFeature(Window.FEATURE_NO_TITLE);
// set full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GamePanel(this));
backgroungMusic = MediaPlayer.create(Game.this, R.raw.music);
backgroungMusic.setLooping(true);
backgroungMusic.start();
}
#Override
protected void onPause()
{
super.onPause();
backgroungMusic.release();
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// GamePanel.thread.setStoped(true);
GamePanel.thread.setRunning(false);
// in the next line of code we also style the dialog through xml which i put in styles
AlertDialog alertDialog = new AlertDialog.Builder(this,R.style.myBackgroundStyle).create();
alertDialog.setTitle("Exit Alert");
alertDialog.setMessage("Do you really want to exit the Game?");
alertDialog.setButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Best way is firstly use finish() and after that use System.exit(0) to clear static variables. It will give you some free space.
// A lot of applications leave working processes and variables what makes me angry. After 30 minutes of using memory is full and i have to run Task Manager - Lvl 2 clear memory
finish();
System.exit(0);
return;
}
});
alertDialog.setButton2("Cancle", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// dialog.cancel();
// GamePanel.thread.resume();
// When user press the "Cancle" button then game resume for 3 seconds then start again
// dialog.dismiss();
// Here is the Code of the toasts and each toast appear with delay of one second.
final Handler handler = new Handler();
final TextView textView = (TextView) findViewById(R.id.textView123);
final java.util.concurrent.atomic.AtomicInteger n = new AtomicInteger(3);
final Runnable counter = new Runnable() {
#Override
public void run() {
if(n.getAndDecrement() >= 1 )
handler.postDelayed(this, 1000);
else {
GamePanel.thread.setRunning(true);
}
}
};
handler.postDelayed(counter, 1000);
return;
}
}
);
alertDialog.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
#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_game, 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);
}
}
And here's textview in xml layout.
<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=".Game">
<TextView
android:id="#+id/textView123"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:paddingRight="10dip"
android:textSize="50dp" />
please help me thanks!
You dont need to do dialog.dismiss();
You also have the problem that final TextView textView = (TextView) findViewById(R.id.textView123); is looking for a view on the dialog rather than on the activity where it lives, are there no erros in your Logcat? You need to be calling textView.setText at some point, but I would expect you to get a NullPointerException
What I would do is use a callback to the activity, it's best to do that by creating a DialogFragment.
public class MyDialogFragment extends DialogFragment {
public MyDialogFragment newInstance() {
MyDialogFragment fragment = new MyDialogFragment();
return fragment;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.myBackgroundStyle);
builder.setTitle("Exit Alert");
builder.setMessage("Do you really want to exit the Game?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
if (getActivity() instanceof DialogClickListener) {
((DialogClickListener) getActivity()).onPositive();
}
}
});
return builder.create();
}
}
public interface DialogClickListener {
void onPositive();
}
public class MyActivity extends Activity implements DialogClickListener {
private TextView textView; //rename this
public void onCreate(...) {
...
textView = (TextView) findViewById(R.id.textView123);
}
public void showExitDialog() {
FragmentManager fm = getSupportFragmentManager();
MyDialogFragment exitDlg = (MyDialogFragment) fm.findFragmetByTag(MyDialogFragment.TAG);
if (exitDlg != null && exitDlg.isAdded()) {
exitDlg.dismiss();
}
exitDlg = MyDialogFragment.newInstance();
exitDlg.show(fm, AddEditDialogFragment.TAG);
}
public void onPositive() {
final Handler handler = new Handler();
final java.util.concurrent.atomic.AtomicInteger n = new AtomicInteger(3);
final Runnable counter = new Runnable() {
#Override
public void run() {
if (n.getAndDecrement() >= 1 ) {
handler.postDelayed(this, 1000);
} else {
GamePanel.thread.setRunning(true);
}
textView.setText(String.valueOf(n));
}
};
handler.postDelayed(counter, 1000);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showExitDialog()
}
}
}
In a RelativeLayout you can use centerInParent:
<TextView
android:id="#+id/textView123"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:paddingRight="10dip"
android:textSize="50dp" />
I've looked at a lot of similar questions and can't seem to get anything to work. I have a main class with a function like this that edits shows a dialog box then edits a List when a button is pressed.
public class EditPlayers extends SherlockFragmentActivity {
listPlayerNames.setAdapter(new EditPlayerAdapter(ctx,
R.layout.score_row_edit_player, listScoreEdit));
public void deletePlayer(final int position) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
EditPlayers.this);
// Setting Dialog Title
alertDialog.setTitle("Delete Player");
// Setting Dialog Message
alertDialog.setMessage("Are you sure?");
// Setting Delete Button
alertDialog.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listScoreEdit.remove(position);
updateListView();
}
});
// Setting Cancel Button
alertDialog.setNeutralButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
}
How do I access that function from the getView() in the adapter? Here's the XML for the row
<TextView
android:id="#+id/nameEdit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:layout_weight="70"
android:text="Name"
android:textColor="#666666"
android:textSize="22sp"
android:textStyle="bold" >
</TextView>
<Button
android:id="#+id/deletePlayer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="Delete"
android:focusable="false" />
Here's the getView()
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = (LinearLayout) inflater.inflate(resource, null);
Score score = getItem(position);
TextView txtName = (TextView) convertView.findViewById(R.id.nameEdit);
txtName.setText(score.getName());
Button b = (Button)convertView.findViewById(R.id.deletePlayer);
b.setTag(position);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//call function here
}
});
return convertView;
}
I'm totally lost at this point so any help would be appreciated. Thanks!
I would recommend providing an interface back to your activity that lets it know when that button is pressed. I would not recommend calling an activity's method from an ArrayAdapter. It is too tightly coupled.
Try something like this:
Your Activity
public class EditPlayers extends SherlockFragmentActivity implements EditPlayerAdapterCallback {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EditPlayerAdapter adapter = new EditPlayerAdapter(this,
R.layout.score_row_edit_player, listScoreEdit);
adapter.setCallback(this);
listPlayerNames.setAdapter(adapter);
}
private void deletePlayer(final int position) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
EditPlayers.this);
// Setting Dialog Title
alertDialog.setTitle("Delete Player");
// Setting Dialog Message
alertDialog.setMessage("Are you sure?");
// Setting Delete Button
alertDialog.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listScoreEdit.remove(position);
updateListView();
}
});
// Setting Cancel Button
alertDialog.setNeutralButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void deletePressed(int position) {
deletePlayer(position);
}
}
Adapter:
public class EditPlayerAdapter extends ArrayAdapter {
private EditPlayerAdapterCallback callback;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = (LinearLayout) inflater.inflate(resource, null);
Score score = getItem(position);
TextView txtName = (TextView) convertView.findViewById(R.id.nameEdit);
txtName.setText(score.getName());
Button b = (Button)convertView.findViewById(R.id.deletePlayer);
b.setTag(position);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(callback != null) {
callback.deletePressed(position);
}
}
});
return convertView;
}
public void setCallback(EditPlayerAdapterCallback callback){
this.callback = callback;
}
public interface EditPlayerAdapterCallback {
public void deletePressed(int position);
}
}
Your EditPlayerAdapter gets a Context passed to it. Activity extends Context
If the Context passed is your EditPlayers and you store a class-scoped reference to that Context in your Adapter, you can then do:
((EditPlayers) yourContextVar).function();
Better yet, make an interface of some sort. It will help clarify and organise your code and it applies the same principle.