I use androidx. In the settings fragment, I want to create the "Preference" buttons and click on them to trigger some individual events.
How can I implement a click listener on a specific Preference?
Thats some my Code:
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preference);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(R.color.graylight));
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(R.string.action_settings);
toolbar.setLogo(R.drawable.ic_settings_white_24dp);
PreferenceManager preferenceManager = getPreferenceManager();
PreferenceScreen preferenceScreen = getPreferenceScreen();
return view;
}
}
And XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory
android:title="#string/setting_person"
app:initialExpandedChildrenCount="0"
app:key="profile_set">
<Preference
android:id="#+id/preference2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:key="button1"
android:summary="#string/setting_person_data"
android:title="#string/setting_person_reg"
app:icon="#drawable/ic_assignment" />
<Preference
android:key="button"
android:summary="#string/setting_avatar"
android:title="#string/setting_avatar_chg"
app:icon="#drawable/ic_wallpaper_black_24dp" />
</PreferenceCategory>
</PreferenceScreen>
As a result, I want to click on the trigger an event in MainActivity. But this is another question, now at least I should get a listen to the event, for example by calling Toast with the key of the button pressed.
Find the preference, then set a click listener on it.
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preference);
Preference preference = findPreference("button1");
preference.setOnClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference p) {
// Handle preference click
}
});
}
}
Please review the documentation on using Preferences:
https://developer.android.com/reference/androidx/preference/package-summary.html
https://developer.android.com/reference/androidx/preference/PreferenceFragmentCompat.html
https://developer.android.com/reference/androidx/preference/PreferenceFragmentCompat.html#findPreference(java.lang.CharSequence)
https://developer.android.com/reference/androidx/preference/Preference.OnPreferenceClickListener.html
Hope that helps!
After much torment, the solution was found as follows: (for AndroidX)
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preference);
Preference preferenceMap = findPreference("button");
preferenceMap.setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
getActivity().onBackPressed();
((MainActivity) getActivity()).injectSetting("map");
return true;
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(R.color.graylight));
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(R.string.action_settings);
toolbar.setLogo(R.drawable.ic_settings_white_24dp);
return view;
}
}
and in XML androidx.preference is added to the element:
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.preference.PreferenceCategory
android:title="#string/setting_person"
app:initialExpandedChildrenCount="1"
app:key="profile_set">
<androidx.preference.Preference
android:id="#+id/preference1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:key="button"
android:summary="#string/setting_person_data"
android:title="#string/setting_person_reg"
app:icon="#drawable/ic_assignment" />
<androidx.preference.Preference
android:id="#+id/preference2"
android:key="button2"
android:summary="#string/setting_avatar"
android:title="#string/setting_avatar_chg"
app:icon="#drawable/ic_wallpaper_black_24dp" />
</androidx.preference.PreferenceCategory>
</androidx.preference.PreferenceScreen>
And do not forget at build.gradle dependencies:
implementation 'androidx.preference:preference:1.1.0'
Maybe someone will need ))
Related
I'm new to this and i'm doing an app for a university project and I wanted to put a VideoView in my app, so I watched this video ("https://www.youtube.com/watch?v=SrPHLj_q_OQ&t=421s") and did it and worked. But then I add to copy the code from content_main.xml to a fragment and it stopped working and giving an error on the "android:onClick" on the Button. And when I press CTRL+F1 to inspect it says this:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
Heres my 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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:background="#003e6f"
android:orientation="vertical"
tools:context=".InicioFragment">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_gravity="center_horizontal"
android:layout_height="197dp" />
<Button
android:id="#+id/button2"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#FF6600"
android:text="Play"
android:onClick="videoplay"
android:textColor="#ffffff" />
<ImageView
android:id="#+id/imagem2"
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_alignParentBottom="true"
android:adjustViewBounds="false"
android:background="#drawable/tech3" />
</LinearLayout>
Heres my java:
package intro.android.migueloliveiraapp;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
clk = (Button) findViewById(R.id.button2);
videov = (VideoView) findViewById(R.id.videoView);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Carregar o layout do fragent incial "InicioFragment"
InicioFragment inicioFragment = new InicioFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment, inicioFragment, inicioFragment.getTag())
.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_oliveira) {
Quem_Oliveira quem_oliveiraFragment = new Quem_Oliveira();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
quem_oliveiraFragment, quem_oliveiraFragment.getTag())
.commit();
Toast.makeText(this, "Oliveira", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_profissao) {
Profissao profissaoFragment = new Profissao();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
profissaoFragment, profissaoFragment.getTag())
.commit();
Toast.makeText(this, "Profissão", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_feitos) {
Principais_feitos principais_feitosFragment = new Principais_feitos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
principais_feitosFragment, principais_feitosFragment.getTag())
.commit();
Toast.makeText(this, "Principais Feitos", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_academicas) {
Habilitacoes_Academicas habilitacoes_academicasFragment = new Habilitacoes_Academicas();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
habilitacoes_academicasFragment, habilitacoes_academicasFragment.getTag())
.commit();
Toast.makeText(this, "Habilitações Académicas", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_galeria) {
Galeria galeriaFragment = new Galeria();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
galeriaFragment, galeriaFragment.getTag())
.commit();
Toast.makeText(this, "Galeria", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_contactos) {
Contactos contactosFragment = new Contactos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
contactosFragment, contactosFragment.getTag())
.commit();
Toast.makeText(this, "Contactos", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//video view
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Heres my InicioFragment java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
}
heres my updated InicioFragment.java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.Uri;
import android.widget.Button;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
clk = (Button) view.findViewById(R.id.button);
videov = (VideoView) view.findViewById(R.id.videoView);
// bind the views here.
Button button2 = view.findViewById(R.id.button);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
You can use this for click.
Button mPlayVideo;
//In oncreate
mPlayVideo = findViewById(R.id.button2);
mPlayVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
In your xml your tools:context=".InicioFragment refers to your fragment and not your activity.
Your method is found inside the activity and not the fragment class and this is why are getting this error.
You can check Call an activity method from a fragment
But I can recommend using the onClick attribute inside your activities and inside fragment use normal click listener:
View view = findViewById(R.id.viewId);
view .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
This is because you created videoplay() method inside your MainActivity.java . You should put your videoplay() method into the InicioFragment.java as it is the corresponding file for the xml layout you have mentioned above.
Initialize your variables like bellow inside your onCreateView method on InicioFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inicio, container, false);
Button btn1 = view.findViewById(R.id.button_id);
.....
.....
return view;
}
public void videoplay(View v){
.........
.....
}
The following error:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
means that you forget to add the corresponding method in your Activity class when using android:onClick="videoplay" attribute. So, you need to add the following method to your activity:
public void videoplay(View v){
// do something here.
}
The most important part is, android:onClick tag is only working when you're using it inside the content layout of Activity.. So, android:onClick doesn't work when you're using it inside the fragment layout. You need to use the onClickListener instead.
You need to bind the view and add the onClickListener with something like this:
public class InicioFragment extends Fragment {
public InicioFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// bind the views here.
Button button2 = view.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
}
Pay attention on your xml file that this file's context is your InicioFragment (tools:context=".InicioFragment" )
Therefore, videoplay(View v) should be inside your InicioFragment class.
That's the reason why is not found. It won't search on your MainActivity.
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.testclassfragment, container, false);
Button clk = (Button) view.findViewById(R.id.button);
VideoView videov = (VideoView) view.findViewById(R.id.videoView);
return view;
}
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Since you also have a variable for your button another option is to do:
clk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TESTING", "Clicked");
}
});
I have a fragment which hosts a TabLayout and a ViewPager. The host fragment is part of a container that switches based on the item selection of a bottom navigation bar.
For some reason, the ViewPager isn't inflating the fragments, and the TabLayout is unresponsive. When sliding left or right, the indicator stops as soon as you stop sliding, and doesn't snap like it should. And, of course, the fragments don't show.
Here is my code...I'm wondering what I am doing wrong.
PopularHolderFragment.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ai.gab.android.R;
import ai.gab.android.ui.adapters.fragment.PopularFragmentsAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Andrew Quebe on 10/20/2017.
*/
#SuppressWarnings("ConstantConditions")
public class PopularHolderFragment extends Fragment {
#BindView(R.id.tabLayout)
TabLayout tabLayout;
#BindView(R.id.viewPager)
ViewPager viewPager;
public static PopularHolderFragment newInstance() {
return new PopularHolderFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewPager.setAdapter(new PopularFragmentsAdapter(getActivity().getSupportFragmentManager()));
tabLayout.addTab(tabLayout.newTab().setText("Posts"));
tabLayout.addTab(tabLayout.newTab().setText("Users"));
tabLayout.setupWithViewPager(viewPager);
}
}
PopularFragmentsAdapter.java
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import ai.gab.android.ui.fragments.popular.PopularPostsFragment;
import ai.gab.android.ui.fragments.popular.PopularUsersFragment;
/**
* Created by Andrew Quebe on 8/7/2017.
*/
public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {
public PopularFragmentsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PopularPostsFragment.newInstance();
case 1:
return PopularUsersFragment.newInstance();
}
return null;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Posts";
case 1:
return "Users";
}
return super.getPageTitle(position);
}
#Override
public int getCount() {
return 2;
}
}
fragment_popular_holder.xml
<android.support.design.widget.CoordinatorLayout 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.activities.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Light">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:elevation="2dp"
tools:targetApi="lollipop" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/util_popular_main_content" />
</android.support.design.widget.CoordinatorLayout>
util_popular_main_content.xml
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/fragment_popular_holder">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Screenshots
Also wondering why the text isn't its normal size.
Note that I do not want a toolbar in this layout, and perhaps that is my issue, but I don't see why it would be as the widgets should be able to work independently of each other.
Using the comment from Mike and AndroidSmoker74's answer, I was able to fix the TabLayout bug.
PopularWrapperFragment.java
public class PopularWrapperFragment extends Fragment {
#BindView(R.id.tabLayout)
TabLayout tabLayout;
#BindView(R.id.viewPager)
ViewPager viewPager;
public static PopularWrapperFragment newInstance() {
return new PopularWrapperFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
ButterKnife.bind(this, view);
((MainActivity) getActivity()).setPagingEnabled(false);
viewPager.setAdapter(new PopularFragmentsAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
return view;
}
}
PopularFragmentsAdapter.java
public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {
public PopularFragmentsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PopularPostsFragment.newInstance();
case 1:
return PopularUsersFragment.newInstance();
}
return null;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Posts";
case 1:
return "Users";
}
return super.getPageTitle(position);
}
#Override
public int getCount() {
return 2;
}
}
Hope someone finds this useful!
May be my answer is not correct answer for your question. I faced same issue while dealing with Fragments... Below is the mistake I did.
return super.onCreateView(inflater, container, savedInstanceState);
This was creating this kind of issue. I removed this sentence and just inflated some view from the layout files, then it was working fine.
Just check your onCreateView function it will probably solve your problem.
My point is clear here. You should return your inflated view in onCreateView function instead of super.onCreateView(inflater, container, savedInstanceState);
do the binding of pager and tabs in onCreateView. Not in the onActivityCreated.
And you don't need to manually add tabs to TabLayout, it'll do so automatically.
just get the tabs by position and set their text.
binding should be in onCreateView.
I am using the Hamweather Aeris Andorid SDK, and I am trying to implement the map view component. When I follow their online tutorials, I can not render the AerisMapView, and I get the error:
java.lang.ClassNotFoundException: com.hamweather.aeris.maps.R$layout.
Does anyone know where this is coming from/how to fix it?
My xml file:
<?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" >
<com.hamweather.aeris.maps.AerisMapView
android:id="#+id/aerisfragment_map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</com.hamweather.aeris.maps.AerisMapView>
</LinearLayout>
And my Activity:
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Window;
public class MapViewActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview_activity);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MapFragment fragment = new MapFragment();
fragmentTransaction.add(R.id.frame_container, fragment);
fragmentTransaction.commit();
}
}
Finally, the fragment:
import android.location.*;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.model.LatLng;
import com.hamweather.aeris.communication.AerisCallback;
import com.hamweather.aeris.communication.EndpointType;
import com.hamweather.aeris.location.LocationHelper;
import com.hamweather.aeris.maps.AerisMapView;
import com.hamweather.aeris.maps.AerisMapView.AerisMapType;
import com.hamweather.aeris.maps.MapViewFragment;
import com.hamweather.aeris.maps.interfaces.OnAerisMapLongClickListener;
import com.hamweather.aeris.maps.interfaces.OnAerisMarkerInfoWindowClickListener;
import com.hamweather.aeris.maps.markers.AerisMarker;
import com.hamweather.aeris.model.AerisResponse;
import com.hamweather.aeris.response.EarthquakesResponse;
import com.hamweather.aeris.response.FiresResponse;
import com.hamweather.aeris.response.StormCellResponse;
import com.hamweather.aeris.response.StormReportsResponse;
public class MapFragment extends MapViewFragment implements OnAerisMapLongClickListener, AerisCallback,
OnAerisMarkerInfoWindowClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.single_tab_site_weather2,
container, false);
mapView = (AerisMapView) view.findViewById(R.id.aerisfragment_map);
mapView.init(savedInstanceState, AerisMapType.GOOGLE);
initMap();
setHasOptionsMenu(true);
return view;
}
/**
* Inits the map with specific setting
*/
private void initMap() {
mapView.moveToLocation(new LatLng(34.7, -86.7), 9);
mapView.setOnAerisMapLongClickListener(this);
mapView.setOnAerisWindowClickListener(this);
}
#Override
public void onResult(EndpointType endpointType, AerisResponse aerisResponse) {
}
#Override
public void onMapLongClick(double v, double v1) {
}
#Override
public void wildfireWindowPressed(FiresResponse firesResponse, AerisMarker aerisMarker) {
}
#Override
public void stormCellsWindowPressed(StormCellResponse stormCellResponse, AerisMarker aerisMarker) {
}
#Override
public void stormReportsWindowPressed(StormReportsResponse stormReportsResponse, AerisMarker aerisMarker) {
}
#Override
public void earthquakeWindowPressed(EarthquakesResponse earthquakesResponse, AerisMarker aerisMarker) {
}
}
Also, this is my first Q on stack exchange, so if I failed to adhere to a certain convention or etiquette, please let me know, and I'll try to fix it. Thanks.
I Managed to get it working. For anyone who has this issue, here were my steps:
I first switched from using the jars to using the gradle dependency. Per their website, add the following to your build.gradle(the module one)
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.android.gms:play-services:4.4.52'
compile 'com.hamweather:aeris-maps-library:1.0.0#aar'
}
Also be sure to add the following, in the andorid tag, which probably already exists in the file:
android {
...some other stuff...
dexOptions{
preDexLibraries = false
}
}
Double check that you have the proper API key permissions for google maps. Then it works. As far as I can tell, it had something to do with using the compiled jar, not the repo version.
I need your help on this. I am going to make an app using ViewPager and I since I never been programming for android before I thought it would be good to make a sample app first. I want to use the ViewPager a little bit differently than the classic list-of-items-style so I made an app that will show all the colors (or every 10th color) from #000000 to #FFFFFF.
It doesn't work. I've started the app on the emulator but I just get a white screen. If the default position of the ViewPager when starting is 0 then the color should be black. And when I try to make a breakpoint the program doesn't stop, or it's never reaching the point. I'm using eclipse.
These are the files of the project
MainActivity.java
package com.example.colorswipe;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity {
private ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager=(ViewPager)this.findViewById(R.id.pager);
mPager.setAdapter(new MyAdapter());
}
private class MyAdapter extends PagerAdapter {
#Override
public int getCount() {
return 0xFFFFFF/10;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ColorView view=new ColorView(container.getContext());
view.setBackgroundColor(android.graphics.Color.parseColor(String.format("#%06X", position*10)));
view.setText(position);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
ColorView.java
package com.example.colorswipe;
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ColorView extends LinearLayout {
private TextView tv;
public ColorView(Context context) {
super(context);
LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
this.setLayoutParams(params);
TextView tv=new TextView(context);
this.tv=tv;
this.addView(tv);
}
public void setText(int position) {
tv.setText(Integer.toString(position).toCharArray(), 0, Integer.toString(position).length());
}
}
EDIT - the view pager is there , but I think you don't resolve the color correctly.
I found the problem. isViewFromObject must be implemented as return arg0==arg1.
I have a problem with btn.setOnClickListener(this). I have a simple project that works good, but when I add an action to the button I get the message:
unfortunatelay (app name) has stopped
When I comment btn.setOnClickListener(this) out the project works without any problem.
Here is my code:
package com.example.hello;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static final Context PlaceholderFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements OnClickListener {
Button btn;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
btn=(Button)rootView.findViewById(R.id.Entrer);
btn.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// here is the problem error: no eclosing istance of the type MainActivityis accessible in scope
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
}
My layout is as follows:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.hello.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:text="#string/hello_world"
android:textSize="16dp" />
<Button
android:id="#+id/Entrer"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:text="Entrer" />
</RelativeLayout>
I dont know if I have simple things that are not go correctly. I'm new to Android programming. Thank you!
btn is null, so when you set onClickListener you get NullPointerException. It's null because it's located in fragment_main.xml, not activity_main.xml. You should move this code from onCreate()
btn = (Button) findViewById(R.id.Entrer);
btn.setOnClickListener(this);
to PlaceholderFragment() as follows:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
btn=(Button) rootView.findViewById(R.id.Entrer);
btn.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return rootView;
}
}
btn=(Button)findViewById(R.id.Entrer);
btn.setOnClickListener(this);
Most likely, findViewById above is returning null. btn.setOnClickListener is crashing on a null pointer exception. (Because btn is null).
It is extremely likely, since you are using the default fragment structure created by the Eclipse solution, that the Button is really in the fragment layout file (fragment_main.xml) and not in activity_main.xml. (Hence, the button is not in the Activity view, it's in the fragment view).
If that's the case, then move the above two lines into the onCreateView method of the PlaceholderFragment.