Seekbar is null, even though it exists - java

My goal is to access a seekbar. I tried many things, even pulling the Seekbar seekingbar before the override, but I get always the null toast. R.layout.firstLayout, R.layout.secondLayout, R.id.seekingbar, they all exist.
This is my abbreviated code
public class MainActivity extends AppCompatActivity {
SeekBar seekingbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekingbar = (SeekBar) findViewById(R.id.seekingbar);
LayoutInflater inflater = getLayoutInflater();
final View firstLayout = inflater.inflate(R.layout.firstLayout, null);
final View secondLayout = inflater.inflate(R.layout.secondLayout, null);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton("Forward", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
AlertDialog dialog2 = new AlertDialog.Builder(MainActivity.this)
.setView(secondLayout)
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (seekingbar == null)
{
Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_LONG).show();
}
}
}).create();
dialog2.show();
}
}).create();
dialog.show();
}
});
}
}
firstLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/seekbarll"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
tools:context=".MainActivity">
<SeekBar
android:id="#+id/seekingbar"
style="#style/Widget.AppCompat.SeekBar.Discrete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:min="0"
android:progress="3" />
</LinearLayout>

Try to find the seekBar in the firstLayout after declaring it:
"firstLayout.findViewById(R.id.seekbar)"

Related

androidstudio recyclerview and custom dialog

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");

How to call android:onClick on xml button under another xml listview using fragment?

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
}
});

AlertDialog Builder OnItemSelectedListener

I have a tyny, but annoying problem with the AlertDialog Builder.
I want to handle an item select in a custom made AlertDialog, but OnItemSelectedListener doesn't seem to pick my clicks.
Custom Dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:background="#AAFFFFFF"
android:orientation="vertical">
<TextView
android:text="English"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_english"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingLeft="10dp"
android:onClick="onLanguageButtonClicked" />
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#000000" />
<TextView
android:text="عربى"
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_arabic"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingRight="10dp"
android:onClick="onLanguageButtonClicked" />
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#2e2e2e"/>
<TextView
android:text="کوردی "
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/lang_kurdish"
android:gravity="center_vertical"
android:background="#color/borders"
android:paddingRight="10dp"
android:onClick="onLanguageButtonClicked" />
</LinearLayout>
On button click I open the dialog and handle it:
public void onClickDrawer(View view) {
switch (view.getId()) {
case R.id.button_account_language:
handleLanguageDialog();
break;
case R.id.button_account_currency:
handleCurrencyDialog();
break;
default:
break;
}
}
And the handler:
private void handleLanguageDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.dialog_language);
builder.setOnItemSelectedListener(new AdapterView.
OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Log.i("info", "pressed" + Integer.toString(position));
restartInLocale(new Locale(preferences.getString("locale","")));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
builder.setNegativeButton("CANCEL", new DialogInterface
.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
Is this the correct approach or am I missing something?
Thank you in advance!
I don't this is correct Approach, you are making it very much complex. If I am not wrong then you are trying to show Language selection dialog for that you should follow the below given steps.
Create string-array inside strings.xml resource file
<string-array name="lang">
<item>English</item>
<item>عربى</item>
</string-array>
When you want to show alert dialog write down below code
private void handleLanguageDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color)
.setItems(R.array.lang, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch(which)
{
case 0:// English
break;
case 1:// عربى
break;
}
}
});
return builder.create();
}
This is the simplest way to show list of languages in alert dialog and without any positive or negative button .
It looks a bit off. It should look like this:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
https://developer.android.com/guide/topics/ui/dialogs.html
private void handleLanguageDialog() {
ArrayList<String> listItems = new ArrayList<>();
listItems.add("English");
listItems.add("Arabic");
new AlertDialog.Builder(this)
.setTitle("title")
.setCancelable(false)
.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).show();
}
Try to use setOnItemClick listener on the list/spinner view whichever you are using to display the list instead of builder itself. Like if you are using spinner to show the list use-
final Spinner spinner = (Spinner) layout.findViewById(R.id.spinner); spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int item = spinner.getSelectedItemPosition();
commandWriter(item);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Try this: add click listener to the language item in your Dialog
onItemSelected() is applied for listview or spinner items your Dialog layout dialog_language does not have those.
Try this code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater =getLayoutInflater();
View myview = inflater.inflate(R.layout.dialog_language, null);
// Inflate and set the layout for the dialog
builder.setView(myview);
TextView english = (TextView) myview.findViewById (R.id.lang_english);
english.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do some stuff
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.i("info", "pressed" + Integer.toString(position));
restartInLocale(new Locale(preferences.getString("locale","")));
}
});
TextView arabic = (TextView) myview.findViewById (R.id.lang_arabic);
arabic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do other stuff
}
});
// Add action buttons
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();

When button is clicked the Alert Dialog does not appear

I have an Alert Dialog that has an EditText where you input text and then add it to a ListView. Then on each item there is a Button I want to make that Button make an AlertDialog. The code below does not work.
This is my code...
public class DeleteRenameList extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert=new AlertDialog.Builder(DeleteRenameList.this);
alert.setMessage("What do you want to do?");
alert.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog ale=alert.create();
ale.show();
}
});
}}
Please Help.
Try this:
Make your custom dialog and present it:
//Make your class named CUstomDialogClass
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.Button;
public class CustomDialogClass extends Dialog{
public Activity c;
public Dialog d;
public Button yes, no;
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customdialog);
}
}
In your MainActivity, place this code in your onCreate() method:
Button button = (Button)findViewById(R.id.yourid);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final CustomDialogClass dialog = new CustomDialogClass(MainActivity.this);
dialog.setTitle("Your Title");
dialog.show();
final Timer time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
dialog.dismiss();
}
}, 5000);
}
});
Finally, there's the layout for custom dialog which you can modify. I just gave an example:
<?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:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yout Title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Message"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
And then you can add your listeners to it.
Hope this helps..:)
Your new onClickListener should be new View.onClickListener.
You should have something like this to start with:
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.onClickListener(){
#Override
public void onClick(View v){
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Are you sure you want to exit?")
.setIcon(R.drawable.ic_launcher)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
finish();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).create().show();
}
});

How to call main activity's function from custom ArrayAdapter?

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.

Categories