Android alert dialog button background - dialog

In Android Alert Dialog : dialog.getButton is not available
How to change the background of the Positive button in laert dialog

You need to write it after
dialog.show();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(NewApplication.this);
alertDialogBuilder.setCancelable(false).setNegativeButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
alertDialog.getButton(Dialog.BUTTON_NEGATIVE).
setBackgroundColor(Color.parseColor("#3399ff"));

I think this has been addressed here before, IRC.
Check these answers posted earlier on a similar issue:
Android Button modify Question.
Good links and answers there.

First off, the
'
`DialogInterface.OnClickListener`'
listener — must not be NULL .
Second make sure you imported the correct Android classes, there are a lot of them, and some are version specific.
For example:
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.os.Handler;
import android.util.Log;
Here is a quick and dirty sample of code in Java that illustrates the use of some special Android imports you need for an application. Remember Android uses many special classes and objects all its own.
final AlertDialog d = new AlertDialog.Builder(this)...create();
//final Button b1 = d.getButton(Dialog.BUTTON_POSITIVE);
editName.addTextChangedListener(new TextWatcher() //
{
public void afterTextChanged(Editable ed) {
Button b1 = d.getButton(Dialog.BUTTON_POSITIVE);
//comment out sections that may or may not work //
b1.setEnabled(ed.length() > 0);
private static final class [More ...] ButtonHandler extends Handler {
// Button clicks have Message.what as the BUTTON{1,2,3} constant//
private static final int MSG_DISMISS_DIALOG = 1;
private WeakReference<DialogInterface> mDialog;
public void // whatever classes you want //
ButtonHandler(DialogInterface dialog) {
mDialog = new WeakReference<DialogInterface>(dialog);
}
Use override to set replacement buttons or new button messages in a new section. It is one way to use the same button positioning for a new function. For example:
#Override
public void [More ...]
handleMessage(Message msg) {
switch (msg.what) {
case DialogInterface.BUTTON_POSITIVE:
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEUTRAL:
((DialogInterface.OnClickListener)
msg.obj).onClick(mDialog.get(), msg.what);
break;
case MSG_DISMISS_DIALOG:
((DialogInterface) msg.obj).dismiss();
}
Hope this helps answer your question.
Code illustrated for illustration only, it is not the actual code, you need to write your own.
As an additional note: If you are using eclipse or other GUI interface, it tends to add a lot of additional and unnecessary code. Try coding on a text editor like Notepad++ and you will find it to be cleaner and smoother.

U try to Custom Alert dialog
<LinearLayout
android:id="#+id/ll_head"
android:layout_width="match_parent"
android:layout_height="30dp"
android:orientation="horizontal"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:background="#color/colorPrimaryDark"
app:layout_constraintRight_toRightOf="parent">
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="63dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/ll_head"
android:layout_alignParentStart="true"
android:background="#color/colorAccent"
android:layout_marginLeft="36dp"
android:layout_marginStart="36dp"
android:layout_marginBottom="36dp"
android:id="#+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#android:color/holo_blue_bright"
android:layout_marginRight="53dp"
android:layout_marginEnd="53dp" /> </RelativeLayout>
public class MainActivity extends AppCompatActivity {
Dialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=(TextView) findViewById(R.id.text);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog=new Dialog(MainActivity.this);
alertDialog.setContentView(R.layout.dialog);
alertDialog.show();
}
});
}
}

Related

how to make an image show when radio button is clicked

I know this is a simple question but I'm a beginner and I have this homework where we
have to make an image show when the radio button is clicked but they didn't teach us anything about that
because of coronavirus so I would really appreciate it if someone could tell me how to do it.
For creating two radio buttons with simple image, and control visibility of image when check one of the radio buttons, I will give some simple steps to build that in java.
After build a new empty activity project:
You can open the wanted files from project explorer as shown :
go to activity_main.xml which is the layout file, I will create Linear layout with image and radio group contains two radio buttons,and I used imageview android:src attribute as a color (you can change it to image):
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#color/colorPrimary"
android:text="Hello World!"
android:visibility="gone" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radio_button_choice1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choice-1" />
<RadioButton
android:id="#+id/radio_button_choice2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choice-2" />
</RadioGroup>
Second, we need to go to java file named as MainActivity which is java file, and we will get the views and create a listener on the RadioGroup which we will use to show and hide the image (some comments help you understands the java code):
package com.your.packagename.here;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
public class MainActivity extends AppCompatActivity {
private ImageView image;
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//intit views
image = findViewById(R.id.imageView);
radioGroup = findViewById(R.id.radioGroup);
//create the listener for radio group
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//check if the choice-1 is selected
if (radioGroup.getCheckedRadioButtonId() == R.id.radio_button_choice1) {
//show image wen select choice-1
image.setVisibility(View.VISIBLE);
} else {
//hide image when choice-1 not selected
image.setVisibility(View.GONE);
}
}
});
}
}
Finally, and you will get similar to this.
I hope this was helped you.

Android Studio: How to use ViewPagerAdapter on Multiple Buttons to load different images?

I am new to coding and I am stuck with something. I have a set of 5 slideshows with about 30 images for each. I have an activity with 5 buttons. I am using a ViewPagerAdapter to load the slides from my drawable folder. All is working for the first button using the code I am posting here. The code loads all ~30 images to make the slideshow. Now When I try to make a new ViewPagerAdapter (couldn't make a duplicate name so i renamed it ViewPagerAdapterBD. Not sure if this is wrong) for the second button to load different files from the drawable, the class in the code is grayed out saying "ViewPagerAdapterBD is never used". I continued to load the new images but the second button would still load the files from the first button. My question is, how can I have my 5 buttons open up different images from my drawable folder? What do I need to do to have my buttons open up different images to ultimately have each button display a different slideshow for each? Or better wording, I want to know how to go about using an imageslider on different activities using viewpageradapter?
BurstMode.java
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class BurstMode extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_burst_mode);
getSupportActionBar().setTitle("Burst Mode");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewPager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
}
}
activity_burst_mode.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BurstMode">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
</RelativeLayout>
ViewPagerAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer [] images = {R.drawable.bm1,R.drawable.bm2,R.drawable.bm3,
R.drawable.bm4,R.drawable.bm5,R.drawable.bm6,R.drawable.bm7,
R.drawable.bm8,R.drawable.bm8,R.drawable.bm10,R.drawable.bm11,
R.drawable.bm12,R.drawable.bm13,R.drawable.bm14,R.drawable.bm15,
R.drawable.bm16,R.drawable.bm17,R.drawable.bm18,R.drawable.bm19,
R.drawable.bm20,R.drawable.bm21,R.drawable.bm22,R.drawable.bm23,
R.drawable.bm24,R.drawable.bm26,R.drawable.bm27,R.drawable.bm28,
R.drawable.bm29,R.drawable.bm30,R.drawable.bm31};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view == o;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.custom_layout_burst_mode,
null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view,0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull
Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
custom_layout_burst_mode.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
app:srcCompat="#android:drawable/btn_star_big_off"
tools:layout_editor_absoluteX="164dp"
tools:layout_editor_absoluteY="65dp" />
</LinearLayout>
Here is an image of the activity with the buttons: Image
I want to know how I can go about having each button open up different sets of images, different from the other buttons
Welcome to programming!
Go ahead and scrap the other class, ViewPagerAdapterBD. Instead, let's extend the other class you already wrote.
Consider the constructor for ViewPagerAdapter.
public ViewPagerAdapter(Context context) {
this.context = context;
}
Why not pass in an argument here which configures it to behave differently?
public ViewPagerAdapter(Context context, SlideShowType type) {
this.context = context
this.type = type
}
Go ahead and look up enumerated types in Java, it will help you create this SlideShowType enum. Once you've done that, your adapter can check this configuration in a switch statement, and make use of different arrays of images depending on the SlideShowType passed into the constructor!
Another option would be passing the array of image resources into the constructor directly. Let me know if you'd like me to follow up with more detail on anything.

setListAdapter for twitter fabric

I am trying to make an app with a twitter timeline an android studio. To do this I am using the twitter fabric API. The documentation for that I am following is found at https://docs.fabric.io/android/twitter/show-timelines.html#timeline-builders. The problem I am having is that the setListAdapter in
setListAdapter(adapter); is coming up with an error saying "cannot resolve method 'setListAdapter(com.twitter.sdk.tweetui.TweetTimelineListAdapter)'". I really have no experience with android studio, so I've copied and pasted most of this code. I've looked up how adapters work in android studio, and I get what they do, but I'm not sure how they're set up. Thanks in advance for the help!
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.widget.SwipeRefreshLayout;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.tweetui.SearchTimeline;
import com.twitter.sdk.android.tweetui.TimelineResult;
import com.twitter.sdk.android.tweetui.TweetTimelineListAdapter;
import com.twitter.sdk.android.tweetui.UserTimeline;
import com.twitter.sdk.android.tweetui.CollectionTimeline;
public class FeedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
final SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
final SearchTimeline timeline = new SearchTimeline.Builder()
.query("#fblaoutfit")
.build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(this)
.setTimeline(timeline)
.build();
setListAdapter(adapter);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeLayout.setRefreshing(true);
adapter.refresh(new Callback<TimelineResult<Tweet>>() {
#Override
public void success(Result<TimelineResult<Tweet>> result) {
swipeLayout.setRefreshing(false);
}
#Override
public void failure(TwitterException exception) {
// Toast or some other action
}
});
}
});
}
Here's the XML if it will help you at all:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="No Tweets"/>
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="#e1e8ed"
android:dividerHeight="1dp"
android:drawSelectorOnTop="false"/>
</android.support.v4.widget.SwipeRefreshLayout>
You need to study more on using ListViews and ListActivities in android.
Cause of Error
Your troubling method setListAdapter(adapter) is available in a ListActivity but your activity class is AppCompatActivity. There is no setListAdapter(adapter) method defined in AppCompatActivity. That is why you get the above error.
Solution
By considering rest of your implementation, it is fine that you use AppCompactActivity. But then you can't use the setListAdapter(adapter) method. Instead you need to get a reference to your ListView in your layout and set the adapter for the ListView as in below code snippet.
public class FeedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(this)
.setTimeline(timeline)
.build();
//obtain reference to the list view
ListView listView = (ListView) findViewById(R.id.listView);
//set the adapter to list view
listView.setAdapter(adapter);
//your rest of the code
}
}
Also change the id of your ListView in layout file as follows.
<ListView android:id="#+id/listView"...

Method has incorrect signature

Despite having the method onButtonHomeClick declared in the Java file MainActivity, when I attempt to reference the method in the XML I receive the error message: "Method onButtonHomeClick in MainActivity has incorrect signature". Both of them are below, and I cannot for the life of me figure out why it is returning such an error, especially since attempting to navigate to the declaration by Ctrl clicking onButtonHomeClick in the XML file navigates to the method in the Java class.
And it's definitely struggling to find the method, as the Android Monitor returns a fatal error when attempting to assign the behaviour to the button.
<!-- XML file -->
<item
android:id="#+id/button_home"
android:orderInCategory="100"
android:icon="#drawable/home"
android:title="Home"
android:onClick="onButtonHomeClick"
app:showAsAction="always"
/>
//Java method
public void onButtonHomeClick(View v){
Intent intent = new Intent(this, MainActivity.class);
}
Clean your project and then make sure the method onButtonHomeClick() is declared as public void.
Your On Click Method has Invalid Arguments for MenuItem. For MenuItem, it is
public void onClickMethod(MenuItem menuItem) {
// Your code here
}
Whereas public void onClickMethod(View view) {...} is for View present in your activity layout.
Also just creating an Intent will not start the Activity. For starting the activity you should pass your intent to startActivity().
you need to add startActivity(intent); in your method, so it should be something like this:
public void onButtonHomeClick(View v){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
I tried your code with startActivity(intent); included and it works just fine
in kotlin:
<android.support.v7.widget.AppCompatButton
android:id="#+id/mRecharge_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:textSize="18sp" />
in your activity create public fun onClick
public fun onClick(view: View?) {
// do ur logic here
}
You must also define the android: onClick method to all views. Remember that the click method name is the same in all views.
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layoutDirection="rtl" >
<RadioButton
android:id="#+id/radioButton_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Score"
android:onClick="OnClickView"/>
<RadioButton
android:id="#+id/radioButton_discoun_percent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Discoun Percent"
android:onClick="OnClickView" />
</RadioGroup>
public void OnClickView(View view) {
switch(view.getId()){
case R.id.radioButton_score:
Toast.makeText(this, "click Score",
Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton_discoun_percent:
Toast.makeText(this, "click Discoun Percent",
Toast.LENGTH_SHORT).show();
break;
}
}
Did you remember to include in your MainActvity.java file the import for the View class? (It's not imported by default.)
import android.view.View;

Android Fragment Interface Unresponsive

I am having a strange issue with my program that I cannot explain and I have thus far not been able to find a solution. I have a simple activity that will switch between fragments and run the user through an initial setup of the app. The first fragment is just a text view at the top, with a button on the bottom with an onClickListener set to call a method on the parent activity, however in testing, when I click on the button, nothing happens. It does not change color like a normal button would, and no click seems to be registered.
Here is the XML for the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/setup_intro" />
<Button
android:id="#+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:clickable="true"
android:width="72dp"
android:text="#string/next_button" />
</RelativeLayout>
And this is the fragment code where I implement the onClickListener
public class SetupFragmentInitialScreen extends SherlockFragment
{
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View parentView = null;
parentView = inflater.inflate(R.layout.setup_fragment_initial_screen,
container,
false);
Button nextButton = (Button)parentView.findViewById(R.id.next_button);
nextButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.v("ButtonPressed", "You Pressed the button!");
((InitialActivity)getActivity()).onInitialScreenNextPress();
}
});
return parentView;
}
}
And lastly, here is my code for my activity so far
public class InitialActivity extends SherlockFragmentActivity
{
private SetupFragmentInitialScreen initialScreen;
private SetupFragmentPreferenceOneScreen preferenceOneScreen;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
initialScreen = new SetupFragmentInitialScreen();
preferenceOneScreen = new SetupFragmentPreferenceOneScreen();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(android.R.id.content,
initialScreen);
fragmentTransaction.commit();
}
public void onInitialScreenNextPress()
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(android.R.id.content,
preferenceOneScreen);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
So far the code to me seems correct, but as I said, there is no reaction from the interface when I try to press the button.
Edit: I have added the following code to my Activity to check for touch events
#Override
public boolean onTouchEvent(MotionEvent event)
{
super.onTouchEvent(event);
Log.v("Touch Detected", "You are touching the screen.");
return false;
}
It logs events all over the screen, except for when I'm touching the button, so the activity is receiving touch events, but the UI itself is not. I also tried loading another interface which has a pair of radio buttons, and they too were unresponsive. Is there something I'm doing wrong with initializing the fragments?
Unfortunately none of the code you posted seems to point to what the issue is.
A button does not need an onClick listener in order to change color when pressed, so I wouldn't worry about that part. More importantly:
Is it possible that any transparent view is lying on top of the button and taking the click? DDMS has a "Dump View Hierarchy for UI Automator" button that may help you check on this.
Does your activity override dispatchTouchEvent(), onInterceptTouchEvent(), or related API's and could one of these be preventing the touch from reaching the button?
If you are applying custom theming to the button, do you have separate visuals for the pressed state?
I figured out what it was. For whatever reason the program didn't like me trying to do the fade out-fade in animation when loading the first fragment into the activity. I removed that line from the onCreate() method and it works fine now.

Resources