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

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.

Related

How to implement a Map in android studio with Leaflet and OpenStreetMap?

I am new to android. I am trying to develop a small app for loading a map with markers in android studio using leaflet and openstreetmap. I have read the article in this link https://asmaloney.com/2014/01/code/creating-an-interactive-map-with-leaflet-and-openstreetmap/#comment-10133 where author explains how to load the map using leaflet and openstreetmap in JavaScript. But I am trying to implement it completely in java in android studio. Is there any source code available for it to start with?
Leaflet is a free library and it helps to load more data on the map. I have implemented the google map in Android studio using Google Api.
Also I have tried openstreetmap alone for loading map. Here is my java file.
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.preference.PreferenceManager;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ScaleBarOverlay;
public class MainActivity extends Activity {
private MapView map;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialise osmdroid configuration
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx,
PreferenceManager.getDefaultSharedPreferences(ctx));
Configuration.getInstance().setUserAgentValue(BuildConfig.APPLICATION_ID);
setContentView(R.layout.activity_main);
map = (MapView) findViewById(R.id.map);
map.setMultiTouchControls(true);
map.setBuiltInZoomControls(true);
IMapController mapController = map.getController();
mapController.setZoom(14);
mapController.setCenter(new GeoPoint(48.745, -3.455));
ScaleBarOverlay scala = new ScaleBarOverlay(map);
map.getOverlays().add(scala);
map.invalidate();
}
public void onResume() {
super.onResume();
map.onResume(); //needed for compass, my location overlays, v6.0.0
and up
}
public void onPause() {
super.onPause();
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
//SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
//Configuration.getInstance().save(this, prefs);
map.onPause(); //needed for compass, my location overlays, v6.0.0
and up
}
}
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<org.osmdroid.views.MapView
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
I expect a sample source code to understand how to start with leaflet and openstreetmap for implementing the map on android studio.
Use OSMdroid. I have a good experience with it. Works natively.
Here, I made you some code. In your Java:
import android.content.Context;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.MapTileIndex;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Marker;
public class tester extends AppCompatActivity {
MapView map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tester);
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
map = (MapView) findViewById(R.id.map);
map.getTileProvider().clearTileCache();
Configuration.getInstance().setCacheMapTileCount((short)12);
Configuration.getInstance().setCacheMapTileOvershoot((short)12);
// Create a custom tile source
map.setTileSource(new OnlineTileSourceBase("", 1, 20, 512, ".png",
new String[] { "https://a.tile.openstreetmap.org/" }) {
#Override
public String getTileURLString(long pMapTileIndex) {
return getBaseUrl()
+ MapTileIndex.getZoom(pMapTileIndex)
+ "/" + MapTileIndex.getX(pMapTileIndex)
+ "/" + MapTileIndex.getY(pMapTileIndex)
+ mImageFilenameEnding;
}
});
map.setMultiTouchControls(true);
IMapController mapController = map.getController();
GeoPoint startPoint;
startPoint = new GeoPoint(51.0, 4.0);
mapController.setZoom(11.0);
mapController.setCenter(startPoint);
final Context context = this;
map.invalidate();
createmarker();
}
public void createmarker(){
if(map == null) {
return;
}
Marker my_marker = new Marker(map);
my_marker.setPosition(new GeoPoint(4.1,51.1));
my_marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
my_marker.setTitle("Give it a title");
my_marker.setPanToView(true);
map.getOverlays().add(my_marker);
map.invalidate();
}
In your build.gradle (app): Add this to your dependencies
implementation 'org.osmdroid:osmdroid-android:6.0.3'
And your layoutfile:
<org.osmdroid.views.MapView android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
The code given above is right but there is two errors: it miss a closing bracket at the end of the program (Activity) and you need to add some permissions (by using <uses-permission..../>) in your AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
After that, you have your map on your screen!

Custom ArrayAdapter and Custom Layout

I am learning android programming online from udacity and this one lecture is very old and it is in Android Studio 1.0 and I am using ver 3.0.1 and that code is not working so i am trying to move with that code and have to change few thing but stuck.
Problem, I am facing is that I am trying to make custom ArrayAdapter and trying to get the custom xml layout in it but i can not find the name of my xml in the list. here are the codes so far.
Java files: CategoryAdapter.java, MainActivity.java, MainFragment.java
Layout files: activity_main.xml, fragment_main.xml, list_item_forecast.xml.
CategoryAdapter
package com.example.android.sunshine;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Provides the appropriate {#link Fragment} for a view pager.
*/
public class CategoryAdapter extends FragmentPagerAdapter {
/**
* Create a new {#link CategoryAdapter} object.
*
* #param mainActivity
* #param fm is the fragment manager that will keep each fragment's state in the adapter
*/
public CategoryAdapter(MainActivity mainActivity, FragmentManager fm) {
super(fm);
}
/**
* Return the {#link Fragment} that should be displayed for the given page number.
*/
#Override
public Fragment getItem(int position) {
return new MainFragment();
}
/**
* Return the total number of pages.
*/
#Override
public int getCount() {
return 1;
}
}
MainActivity
package com.example.android.sunshine;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
CategoryAdapter adapter = new CategoryAdapter(this, getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
}
}
MainFragment
package com.example.android.sunshine;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.example.android.sunshine.R.layout;
import com.example.android.sunshine.MainFragment;
/**
* A simple {#link Fragment} subclass.
*/
public class MainFragment extends Fragment {
ArrayAdapter<String> mForecastAdapter;
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
String[] forecastArry = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Wednesday - Cloudy - 72/63",
"Thursday - Asteroids - 75/65",
"Friday - Heavy Rain - 65/56",
"Saturday - Help Trapped In WeatherStation - 60/51",
"Sunday - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArry));
mForecastAdapter = new ArrayAdapter<String>(
getContext(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
this is where I am heaving problem
mForecastAdapter = new ArrayAdapter(getContext(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
I dont see list_item_forecast anywhere and it is in red. when i click on it it say create xml and when i say yes then it say already exists.
here are my xml layout codes
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<ListView
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
list_item_forecast.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:id="#+id/list_item_forecast_textview" />
here you can see list_item_forecast root is TextView.
Try to rebuild the project or create a new project and do the same. Because I did the same with Android Studio version 3.0.1 and didn't get any error.

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"...

Android alert dialog button background

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

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