In my android app I have settings activity, which uses preferences.
There are many preferences such as ListPreference, SwitchPreference, etc., but there aren't one kind of preference that I need.
In this preference I want to:
1. display a title that is constant and will never change (such as other preferences)
2. display text, that will be changed by the app, but NOT by the user.
Most similar preference to this is EditTextPreference, but it's not OK for me, because I don't want user to change displayed text, instead my app will change it. So my preference could be called TextViewPreference.
Good example of what I want is inside the 'Settings' android app, inside the 'device information' category.
Edit:
Code that I would like to use to change summary won't be placed in activity code, and I don't use PreferenceActivity.
In fact, only time when I have to change the summary is when the SettingsActivity is NOT on main thread.
The code below is a complete example of what you are trying to achieve, it shows an example of how to create an info preference that is directly updated based on other preferences (addition of x_pref and y_pref and displaying result in result_pref below) or is updated based on something passed from another activity.
1) DemoActivity----------
public class DemoActivity extends AppCompatActivity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.demo_preferences, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(DemoActivity.this , PrefDemoActivity.class);
i.putExtra("Passed", "Test--##%%&&");
startActivity(i);
break;
default:
throw new RuntimeException("unknown menu selection");
}
return true;
}
}
2) demo_activity.xml----------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Empty"
android:gravity="center"
android:background="#android:color/holo_blue_light"/>
</android.support.constraint.ConstraintLayout>
3) PrefDemoActivity----------
public class PrefDemoActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
DemoEditPreferences mDemoPrefsFragment = new DemoEditPreferences();
mFragmentTransaction.replace(android.R.id.content, mDemoPrefsFragment);
mFragmentTransaction.commit();
}
}
4) DemEditPreferences----------
public class DemoEditPreferences extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
private SharedPreferences demo_preferences;
private int preferencesToEdit;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demo_preferences = getActivity().getSharedPreferences("demo_preference",
0);
preferencesToEdit = R.xml.demo_preferences;
String preferenceName = getResources().getString(R.string.pref_sensor_key);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(preferenceName);
preferenceManager.setSharedPreferencesMode(0);
getActivity().setTitle("Demo Preferences");
addPreferencesFromResource(preferencesToEdit);
Preference from_another_activity_p = (Preference) findPreference("passed_from_another_activity_key");
if(getActivity().getIntent() != null) {
from_another_activity_p.setSummary(getActivity().getIntent().getStringExtra("Passed"));
}
updateResult();
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(findPreference(key) != null) {
if(findPreference(key).getKey().equals("x_key")) {
updateResult();
}else if(findPreference(key).getKey().equals("y_key")) {
updateResult();
}
checkPrefValueValidity(findPreference(key));
updatePrefSummary(findPreference(key));
}
}
private void updateResult(){
EditTextPreference x_p = (EditTextPreference) findPreference("x_key");
EditTextPreference y_p = (EditTextPreference) findPreference("y_key");
Preference result_p = (Preference) findPreference("result_key");
result_p.setSummary("( X + Y ) = " + (Float.valueOf(x_p.getText()) + Float.valueOf(y_p.getText())));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCategory = (PreferenceCategory) p;
for (int i = 0; i < pCategory.getPreferenceCount(); i++) {
initSummary(pCategory.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
private void checkPrefValueValidity(Preference p) {
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
if (editTextPref.getText().equals("")) {
// what do you want to do if the value entered is empty
} else {
// maybe only certain values are allowed
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(android.R.color.white));
return view;
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
5) demo_menu----------
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_settings"
android:title="Settings"
android:titleCondensed="Settings"
android:orderInCategory="1">
</item>
</menu>
7) demo_preferences----------
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Demo">
<EditTextPreference
android:key="x_key"
android:title="X"
android:defaultValue="0"
android:summary="0"
android:inputType="numberDecimal|numberSigned"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
<EditTextPreference
android:key="y_key"
android:title="Y"
android:defaultValue="0"
android:summary="0"
android:inputType="numberDecimal|numberSigned"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
<Preference
android:key="result_key"
android:title="Result"
android:summary="0"> // default summary value if any
</Preference>
<Preference
android:key="passed_from_another_activity_key"
android:title="From another Activity"
android:summary="null"> // default summary value if any
</Preference>
</PreferenceCategory>
</PreferenceScreen>
8) Don't forget to add both activities to the manifest.
What you can do is have an EditTextPreference and disable it. So that the subtitle is displayed but cannot be edited.
findPreference("your-preference-key").setEnabled(false);
Related
How to add action bar in YouTube player?
I'm trying to add action bar in this activity, but because it's not extended to AppCompatActivity that's why I'm getting an error in getSupportActionBar();. I'm also getting error if I replace the YouTubeBaseActivity with AppCompatActivity. Can anyone help me with this?
public class ActivityPlayer extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public String DEVELOPER_KEY = "key";
public String YOUTUBE_VIDEO_CODE = "5z-Roo_NpI4";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerView youTubeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setContentView(R.layout.activity_main);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubeView.initialize(DEVELOPER_KEY, this);
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return true;
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
Snackbar.make(youTubeView, "There was an error initializing the video player.", Snackbar.LENGTH_LONG).setDuration(5000).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.loadVideo(YOUTUBE_VIDEO_CODE);
player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
#Override
public void onBackPressed() {
finish();
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_player);
}
}
I had the same Problem with you, I'm posting an answer in case you or others still need a work around. Forget about YoutubeBaseActivity and focus on YoutubePlayerSupportFragment because Fragment let you setup your Activity as you wish. There is YoutubePlayerFragment also but the Support version of it work better with android support libraries.
Here's is the Steps I used :
Make your activity Extends AppCompatActivity
public class ActivityPlayer extends AppCompatActivity {
Add a FrameLayout in xml layout of the Current Activity that extends AppCompatActivity (activity_main.xml)
<FrameLayout
android:id="#+id/flYoutube"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:visibility="visible" />
Create a YoutubeFragment extends Fragment, with fragment_youtube.xml layout and a FrameLayout inside of it. And in onCreateView, create a YoutubePlayerSupportFragment instance and replace the FrameLayout within the fragment_youtube.xml with that instance of YoutubePlayerSupportFragment.
public class YoutubeFragment extends Fragment {
private static final String YOUTUBE_API_KEY = "8S7K4hEVhgOQ87501j-FAKE-KEY";
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String VIDEO_ID = "VIDEO_ID";
// TODO: Rename and change types of parameters
private String videoId;
public YoutubeFragment() {
// Required empty public constructor
}
public static YoutubeFragment newInstance(String videoId) {
YoutubeFragment fragment = new YoutubeFragment();
Bundle args = new Bundle();
args.putString(VIDEO_ID, videoId);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
videoId = getArguments().getString(VIDEO_ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_youtube, container, false);
YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.flYoutubePlayer, youTubePlayerFragment).commit();
youTubePlayerFragment.initialize(YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
//youTubePlayer.setFullscreen(true);
youTubePlayer.loadVideo(videoId);
//yoTubePlayer.play();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
return rootView;
}
}
Create a 2nd FrameLayout in fragment_youtube.xml
<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"
tools:context="jfsl.ayibopost.fragments.YoutubeFragment">
<FrameLayout
android:id="#+id/flYoutubePlayer"
android:layout_width="match_parent"
android:layout_height="200dp"></FrameLayout>
</RelativeLayout>
Last thing to do in PlayerActivity onCreate(), is to create an instance of your own created YoutubeFragment and replace the Frame Layouts within the activity_main.xml with that YoutubeFragment instance via Fragment Transaction:
// Create Youtube Fragment instance by passing a Youtube Video ID
YoutubeFragment youtubeFragment = YoutubeFragment.newInstance("2zNSgSzhBfM");
getSupportFragmentManager().beginTransaction()
.replace(R.id.flYoutube, youtubeFragment).commit();
And you are done.
You should implement an AppCompatCallback interface.
Please, see my answer.
Am a beginner in android development and am desperately looking for a solution for a challenge i encountered while working on a quiz app.
I have a switch in my SettingsActivity which toggle set a particular text in another activity visible and invisible.
However i have been having problems finding the right logic to reference that text from my SettingsActivity in other to toggle its visibility.
QuizActivity.java
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
}
}
SettingsActivity.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:paddingTop="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/explanationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:fontFamily="cursive"
android:layout_marginBottom="25dp"
android:textColor="#color/settings_text"
android:text="#string/explanation"/>
<Switch
android:id="#+id/explanationSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:checked="true"
android:layout_gravity="center"/>
</LinearLayout>
SettingsActivity.java
private Switch mExplanationSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_settings);
mExplanationSwitch = (Switch) findViewById(R.id.explanationSwitch);
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
}
MainActivity.java
//This is where i start Quiz Activity
private Button startQuiz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startQuiz = (Button) findViewById(R.id.start);
startQuiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startQuiz = new Intent(this, QuizActivity.class);
startActivity(beginnerIntent);
});
}
Save Setting in Shared Preferences
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
Editor editor = preferences.edit();
if(isChecked){
editor.putBoolean("ntoificatoin",isChecked);
}
else
{
editor.putBoolean("ntoificatoin",isChecked);
}
editor.apply();
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
In Your QuizActivity
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
boolean b=preferences.getBoolean("ntoificatoin",false);//it returns stored boolean value else returns false
if(b){
//return true from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
else
{
//return false from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
}
}
if you are looking for how to pass extra info to the QuizActivity here how to use the extra in the intent :
Intent intent = new Intent();
intent.putExtra("stateOfTheSwitch","clicked");
startActivity(intent);
and in the QuizActivity you can retrieve the extra like this :
if(getIntent().getExtras.getString("stateOfTheSwitch").equals("clicked")
//do something
else
//do something else
I am trying to take the value from my edittextpreference and change the font size of the textviews in my mainActivity layout. Please help me with this guys.I must be doing some silly mistake.Help would be appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this);
String str=sp.getString("editTextPref","50");
if(sp!=null)
{
Toast.makeText(this,"String value is "+str,Toast.LENGTH_LONG).show();
txt=(TextView) findViewById(R.id.textView);
txt.setTextSize(Float.parseFloat(str));
}
Toast.makeText(this,"String value is :"+str,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int items=item.getItemId();
switch(items)
{
case R.id.setting:
Toast.makeText(this,"Settings Clicked",Toast.LENGTH_LONG).show();
finish();
Intent i=new Intent(this,Prefs.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
Prefs.java
public class Prefs extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences sp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
// show the current value in the settings screen
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePreference(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory cat = (PreferenceCategory) p;
for (int i = 0; i < cat.getPreferenceCount(); i++) {
initSummary(cat.getPreference(i));
}
} else {
updatePreference(p);
}
}
private void updatePreference(Preference p)
{
if(p instanceof EditTextPreference)
{
EditTextPreference editTextPreference=(EditTextPreference) p;
p.setSummary(editTextPreference.getText());
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
startActivity(new Intent(Prefs.this,MainActivity.class));
Toast.makeText(this,"Pref activity finished",Toast.LENGTH_LONG).show();
}
}
Prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:enabled="false"
android:key="settingCategory"
android:title="Settings"
>
</PreferenceCategory>
<EditTextPreference
android:id="#+id/editTextPref"
android:dialogMessage="I am Dialog Message"
android:dialogTitle="Dialog Title"
android:hint="e.g 25"
android:icon="#mipmap/ic_launcher"
android:key="fontSize"
android:padding="5dp"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="Changes Font Size of Overall App"
android:title="Change Font Size" />
</PreferenceScreen>
You should be reading value for key fontSize not the name of id field of EditTextPreference. Change your code in your MainActivity like this:
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this);
String str=sp.getString("fontSize","50");
I would like to select few players ( highlighted in purple colors ie Player 1, Player 3 & Player 5) from 'MyPlayerActivity' and add these selected players into a mapbox Map as markers (MainActivity) during on click on 'Add Player' button.
Could someone please help me on how to achieve this ?
Following is my 'MyPlayerActivity' code
public class MyPlayerActivity extends ListActivity {
private static int lastClickId = -1;
// Array of strings storing country names
String[] players = new String[] {
"Player 1",
"Player 2",
"Player 3",
"Player 4",
"Player 5"
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] images = new int[]{
R.drawable.play_1,
R.drawable.play_2,
R.drawable.play_3,
R.drawable.play_4,
R.drawable.play_5
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
final ListView listView = (ListView) findViewById(android.R.id.list);
View headerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
getListView().addHeaderView(headerView);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<6;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("label", "" + players[i]);
hm.put("imgs", Integer.toString(images[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "imgs","label"};
// Ids of views in listview_layout
int[] to = { R.id.imgs,R.id.label};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_view, from, to);
// Getting a reference to listview of main.xml layout file
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout relativeLayoutParent = (RelativeLayout) container;
//LinearLayout linearLayoutParent = (LinearLayout) container;
RelativeLayout relativeLayoutChild = (RelativeLayout) relativeLayoutParent.getChildAt(1);
// Getting the inner Linear Layout
// LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Player TextView
TextView myPlayer = (TextView) relativeLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), myPlayer.getText().toString(), Toast.LENGTH_SHORT).show();
}
};
// Setting the item click listener for the listview
listView.setOnItemClickListener(itemClickListener);
}
}
Following is the list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgs"
android:layout_width="75dp"
android:layout_height="75dp"
android:paddingTop="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="#+id/label"
android:textSize="17sp" >
</TextView>
<Button
android:id="#+id/button2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:text="#string/Add_Player"
android:background="#66ccff"
android:textColor="#ffffff">
</Button>
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Below is the 'MainActivity' code, where I have initialized my map and this is where I would need to add my Player markers and display in mapbox map.
'MainActivity' code where I have initialized my map:
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private MapView mapView;
private MapboxMap map;
private Marker customMarker;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, "token");
final boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
onMapReady(map);
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
Log.i("MapAsync", " is called");
//you need to initialize 'map' with 'mapboxMap';
map = mapboxMap;
//map.setOnMapLongClickListener(new LatLng);
map.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(#NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
map.removeAnnotation(customMarker);
customMarker = null;
}
customMarker = map.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) + ", "
+ new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
}); // Long click Ends here
}
});
}
// Initialize the onMapReady
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.map = mapboxMap;
}
private void addDrawerItems() {
String[] osArray = { "Map", "Players", "Video", "TestPlayer", "My Profile"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// depending on the position in your drawer list change this
switch (position) {
case 0: {
Toast.makeText(MainActivity.this, "Access map", Toast.LENGTH_SHORT).show();
break;
}
case 1:{
Intent intent = new Intent(MainActivity.this, ListPlayerActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "See players arena", Toast.LENGTH_SHORT).show();
break;
}
case 2:{
Intent appIntent = new Intent(MainActivity.this, PlayYoutubeActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "See Video", Toast.LENGTH_SHORT).show();
break;
}
case 3:{
Intent appIntent = new Intent(MainActivity.this, MyPlayerActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "Test to see my players", Toast.LENGTH_SHORT).show();
break;
}
default:
break;
}
Toast.makeText(MainActivity.this, "More details to follow", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public class TelemetryServiceNotConfiguredException extends RuntimeException {
public TelemetryServiceNotConfiguredException() {
super("\nTelemetryService is not configured in your applications AndroidManifest.xml. " +
"\nPlease add \"com.mapbox.mapboxsdk.telemetry.TelemetryService\" service in your applications AndroidManifest.xml" +
"\nFor an example visit For more information visit https://www.mapbox.com/android-sdk/.");
}
}
}
To add a marker to the map you can use this snippet:
mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(<position of player>)));
If the listview and map are in separate activities, you can pass the selected player information to the map activity using an intent. Is this what you were looking for?
I am trying to attain Tab feature using simple Buttons
What is happening now::
Click on Button1 ----> F1 Activity is displayed
Click on button1 (again) ---- > F2 Activity is isplayed
Click on Button1 (third time) -----> F1 Activity is Displayed
again
-
Similarly with Button2 w.r.t G1 & G2 activities
FragmentDemo.java
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
case R.id.button2:
state = !state;
if (state) {
addFragment(new G2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new G1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}
F1.java
public class F1 extends Fragment {
Context c;
View v;
public F1(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f1, container, false);
return v;
}
}
F2.java
public class F2 extends Fragment {
Context c;
View v;
public F2(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f2, container, false);
return v;
}
}
Similarly for G1 & G2
activity_fragment_demo.xml
<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:orientation="vertical"
tools:context=".FragmentDemo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2" />
</LinearLayout>
<LinearLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
OUTPUT::
Clearly we can see that, when i start the project i come to blank screen ..... A default activity is not displayed. As it does in Tabs
How can i make sure a default activity say F1 be already be present when i load the project
Like this ::
Any ideas
What changes should i need to make in the code
Hope i am clear
Your Layout activity_fragment_demo looks good so I will use that. The LinearLayout with id simple_fragment will be the container that holds the fragment's view
So lets say that the fragment F1 represents your first Tab and the fragment F2 represents your second tab.
So three methods that you should have are.
The following method adds each fragment to the activity and has to be called for both F1 and F2 in the activity's onCreate
public void addFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, fragment);
}
The following method essentially shows a fragment.I am not sure about the behind workings of attach but it can be seen as View.VISIBLE
public void attachFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportManager().beginTransaction();
ft.attach(fragment).commit();
}
The following method essentially hides a fragment.I am not sure about the behind workings of detach but it can be seen as View.GONE
public void attachFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportManager().beginTransaction();
ft.detach(fragment).commit();
}
Your Activity's onCreate method
public void onCreate()
{
//Create all your fragments here eg F1 f1 = new F1(); etc
//For whatever fragment you have created you should call the method addFragment
//Now depending on what fragment you want shown by default you should call attachFragment or detachFragment. eg. if F1 has to be shown by default
attachFragment(F1);
detachFragment(F2) //and all otherfragment you want hidden by default
//Set the listeners for the buttons
//The purpose of the next two lines is to store the current state of the buttons. Since F1 is attached to button1 and it is currently being shown we set the tag to "clicked"
//and button2 tag has been set to notClicked
button1.setTag("clicked");
button2.setTag("notClicked");
}
Inside the onClickListener for your buttons
OnClickListener onTabButtonClickListener = new OnClickListener()
{
public void onClick(View view)
{
switch(view.getId)
{
case R.id.button1
{
if(button1.getTag().equals("clicked"))
{
detachFragment(F2);
attachFragment(F1);
button1.setTag("notClicked");
button2.setTag("clicked");
}
else
{
detachFragment(F2);
attachFragment(F1);
button1.setTag("clicked");
button2.setTag("notClicked");
}
}
case R.id.button2
{
//Same thing as before except opposite
}
}
}
}
And that should work.I am not very good at explaining stuff so feel free to ask any questions you have.
With the suggestion user1950599 in his comment he gave ..... i achieved this
just one line of updating was required
Sharing this might help someone
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
case R.id.button2:
state = !state;
if (state) {
addFragment(new G2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new G1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}